IRCBridgeModule.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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.IO;
  30. using System.Net.Sockets;
  31. using System.Reflection;
  32. using System.Text.RegularExpressions;
  33. using System.Threading;
  34. using libsecondlife;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Environment.Interfaces;
  39. using OpenSim.Region.Environment.Scenes;
  40. namespace OpenSim.Region.Environment.Modules.Avatar.Chat
  41. {
  42. public class IRCBridgeModule : IRegionModule
  43. {
  44. private static readonly ILog m_log =
  45. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. private const int DEBUG_CHANNEL = 2147483647;
  47. private string m_defaultzone = null;
  48. private IRCChatModule m_irc = null;
  49. private Thread m_irc_connector = null;
  50. private string m_last_leaving_user = null;
  51. private string m_last_new_user = null;
  52. private List<Scene> m_scenes = new List<Scene>();
  53. internal object m_syncInit = new object();
  54. internal object m_syncLogout = new object();
  55. private IConfig m_config;
  56. #region IRegionModule Members
  57. public void Initialise(Scene scene, IConfigSource config)
  58. {
  59. try
  60. {
  61. if ((m_config = config.Configs["IRC"]) == null)
  62. {
  63. m_log.InfoFormat("[IRC] module not configured");
  64. return;
  65. }
  66. if (!m_config.GetBoolean("enabled", false))
  67. {
  68. m_log.InfoFormat("[IRC] module disabled in configuration");
  69. return;
  70. }
  71. }
  72. catch (Exception)
  73. {
  74. m_log.Info("[IRC] module not configured");
  75. return;
  76. }
  77. lock (m_syncInit)
  78. {
  79. if (!m_scenes.Contains(scene))
  80. {
  81. m_scenes.Add(scene);
  82. scene.EventManager.OnNewClient += NewClient;
  83. scene.EventManager.OnChatFromWorld += SimChat;
  84. scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
  85. scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
  86. }
  87. try
  88. {
  89. m_defaultzone = config.Configs["IRC"].GetString("fallback_region", "Sim");
  90. }
  91. catch (Exception)
  92. {
  93. }
  94. // setup IRC Relay
  95. if (m_irc == null)
  96. {
  97. m_irc = new IRCChatModule(config);
  98. }
  99. if (m_irc_connector == null)
  100. {
  101. m_irc_connector = new Thread(IRCConnectRun);
  102. m_irc_connector.Name = "IRCConnectorThread";
  103. m_irc_connector.IsBackground = true;
  104. }
  105. m_log.InfoFormat("[IRC] initialized for {0}, nick: {1} ", scene.RegionInfo.RegionName,
  106. m_defaultzone);
  107. }
  108. }
  109. public void PostInitialise()
  110. {
  111. if (null == m_irc || !m_irc.Enabled) return;
  112. try
  113. {
  114. //m_irc.Connect(m_scenes);
  115. if (m_irc_connector == null)
  116. {
  117. m_irc_connector = new Thread(IRCConnectRun);
  118. m_irc_connector.Name = "IRCConnectorThread";
  119. m_irc_connector.IsBackground = true;
  120. }
  121. if (!m_irc_connector.IsAlive)
  122. {
  123. m_irc_connector.Start();
  124. ThreadTracker.Add(m_irc_connector);
  125. }
  126. }
  127. catch (Exception)
  128. {
  129. }
  130. }
  131. public void Close()
  132. {
  133. if (null != m_irc)
  134. {
  135. m_irc.Close();
  136. m_log.Info("[IRC] closed connection to IRC server");
  137. }
  138. }
  139. public string Name
  140. {
  141. get { return "IRCBridgeModule"; }
  142. }
  143. public bool IsSharedModule
  144. {
  145. get { return true; }
  146. }
  147. #endregion
  148. #region ISimChat Members
  149. public void SimChat(Object sender, ChatFromViewerArgs e)
  150. {
  151. // We only want to relay stuff on channel 0
  152. if (e.Channel != 0) return;
  153. if (e.Message.Length == 0) return;
  154. // not interested in our own babblings
  155. if (m_irc.Equals(sender)) return;
  156. ScenePresence avatar = null;
  157. Scene scene = (Scene)e.Scene;
  158. if (scene == null)
  159. scene = m_scenes[0];
  160. // Filled in since it's easier than rewriting right now.
  161. string fromName = e.From;
  162. if (e.Sender != null)
  163. {
  164. avatar = scene.GetScenePresence(e.Sender.AgentId);
  165. }
  166. if (avatar != null)
  167. {
  168. fromName = avatar.Firstname + " " + avatar.Lastname;
  169. }
  170. // Try to reconnect to server if not connected
  171. if (m_irc.Enabled && !m_irc.Connected)
  172. {
  173. // In a non-blocking way. Eventually the connector will get it started
  174. try
  175. {
  176. if (m_irc_connector == null)
  177. {
  178. m_irc_connector = new Thread(IRCConnectRun);
  179. m_irc_connector.Name = "IRCConnectorThread";
  180. m_irc_connector.IsBackground = true;
  181. }
  182. if (!m_irc_connector.IsAlive)
  183. {
  184. m_irc_connector.Start();
  185. ThreadTracker.Add(m_irc_connector);
  186. }
  187. }
  188. catch (Exception)
  189. {
  190. }
  191. }
  192. if (e.Message.StartsWith("/me ") && (null != avatar))
  193. e.Message = String.Format("{0} {1}", fromName, e.Message.Substring(4));
  194. // this is to keep objects from talking to IRC
  195. if (m_irc.Connected && (avatar != null))
  196. m_irc.PrivMsg(fromName, scene.RegionInfo.RegionName, e.Message);
  197. }
  198. #endregion
  199. public void NewClient(IClientAPI client)
  200. {
  201. try
  202. {
  203. string clientName = String.Format("{0} {1}", client.FirstName, client.LastName);
  204. client.OnChatFromViewer += SimChat;
  205. client.OnLogout += ClientLoggedOut;
  206. client.OnConnectionClosed += ClientLoggedOut;
  207. if (clientName != m_last_new_user)
  208. {
  209. if ((m_irc.Enabled) && (m_irc.Connected))
  210. {
  211. m_log.DebugFormat("[IRC] {0} logging on", clientName);
  212. m_irc.PrivMsg(m_irc.Nick, "Sim",
  213. String.Format("notices {0} logging on", clientName));
  214. }
  215. m_last_new_user = clientName;
  216. }
  217. }
  218. catch (Exception ex)
  219. {
  220. m_log.Error("[IRC]: NewClient exception trap:" + ex.ToString());
  221. }
  222. }
  223. public void OnMakeRootAgent(ScenePresence presence)
  224. {
  225. try
  226. {
  227. if ((m_irc.Enabled) && (m_irc.Connected))
  228. {
  229. string regionName = presence.Scene.RegionInfo.RegionName;
  230. string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname);
  231. m_log.DebugFormat("[IRC] noticing {0} in {1}", clientName, regionName);
  232. m_irc.PrivMsg(m_irc.Nick, "Sim", String.Format("notices {0} in {1}", clientName, regionName));
  233. }
  234. }
  235. catch (Exception)
  236. {
  237. }
  238. }
  239. public void OnMakeChildAgent(ScenePresence presence)
  240. {
  241. try
  242. {
  243. if ((m_irc.Enabled) && (m_irc.Connected))
  244. {
  245. string regionName = presence.Scene.RegionInfo.RegionName;
  246. string clientName = String.Format("{0} {1}", presence.Firstname, presence.Lastname);
  247. m_log.DebugFormat("[IRC] noticing {0} in {1}", clientName, regionName);
  248. m_irc.PrivMsg(m_irc.Nick, "Sim", String.Format("notices {0} left {1}", clientName, regionName));
  249. }
  250. }
  251. catch (Exception)
  252. {
  253. }
  254. }
  255. public void ClientLoggedOut(IClientAPI client)
  256. {
  257. lock (m_syncLogout)
  258. {
  259. try
  260. {
  261. if ((m_irc.Enabled) && (m_irc.Connected))
  262. {
  263. string clientName = String.Format("{0} {1}", client.FirstName, client.LastName);
  264. // handles simple case. May not work for hundred connecting in per second.
  265. // and the NewClients calles getting interleved
  266. // but filters out multiple reports
  267. if (clientName != m_last_leaving_user)
  268. {
  269. Console.WriteLine("Avatar was seen logging out.");
  270. //Console.ReadLine();
  271. Console.WriteLine();
  272. m_last_leaving_user = clientName;
  273. m_irc.PrivMsg(m_irc.Nick, "Sim", String.Format("notices {0} logging out", clientName));
  274. m_log.InfoFormat("[IRC]: {0} logging out", clientName);
  275. }
  276. if (m_last_new_user == clientName)
  277. m_last_new_user = null;
  278. }
  279. }
  280. catch (Exception ex)
  281. {
  282. m_log.Error("[IRC]: ClientLoggedOut exception trap:" + ex.ToString());
  283. }
  284. }
  285. }
  286. // if IRC is enabled then just keep trying using a monitor thread
  287. public void IRCConnectRun()
  288. {
  289. while (m_irc.Enabled)
  290. {
  291. if (!m_irc.Connected)
  292. {
  293. m_irc.Connect(m_scenes);
  294. }
  295. Thread.Sleep(15000);
  296. }
  297. }
  298. }
  299. internal class IRCChatModule
  300. {
  301. #region ErrorReplies enum
  302. public enum ErrorReplies
  303. {
  304. NotRegistered = 451, // ":You have not registered"
  305. NicknameInUse = 433 // "<nick> :Nickname is already in use"
  306. }
  307. #endregion
  308. #region Replies enum
  309. public enum Replies
  310. {
  311. MotdStart = 375, // ":- <server> Message of the day - "
  312. Motd = 372, // ":- <text>"
  313. EndOfMotd = 376 // ":End of /MOTD command"
  314. }
  315. #endregion
  316. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  317. private Thread listener;
  318. private string m_basenick = null;
  319. private string m_channel = null;
  320. private bool m_nrnick = false;
  321. private bool m_connected = false;
  322. private bool m_enabled = false;
  323. private List<Scene> m_last_scenes = null;
  324. private string m_nick = null;
  325. private uint m_port = 6668;
  326. private string m_privmsgformat = "PRIVMSG {0} :<{1} in {2}>: {3}";
  327. private StreamReader m_reader;
  328. private List<Scene> m_scenes = null;
  329. private string m_server = null;
  330. private NetworkStream m_stream;
  331. internal object m_syncConnect = new object();
  332. private TcpClient m_tcp;
  333. private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot";
  334. private StreamWriter m_writer;
  335. private Thread pingSender;
  336. public IRCChatModule(IConfigSource config)
  337. {
  338. m_nick = "OSimBot" + Util.RandomClass.Next(1, 99);
  339. m_tcp = null;
  340. m_writer = null;
  341. m_reader = null;
  342. // configuration in OpenSim.ini
  343. // [IRC]
  344. // server = chat.freenode.net
  345. // nick = OSimBot_mysim
  346. // nicknum = true
  347. // ;nicknum set to true appends a 2 digit random number to the nick
  348. // ;username = USER OpenSimBot 8 * :I'm a OpenSim to irc bot
  349. // ; username is the IRC command line sent
  350. // ; USER <irc_user> <visible=8,invisible=0> * : <IRC_realname>
  351. // channel = #opensim-regions
  352. // port = 6667
  353. // ;MSGformat fields : 0=botnick, 1=user, 2=region, 3=message
  354. // ;for <bot>:<user in region> :<message>
  355. // ;msgformat = "PRIVMSG {0} :<{1} in {2}>: {3}"
  356. // ;for <bot>:<message> - <user of region> :
  357. // ;msgformat = "PRIVMSG {0} : {3} - {1} of {2}"
  358. // ;for <bot>:<message> - from <user> :
  359. // ;msgformat = "PRIVMSG {0} : {3} - from {1}"
  360. // Traps I/O disconnects so it does not crash the sim
  361. // Trys to reconnect if disconnected and someone says something
  362. // Tells IRC server "QUIT" when doing a close (just to be nice)
  363. // Default port back to 6667
  364. try
  365. {
  366. m_server = config.Configs["IRC"].GetString("server");
  367. m_nick = config.Configs["IRC"].GetString("nick");
  368. m_basenick = m_nick;
  369. m_nrnick = config.Configs["IRC"].GetBoolean("nicknum", true);
  370. m_channel = config.Configs["IRC"].GetString("channel");
  371. m_port = (uint)config.Configs["IRC"].GetInt("port", (int)m_port);
  372. m_user = config.Configs["IRC"].GetString("username", m_user);
  373. m_privmsgformat = config.Configs["IRC"].GetString("msgformat", m_privmsgformat);
  374. if (m_server != null && m_nick != null && m_channel != null)
  375. {
  376. if (m_nrnick == true)
  377. {
  378. m_nick = m_nick + Util.RandomClass.Next(1, 99);
  379. }
  380. m_enabled = true;
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. m_log.Info("[IRC]: Incomplete IRC configuration, skipping IRC bridge configuration");
  386. m_log.DebugFormat("[IRC] Incomplete IRC configuration: {0}", ex.ToString());
  387. }
  388. }
  389. public bool Enabled
  390. {
  391. get { return m_enabled; }
  392. }
  393. public bool Connected
  394. {
  395. get { return m_connected; }
  396. }
  397. public string Nick
  398. {
  399. get { return m_nick; }
  400. }
  401. public bool Connect(List<Scene> scenes)
  402. {
  403. lock (m_syncConnect)
  404. {
  405. try
  406. {
  407. if (m_connected) return true;
  408. m_scenes = scenes;
  409. if (m_last_scenes == null)
  410. {
  411. m_last_scenes = scenes;
  412. }
  413. m_tcp = new TcpClient(m_server, (int)m_port);
  414. m_log.Info("[IRC]: Connecting...");
  415. m_stream = m_tcp.GetStream();
  416. m_log.Info("[IRC]: Connected to " + m_server);
  417. m_reader = new StreamReader(m_stream);
  418. m_writer = new StreamWriter(m_stream);
  419. pingSender = new Thread(new ThreadStart(PingRun));
  420. pingSender.Name = "PingSenderThread";
  421. pingSender.IsBackground = true;
  422. pingSender.Start();
  423. ThreadTracker.Add(pingSender);
  424. listener = new Thread(new ThreadStart(ListenerRun));
  425. listener.Name = "IRCChatModuleListenerThread";
  426. listener.IsBackground = true;
  427. listener.Start();
  428. ThreadTracker.Add(listener);
  429. m_writer.WriteLine(m_user);
  430. m_writer.Flush();
  431. m_writer.WriteLine(String.Format("NICK {0}", m_nick));
  432. m_writer.Flush();
  433. m_writer.WriteLine(String.Format("JOIN {0}", m_channel));
  434. m_writer.Flush();
  435. m_log.Info("[IRC]: Connection fully established");
  436. m_connected = true;
  437. }
  438. catch (Exception e)
  439. {
  440. m_log.ErrorFormat("[IRC] cannot connect to {0}:{1}: {2}",
  441. m_server, m_port, e.Message);
  442. }
  443. return m_connected;
  444. }
  445. }
  446. public void Reconnect()
  447. {
  448. m_connected = false;
  449. try
  450. {
  451. listener.Abort();
  452. pingSender.Abort();
  453. m_writer.Close();
  454. m_reader.Close();
  455. m_tcp.Close();
  456. }
  457. catch (Exception)
  458. {
  459. }
  460. if (m_enabled)
  461. {
  462. Connect(m_last_scenes);
  463. }
  464. }
  465. public void PrivMsg(string from, string region, string msg)
  466. {
  467. // One message to the IRC server
  468. try
  469. {
  470. m_writer.WriteLine(m_privmsgformat, m_channel, from, region, msg);
  471. m_writer.Flush();
  472. m_log.InfoFormat("[IRC]: PrivMsg {0} in {1}: {2}", from, region, msg);
  473. }
  474. catch (IOException)
  475. {
  476. m_log.Error("[IRC]: Disconnected from IRC server.(PrivMsg)");
  477. Reconnect();
  478. }
  479. catch (Exception ex)
  480. {
  481. m_log.ErrorFormat("[IRC]: PrivMsg exception trap: {0}", ex.ToString());
  482. }
  483. }
  484. private Dictionary<string, string> ExtractMsg(string input)
  485. {
  486. //examines IRC commands and extracts any private messages
  487. // which will then be reboadcast in the Sim
  488. m_log.Info("[IRC]: ExtractMsg: " + input);
  489. Dictionary<string, string> result = null;
  490. //string regex = @":(?<nick>\w*)!~(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)";
  491. string regex = @":(?<nick>[\w-]*)!(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)";
  492. Regex RE = new Regex(regex, RegexOptions.Multiline);
  493. MatchCollection matches = RE.Matches(input);
  494. // Get some direct matches $1 $4 is a
  495. if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5))
  496. {
  497. m_log.Info("[IRC]: Number of matches: " + matches.Count);
  498. if (matches.Count > 0)
  499. {
  500. m_log.Info("[IRC]: Number of groups: " + matches[0].Groups.Count);
  501. }
  502. return null;
  503. }
  504. result = new Dictionary<string, string>();
  505. result.Add("nick", matches[0].Groups[1].Value);
  506. result.Add("user", matches[0].Groups[2].Value);
  507. result.Add("channel", matches[0].Groups[3].Value);
  508. result.Add("msg", matches[0].Groups[4].Value);
  509. return result;
  510. }
  511. public void PingRun()
  512. {
  513. // IRC keep alive thread
  514. // send PING ever 15 seconds
  515. while (m_enabled)
  516. {
  517. try
  518. {
  519. if (m_connected == true)
  520. {
  521. m_writer.WriteLine(String.Format("PING :{0}", m_server));
  522. m_writer.Flush();
  523. Thread.Sleep(15000);
  524. }
  525. }
  526. catch (IOException)
  527. {
  528. if (m_enabled)
  529. {
  530. m_log.Error("[IRC]: Disconnected from IRC server.(PingRun)");
  531. Reconnect();
  532. }
  533. }
  534. catch (Exception ex)
  535. {
  536. m_log.ErrorFormat("[IRC]: PingRun exception trap: {0}\n{1}", ex.ToString(), ex.StackTrace);
  537. }
  538. }
  539. }
  540. public void ListenerRun()
  541. {
  542. string inputLine;
  543. LLVector3 pos = new LLVector3(128, 128, 20);
  544. while (m_enabled)
  545. {
  546. try
  547. {
  548. while ((m_connected == true) && ((inputLine = m_reader.ReadLine()) != null))
  549. {
  550. // Console.WriteLine(inputLine);
  551. if (inputLine.Contains(m_channel))
  552. {
  553. Dictionary<string, string> data = ExtractMsg(inputLine);
  554. // Any chat ???
  555. if (data != null)
  556. {
  557. ChatFromViewerArgs c = new ChatFromViewerArgs();
  558. c.Message = data["msg"];
  559. c.Type = ChatTypeEnum.Say;
  560. c.Channel = 0;
  561. c.Position = pos;
  562. c.From = data["nick"];
  563. c.Sender = null;
  564. c.SenderUUID = LLUUID.Zero;
  565. // is message "\001ACTION foo
  566. // bar\001"? -> "/me foo bar"
  567. if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION"))
  568. c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9));
  569. foreach (Scene scene in m_scenes)
  570. {
  571. c.Scene = scene;
  572. scene.EventManager.TriggerOnChatBroadcast(this, c);
  573. }
  574. }
  575. Thread.Sleep(150);
  576. continue;
  577. }
  578. ProcessIRCCommand(inputLine);
  579. Thread.Sleep(150);
  580. }
  581. }
  582. catch (IOException)
  583. {
  584. if (m_enabled)
  585. {
  586. m_log.Error("[IRC]: ListenerRun IOException. Disconnected from IRC server ??? (ListenerRun)");
  587. Reconnect();
  588. }
  589. }
  590. catch (Exception ex)
  591. {
  592. m_log.ErrorFormat("[IRC]: ListenerRun exception trap: {0}\n{1}", ex.ToString(), ex.StackTrace);
  593. }
  594. }
  595. }
  596. public void BroadcastSim(string sender, string format, params string[] args)
  597. {
  598. try
  599. {
  600. ChatFromViewerArgs c = new ChatFromViewerArgs();
  601. c.From = sender;
  602. c.Message = String.Format(format, args);
  603. c.Type = ChatTypeEnum.Say;
  604. c.Channel = 0;
  605. c.Position = new LLVector3(128, 128, 20);
  606. c.Sender = null;
  607. c.SenderUUID = LLUUID.Zero;
  608. foreach (Scene m_scene in m_scenes)
  609. {
  610. c.Scene = m_scene;
  611. m_scene.EventManager.TriggerOnChatBroadcast(this, c);
  612. }
  613. }
  614. catch (Exception ex) // IRC gate should not crash Sim
  615. {
  616. m_log.ErrorFormat("[IRC]: BroadcastSim Exception Trap: {0}\n{1}", ex.ToString(), ex.StackTrace);
  617. }
  618. }
  619. public void ProcessIRCCommand(string command)
  620. {
  621. //m_log.Info("[IRC]: ProcessIRCCommand:" + command);
  622. string[] commArgs = new string[command.Split(' ').Length];
  623. string c_server = m_server;
  624. commArgs = command.Split(' ');
  625. if (commArgs[0].Substring(0, 1) == ":")
  626. {
  627. commArgs[0] = commArgs[0].Remove(0, 1);
  628. }
  629. if (commArgs[1] == "002")
  630. {
  631. // fetch the correct servername
  632. // ex: irc.freenode.net -> brown.freenode.net/kornbluth.freenode.net/...
  633. // irc.bluewin.ch -> irc1.bluewin.ch/irc2.bluewin.ch
  634. c_server = (commArgs[6].Split('['))[0];
  635. m_server = c_server;
  636. }
  637. if (commArgs[0] == "ERROR")
  638. {
  639. m_log.ErrorFormat("[IRC]: IRC SERVER ERROR: {0}", command);
  640. }
  641. if (commArgs[0] == "PING")
  642. {
  643. string p_reply = "";
  644. for (int i = 1; i < commArgs.Length; i++)
  645. {
  646. p_reply += commArgs[i] + " ";
  647. }
  648. m_writer.WriteLine(String.Format("PONG {0}", p_reply));
  649. m_writer.Flush();
  650. }
  651. else if (commArgs[0] == c_server)
  652. {
  653. // server message
  654. try
  655. {
  656. Int32 commandCode = Int32.Parse(commArgs[1]);
  657. switch (commandCode)
  658. {
  659. case (int)ErrorReplies.NicknameInUse:
  660. // Gen a new name
  661. m_nick = m_basenick + Util.RandomClass.Next(1, 99);
  662. m_log.ErrorFormat("[IRC]: IRC SERVER reports NicknameInUse, trying {0}", m_nick);
  663. // Retry
  664. m_writer.WriteLine(String.Format("NICK {0}", m_nick));
  665. m_writer.Flush();
  666. m_writer.WriteLine(String.Format("JOIN {0}", m_channel));
  667. m_writer.Flush();
  668. break;
  669. case (int)ErrorReplies.NotRegistered:
  670. break;
  671. case (int)Replies.EndOfMotd:
  672. break;
  673. }
  674. }
  675. catch (Exception)
  676. {
  677. }
  678. }
  679. else
  680. {
  681. // Normal message
  682. string commAct = commArgs[1];
  683. switch (commAct)
  684. {
  685. case "JOIN":
  686. eventIrcJoin(commArgs);
  687. break;
  688. case "PART":
  689. eventIrcPart(commArgs);
  690. break;
  691. case "MODE":
  692. eventIrcMode(commArgs);
  693. break;
  694. case "NICK":
  695. eventIrcNickChange(commArgs);
  696. break;
  697. case "KICK":
  698. eventIrcKick(commArgs);
  699. break;
  700. case "QUIT":
  701. eventIrcQuit(commArgs);
  702. break;
  703. case "PONG":
  704. break; // that's nice
  705. }
  706. }
  707. }
  708. public void eventIrcJoin(string[] commArgs)
  709. {
  710. string IrcChannel = commArgs[2];
  711. if (IrcChannel.StartsWith(":"))
  712. IrcChannel = IrcChannel.Substring(1);
  713. string IrcUser = commArgs[0].Split('!')[0];
  714. BroadcastSim(IrcUser, "/me joins {0}", IrcChannel);
  715. }
  716. public void eventIrcPart(string[] commArgs)
  717. {
  718. string IrcChannel = commArgs[2];
  719. string IrcUser = commArgs[0].Split('!')[0];
  720. BroadcastSim(IrcUser, "/me parts {0}", IrcChannel);
  721. }
  722. public void eventIrcMode(string[] commArgs)
  723. {
  724. string UserMode = "";
  725. for (int i = 3; i < commArgs.Length; i++)
  726. {
  727. UserMode += commArgs[i] + " ";
  728. }
  729. if (UserMode.Substring(0, 1) == ":")
  730. {
  731. UserMode = UserMode.Remove(0, 1);
  732. }
  733. }
  734. public void eventIrcNickChange(string[] commArgs)
  735. {
  736. string UserOldNick = commArgs[0].Split('!')[0];
  737. string UserNewNick = commArgs[2].Remove(0, 1);
  738. BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick);
  739. }
  740. public void eventIrcKick(string[] commArgs)
  741. {
  742. string UserKicker = commArgs[0].Split('!')[0];
  743. string UserKicked = commArgs[3];
  744. string IrcChannel = commArgs[2];
  745. string KickMessage = "";
  746. for (int i = 4; i < commArgs.Length; i++)
  747. {
  748. KickMessage += commArgs[i] + " ";
  749. }
  750. BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage);
  751. if (UserKicked == m_nick)
  752. {
  753. BroadcastSim(m_nick, "Hey, that was me!!!");
  754. }
  755. }
  756. public void eventIrcQuit(string[] commArgs)
  757. {
  758. string IrcUser = commArgs[0].Split('!')[0];
  759. string QuitMessage = "";
  760. for (int i = 2; i < commArgs.Length; i++)
  761. {
  762. QuitMessage += commArgs[i] + " ";
  763. }
  764. BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage);
  765. }
  766. public void Close()
  767. {
  768. m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing",
  769. m_nick, m_channel, m_server));
  770. m_writer.Flush();
  771. m_connected = false;
  772. m_enabled = false;
  773. // listener.Abort();
  774. // pingSender.Abort();
  775. m_writer.Close();
  776. m_reader.Close();
  777. m_tcp.Close();
  778. }
  779. }
  780. }