IRCConnector.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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.Timers;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Net.Sockets;
  32. using System.Reflection;
  33. using System.Text.RegularExpressions;
  34. using System.Threading;
  35. using OpenMetaverse;
  36. using log4net;
  37. using Nini.Config;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Monitoring;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. namespace OpenSim.Region.OptionalModules.Avatar.Chat
  43. {
  44. public class IRCConnector
  45. {
  46. #region Global (static) state
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. // Local constants
  49. // This computation is not the real region center if the region is larger than 256.
  50. // This computation isn't fixed because there is not a handle back to the region.
  51. private static readonly Vector3 CenterOfRegion = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 20);
  52. private static readonly char[] CS_SPACE = { ' ' };
  53. private const int WD_INTERVAL = 1000; // base watchdog interval
  54. private static int PING_PERIOD = 15; // WD intervals per PING
  55. private static int ICCD_PERIOD = 10; // WD intervals between Connects
  56. private static int L_TIMEOUT = 25; // Login time out interval
  57. private static int _idk_ = 0; // core connector identifier
  58. private static int _pdk_ = 0; // ping interval counter
  59. private static int _icc_ = ICCD_PERIOD; // IRC connect counter
  60. // List of configured connectors
  61. private static List<IRCConnector> m_connectors = new List<IRCConnector>();
  62. // Watchdog state
  63. private static System.Timers.Timer m_watchdog = null;
  64. // The watch-dog gets started as soon as the class is instantiated, and
  65. // ticks once every second (WD_INTERVAL)
  66. static IRCConnector()
  67. {
  68. m_log.DebugFormat("[IRC-Connector]: Static initialization started");
  69. m_watchdog = new System.Timers.Timer(WD_INTERVAL);
  70. m_watchdog.Elapsed += new ElapsedEventHandler(WatchdogHandler);
  71. m_watchdog.AutoReset = true;
  72. m_watchdog.Start();
  73. m_log.DebugFormat("[IRC-Connector]: Static initialization complete");
  74. }
  75. #endregion
  76. #region Instance state
  77. // Connector identity
  78. internal int idn = _idk_++;
  79. // How many regions depend upon this connection
  80. // This count is updated by the ChannelState object and reflects the sum
  81. // of the region clients associated with the set of associated channel
  82. // state instances. That's why it cannot be managed here.
  83. internal int depends = 0;
  84. // This variable counts the number of resets that have been performed
  85. // on the connector. When a listener thread terminates, it checks to
  86. // see of the reset count has changed before it schedules another
  87. // reset.
  88. internal int m_resetk = 0;
  89. private Object msyncConnect = new Object();
  90. internal bool m_randomizeNick = true; // add random suffix
  91. internal string m_baseNick = null; // base name for randomizing
  92. internal string m_nick = null; // effective nickname
  93. public string Nick // Public property
  94. {
  95. get { return m_nick; }
  96. set { m_nick = value; }
  97. }
  98. private bool m_enabled = false; // connector enablement
  99. public bool Enabled
  100. {
  101. get { return m_enabled; }
  102. }
  103. private bool m_connected = false; // connection status
  104. private bool m_pending = false; // login disposition
  105. private int m_timeout = L_TIMEOUT; // login timeout counter
  106. public bool Connected
  107. {
  108. get { return m_connected; }
  109. }
  110. private string m_ircChannel; // associated channel id
  111. public string IrcChannel
  112. {
  113. get { return m_ircChannel; }
  114. set { m_ircChannel = value; }
  115. }
  116. private uint m_port = 6667; // session port
  117. public uint Port
  118. {
  119. get { return m_port; }
  120. set { m_port = value; }
  121. }
  122. private string m_server = null; // IRC server name
  123. public string Server
  124. {
  125. get { return m_server; }
  126. set { m_server = value; }
  127. }
  128. private string m_password = null;
  129. public string Password
  130. {
  131. get { return m_password; }
  132. set { m_password = value; }
  133. }
  134. private string m_user = "USER OpenSimBot 8 * :I'm an OpenSim to IRC bot";
  135. public string User
  136. {
  137. get { return m_user; }
  138. }
  139. // Network interface
  140. private TcpClient m_tcp;
  141. private NetworkStream m_stream = null;
  142. private StreamReader m_reader;
  143. private StreamWriter m_writer;
  144. // Channel characteristic info (if available)
  145. internal string usermod = String.Empty;
  146. internal string chanmod = String.Empty;
  147. internal string version = String.Empty;
  148. internal bool motd = false;
  149. #endregion
  150. #region connector instance management
  151. internal IRCConnector(ChannelState cs)
  152. {
  153. // Prepare network interface
  154. m_tcp = null;
  155. m_writer = null;
  156. m_reader = null;
  157. // Setup IRC session parameters
  158. m_server = cs.Server;
  159. m_password = cs.Password;
  160. m_baseNick = cs.BaseNickname;
  161. m_randomizeNick = cs.RandomizeNickname;
  162. m_ircChannel = cs.IrcChannel;
  163. m_port = cs.Port;
  164. m_user = cs.User;
  165. if (m_watchdog == null)
  166. {
  167. // Non-differentiating
  168. ICCD_PERIOD = cs.ConnectDelay;
  169. PING_PERIOD = cs.PingDelay;
  170. // Smaller values are not reasonable
  171. if (ICCD_PERIOD < 5)
  172. ICCD_PERIOD = 5;
  173. if (PING_PERIOD < 5)
  174. PING_PERIOD = 5;
  175. _icc_ = ICCD_PERIOD; // get started right away!
  176. }
  177. // The last line of defense
  178. if (m_server == null || m_baseNick == null || m_ircChannel == null || m_user == null)
  179. throw new Exception("Invalid connector configuration");
  180. // Generate an initial nickname
  181. if (m_randomizeNick)
  182. m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
  183. else
  184. m_nick = m_baseNick;
  185. m_log.InfoFormat("[IRC-Connector-{0}]: Initialization complete", idn);
  186. }
  187. ~IRCConnector()
  188. {
  189. m_watchdog.Stop();
  190. Close();
  191. }
  192. // Mark the connector as connectable. Harmless if already enabled.
  193. public void Open()
  194. {
  195. if (!m_enabled)
  196. {
  197. if (!Connected)
  198. {
  199. Connect();
  200. }
  201. lock (m_connectors)
  202. m_connectors.Add(this);
  203. m_enabled = true;
  204. }
  205. }
  206. // Only close the connector if the dependency count is zero.
  207. public void Close()
  208. {
  209. m_log.InfoFormat("[IRC-Connector-{0}] Closing", idn);
  210. lock (msyncConnect)
  211. {
  212. if ((depends == 0) && Enabled)
  213. {
  214. m_enabled = false;
  215. if (Connected)
  216. {
  217. m_log.DebugFormat("[IRC-Connector-{0}] Closing interface", idn);
  218. // Cleanup the IRC session
  219. try
  220. {
  221. m_writer.WriteLine(String.Format("QUIT :{0} to {1} wormhole to {2} closing",
  222. m_nick, m_ircChannel, m_server));
  223. m_writer.Flush();
  224. }
  225. catch (Exception) { }
  226. m_connected = false;
  227. try { m_writer.Close(); }
  228. catch (Exception) { }
  229. try { m_reader.Close(); }
  230. catch (Exception) { }
  231. try { m_stream.Close(); }
  232. catch (Exception) { }
  233. try { m_tcp.Close(); }
  234. catch (Exception) { }
  235. }
  236. lock (m_connectors)
  237. m_connectors.Remove(this);
  238. }
  239. }
  240. m_log.InfoFormat("[IRC-Connector-{0}] Closed", idn);
  241. }
  242. #endregion
  243. #region session management
  244. // Connect to the IRC server. A connector should always be connected, once enabled
  245. public void Connect()
  246. {
  247. if (!m_enabled)
  248. return;
  249. // Delay until next WD cycle if this is too close to the last start attempt
  250. if(_icc_ < ICCD_PERIOD)
  251. return;
  252. m_log.DebugFormat("[IRC-Connector-{0}]: Connection request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
  253. _icc_ = 0;
  254. lock (msyncConnect)
  255. {
  256. try
  257. {
  258. if (m_connected) return;
  259. m_connected = true;
  260. m_pending = true;
  261. m_timeout = L_TIMEOUT;
  262. m_tcp = new TcpClient(m_server, (int)m_port);
  263. m_stream = m_tcp.GetStream();
  264. m_reader = new StreamReader(m_stream);
  265. m_writer = new StreamWriter(m_stream);
  266. m_log.InfoFormat("[IRC-Connector-{0}]: Connected to {1}:{2}", idn, m_server, m_port);
  267. WorkManager.StartThread(ListenerRun, "IRCConnectionListenerThread", ThreadPriority.Normal, true, false);
  268. // This is the message order recommended by RFC 2812
  269. if (m_password != null)
  270. m_writer.WriteLine(String.Format("PASS {0}", m_password));
  271. m_writer.WriteLine(String.Format("NICK {0}", m_nick));
  272. m_writer.Flush();
  273. m_writer.WriteLine(m_user);
  274. m_writer.Flush();
  275. }
  276. catch (Exception e)
  277. {
  278. m_log.ErrorFormat("[IRC-Connector-{0}] cannot connect {1} to {2}:{3}: {4}",
  279. idn, m_nick, m_server, m_port, e.Message);
  280. // It might seem reasonable to reset connected and pending status here
  281. // Seeing as we know that the login has failed, but if we do that, then
  282. // connection will be retried each time the interconnection interval
  283. // expires. By leaving them as they are, the connection will be retried
  284. // when the login timeout expires. Which is preferred.
  285. }
  286. }
  287. return;
  288. }
  289. // Reconnect is used to force a re-cycle of the IRC connection. Should generally
  290. // be a transparent event
  291. public void Reconnect()
  292. {
  293. m_log.DebugFormat("[IRC-Connector-{0}]: Reconnect request for {1} on {2}:{3}", idn, m_nick, m_server, m_ircChannel);
  294. // Don't do this if a Connect is in progress...
  295. lock (msyncConnect)
  296. {
  297. if (m_connected)
  298. {
  299. m_log.InfoFormat("[IRC-Connector-{0}] Resetting connector", idn);
  300. // Mark as disconnected. This will allow the listener thread
  301. // to exit if still in-flight.
  302. // The listener thread is not aborted - it *might* actually be
  303. // the thread that is running the Reconnect! Instead just close
  304. // the socket and it will disappear of its own accord, once this
  305. // processing is completed.
  306. try { m_writer.Close(); }
  307. catch (Exception) { }
  308. try { m_reader.Close(); }
  309. catch (Exception) { }
  310. try { m_tcp.Close(); }
  311. catch (Exception) { }
  312. m_connected = false;
  313. m_pending = false;
  314. m_resetk++;
  315. }
  316. }
  317. Connect();
  318. }
  319. #endregion
  320. #region Outbound (to-IRC) message handlers
  321. public void PrivMsg(string pattern, string from, string region, string msg)
  322. {
  323. // m_log.DebugFormat("[IRC-Connector-{0}] PrivMsg to IRC from {1}: <{2}>", idn, from,
  324. // String.Format(pattern, m_ircChannel, from, region, msg));
  325. // One message to the IRC server
  326. try
  327. {
  328. m_writer.WriteLine(pattern, m_ircChannel, from, region, msg);
  329. m_writer.Flush();
  330. // m_log.DebugFormat("[IRC-Connector-{0}]: PrivMsg from {1} in {2}: {3}", idn, from, region, msg);
  331. }
  332. catch (IOException)
  333. {
  334. m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg I/O Error: disconnected from IRC server", idn);
  335. Reconnect();
  336. }
  337. catch (Exception ex)
  338. {
  339. m_log.ErrorFormat("[IRC-Connector-{0}]: PrivMsg exception : {1}", idn, ex.Message);
  340. m_log.Debug(ex);
  341. }
  342. }
  343. public void Send(string msg)
  344. {
  345. // m_log.DebugFormat("[IRC-Connector-{0}] Send to IRC : <{1}>", idn, msg);
  346. try
  347. {
  348. m_writer.WriteLine(msg);
  349. m_writer.Flush();
  350. // m_log.DebugFormat("[IRC-Connector-{0}] Sent command string: {1}", idn, msg);
  351. }
  352. catch (IOException)
  353. {
  354. m_log.ErrorFormat("[IRC-Connector-{0}] Disconnected from IRC server.(Send)", idn);
  355. Reconnect();
  356. }
  357. catch (Exception ex)
  358. {
  359. m_log.ErrorFormat("[IRC-Connector-{0}] Send exception trap: {0}", idn, ex.Message);
  360. m_log.Debug(ex);
  361. }
  362. }
  363. #endregion
  364. public void ListenerRun()
  365. {
  366. string inputLine;
  367. int resetk = m_resetk;
  368. try
  369. {
  370. while (m_enabled && m_connected)
  371. {
  372. if ((inputLine = m_reader.ReadLine()) == null)
  373. throw new Exception("Listener input socket closed");
  374. Watchdog.UpdateThread();
  375. // m_log.Info("[IRCConnector]: " + inputLine);
  376. if (inputLine.Contains("PRIVMSG"))
  377. {
  378. Dictionary<string, string> data = ExtractMsg(inputLine);
  379. // Any chat ???
  380. if (data != null)
  381. {
  382. OSChatMessage c = new OSChatMessage();
  383. c.Message = data["msg"];
  384. c.Type = ChatTypeEnum.Region;
  385. c.Position = CenterOfRegion;
  386. c.From = data["nick"] + "@IRC";
  387. c.Sender = null;
  388. c.SenderUUID = UUID.Zero;
  389. // Is message "\001ACTION foo bar\001"?
  390. // Then change to: "/me foo bar"
  391. if ((1 == c.Message[0]) && c.Message.Substring(1).StartsWith("ACTION"))
  392. c.Message = String.Format("/me {0}", c.Message.Substring(8, c.Message.Length - 9));
  393. ChannelState.OSChat(this, c, false);
  394. }
  395. }
  396. else
  397. {
  398. ProcessIRCCommand(inputLine);
  399. }
  400. }
  401. }
  402. catch (Exception /*e*/)
  403. {
  404. // m_log.ErrorFormat("[IRC-Connector-{0}]: ListenerRun exception trap: {1}", idn, e.Message);
  405. // m_log.Debug(e);
  406. }
  407. // This is potentially circular, but harmless if so.
  408. // The connection is marked as not connected the first time
  409. // through reconnect.
  410. if (m_enabled && (m_resetk == resetk))
  411. Reconnect();
  412. Watchdog.RemoveThread();
  413. }
  414. private Regex RE = new Regex(@":(?<nick>[\w-]*)!(?<user>\S*) PRIVMSG (?<channel>\S+) :(?<msg>.*)",
  415. RegexOptions.Multiline);
  416. private Dictionary<string, string> ExtractMsg(string input)
  417. {
  418. //examines IRC commands and extracts any private messages
  419. // which will then be reboadcast in the Sim
  420. // m_log.InfoFormat("[IRC-Connector-{0}]: ExtractMsg: {1}", idn, input);
  421. Dictionary<string, string> result = null;
  422. MatchCollection matches = RE.Matches(input);
  423. // Get some direct matches $1 $4 is a
  424. if ((matches.Count == 0) || (matches.Count != 1) || (matches[0].Groups.Count != 5))
  425. {
  426. // m_log.Info("[IRCConnector]: Number of matches: " + matches.Count);
  427. // if (matches.Count > 0)
  428. // {
  429. // m_log.Info("[IRCConnector]: Number of groups: " + matches[0].Groups.Count);
  430. // }
  431. return null;
  432. }
  433. result = new Dictionary<string, string>();
  434. result.Add("nick", matches[0].Groups[1].Value);
  435. result.Add("user", matches[0].Groups[2].Value);
  436. result.Add("channel", matches[0].Groups[3].Value);
  437. result.Add("msg", matches[0].Groups[4].Value);
  438. return result;
  439. }
  440. public void BroadcastSim(string sender, string format, params string[] args)
  441. {
  442. try
  443. {
  444. OSChatMessage c = new OSChatMessage();
  445. c.From = sender;
  446. c.Message = String.Format(format, args);
  447. c.Type = ChatTypeEnum.Region; // ChatTypeEnum.Say;
  448. c.Position = CenterOfRegion;
  449. c.Sender = null;
  450. c.SenderUUID = UUID.Zero;
  451. ChannelState.OSChat(this, c, true);
  452. }
  453. catch (Exception ex) // IRC gate should not crash Sim
  454. {
  455. m_log.ErrorFormat("[IRC-Connector-{0}]: BroadcastSim Exception Trap: {1}\n{2}", idn, ex.Message, ex.StackTrace);
  456. }
  457. }
  458. #region IRC Command Handlers
  459. public void ProcessIRCCommand(string command)
  460. {
  461. string[] commArgs;
  462. string c_server = m_server;
  463. string pfx = String.Empty;
  464. string cmd = String.Empty;
  465. string parms = String.Empty;
  466. // ":" indicates that a prefix is present
  467. // There are NEVER more than 17 real
  468. // fields. A parameter that starts with
  469. // ":" indicates that the remainder of the
  470. // line is a single parameter value.
  471. commArgs = command.Split(CS_SPACE, 2);
  472. if (commArgs[0].StartsWith(":"))
  473. {
  474. pfx = commArgs[0].Substring(1);
  475. commArgs = commArgs[1].Split(CS_SPACE, 2);
  476. }
  477. cmd = commArgs[0];
  478. parms = commArgs[1];
  479. // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}>", idn, pfx, cmd);
  480. switch (cmd)
  481. {
  482. // Messages 001-004 are always sent
  483. // following signon.
  484. case "001": // Welcome ...
  485. case "002": // Server information
  486. case "003": // Welcome ...
  487. break;
  488. case "004": // Server information
  489. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  490. commArgs = parms.Split(CS_SPACE);
  491. c_server = commArgs[1];
  492. m_server = c_server;
  493. version = commArgs[2];
  494. usermod = commArgs[3];
  495. chanmod = commArgs[4];
  496. m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
  497. m_writer.Flush();
  498. m_log.InfoFormat("[IRC-Connector-{0}]: sent request to join {1} ", idn, m_ircChannel);
  499. break;
  500. case "005": // Server information
  501. break;
  502. case "042":
  503. case "250":
  504. case "251":
  505. case "252":
  506. case "254":
  507. case "255":
  508. case "265":
  509. case "266":
  510. case "332": // Subject
  511. case "333": // Subject owner (?)
  512. case "353": // Name list
  513. case "366": // End-of-Name list marker
  514. case "372": // MOTD body
  515. case "375": // MOTD start
  516. // m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
  517. break;
  518. case "376": // MOTD end
  519. // m_log.InfoFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
  520. motd = true;
  521. break;
  522. case "451": // Not registered
  523. break;
  524. case "433": // Nickname in use
  525. // Gen a new name
  526. m_nick = m_baseNick + Util.RandomClass.Next(1, 99);
  527. m_log.ErrorFormat("[IRC-Connector-{0}]: [{1}] IRC SERVER reports NicknameInUse, trying {2}", idn, cmd, m_nick);
  528. // Retry
  529. m_writer.WriteLine(String.Format("NICK {0}", m_nick));
  530. m_writer.Flush();
  531. m_writer.WriteLine(m_user);
  532. m_writer.Flush();
  533. m_writer.WriteLine(String.Format("JOIN {0}", m_ircChannel));
  534. m_writer.Flush();
  535. break;
  536. case "479": // Bad channel name, etc. This will never work, so disable the connection
  537. m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]);
  538. m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] Connector disabled", idn, cmd);
  539. m_enabled = false;
  540. m_connected = false;
  541. m_pending = false;
  542. break;
  543. case "NOTICE":
  544. // m_log.WarnFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE,2)[1]);
  545. break;
  546. case "ERROR":
  547. m_log.ErrorFormat("[IRC-Connector-{0}] [{1}] {2}", idn, cmd, parms.Split(CS_SPACE, 2)[1]);
  548. if (parms.Contains("reconnect too fast"))
  549. ICCD_PERIOD++;
  550. m_pending = false;
  551. Reconnect();
  552. break;
  553. case "PING":
  554. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  555. m_writer.WriteLine(String.Format("PONG {0}", parms));
  556. m_writer.Flush();
  557. break;
  558. case "PONG":
  559. break;
  560. case "JOIN":
  561. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  562. eventIrcJoin(pfx, cmd, parms);
  563. break;
  564. case "PART":
  565. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  566. eventIrcPart(pfx, cmd, parms);
  567. break;
  568. case "MODE":
  569. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  570. eventIrcMode(pfx, cmd, parms);
  571. break;
  572. case "NICK":
  573. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  574. eventIrcNickChange(pfx, cmd, parms);
  575. break;
  576. case "KICK":
  577. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  578. eventIrcKick(pfx, cmd, parms);
  579. break;
  580. case "QUIT":
  581. m_log.DebugFormat("[IRC-Connector-{0}] [{1}] parms = <{2}>", idn, cmd, parms);
  582. eventIrcQuit(pfx, cmd, parms);
  583. break;
  584. default:
  585. m_log.DebugFormat("[IRC-Connector-{0}] Command '{1}' ignored, parms = {2}", idn, cmd, parms);
  586. break;
  587. }
  588. // m_log.DebugFormat("[IRC-Connector-{0}] prefix = <{1}> cmd = <{2}> complete", idn, pfx, cmd);
  589. }
  590. public void eventIrcJoin(string prefix, string command, string parms)
  591. {
  592. string[] args = parms.Split(CS_SPACE, 2);
  593. string IrcUser = prefix.Split('!')[0];
  594. string IrcChannel = args[0];
  595. if (IrcChannel.StartsWith(":"))
  596. IrcChannel = IrcChannel.Substring(1);
  597. if(IrcChannel == m_ircChannel)
  598. {
  599. m_log.InfoFormat("[IRC-Connector-{0}] Joined requested channel {1} at {2}", idn, IrcChannel,m_server);
  600. m_pending = false;
  601. }
  602. else
  603. m_log.InfoFormat("[IRC-Connector-{0}] Joined unknown channel {1} at {2}", idn, IrcChannel,m_server);
  604. BroadcastSim(IrcUser, "/me joins {0}", IrcChannel);
  605. }
  606. public void eventIrcPart(string prefix, string command, string parms)
  607. {
  608. string[] args = parms.Split(CS_SPACE, 2);
  609. string IrcUser = prefix.Split('!')[0];
  610. string IrcChannel = args[0];
  611. m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCPart {1}:{2}", idn, m_server, m_ircChannel);
  612. BroadcastSim(IrcUser, "/me parts {0}", IrcChannel);
  613. }
  614. public void eventIrcMode(string prefix, string command, string parms)
  615. {
  616. string[] args = parms.Split(CS_SPACE, 2);
  617. string UserMode = args[1];
  618. m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCMode {1}:{2}", idn, m_server, m_ircChannel);
  619. if (UserMode.Substring(0, 1) == ":")
  620. {
  621. UserMode = UserMode.Remove(0, 1);
  622. }
  623. }
  624. public void eventIrcNickChange(string prefix, string command, string parms)
  625. {
  626. string[] args = parms.Split(CS_SPACE, 2);
  627. string UserOldNick = prefix.Split('!')[0];
  628. string UserNewNick = args[0].Remove(0, 1);
  629. m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCNickChange {1}:{2}", idn, m_server, m_ircChannel);
  630. BroadcastSim(UserOldNick, "/me is now known as {0}", UserNewNick);
  631. }
  632. public void eventIrcKick(string prefix, string command, string parms)
  633. {
  634. string[] args = parms.Split(CS_SPACE, 3);
  635. string UserKicker = prefix.Split('!')[0];
  636. string IrcChannel = args[0];
  637. string UserKicked = args[1];
  638. string KickMessage = args[2];
  639. m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCKick {1}:{2}", idn, m_server, m_ircChannel);
  640. BroadcastSim(UserKicker, "/me kicks kicks {0} off {1} saying \"{2}\"", UserKicked, IrcChannel, KickMessage);
  641. if (UserKicked == m_nick)
  642. {
  643. BroadcastSim(m_nick, "Hey, that was me!!!");
  644. }
  645. }
  646. public void eventIrcQuit(string prefix, string command, string parms)
  647. {
  648. string IrcUser = prefix.Split('!')[0];
  649. string QuitMessage = parms;
  650. m_log.DebugFormat("[IRC-Connector-{0}] Event: IRCQuit {1}:{2}", idn, m_server, m_ircChannel);
  651. BroadcastSim(IrcUser, "/me quits saying \"{0}\"", QuitMessage);
  652. }
  653. #endregion
  654. #region Connector Watch Dog
  655. // A single watch dog monitors extant connectors and makes sure that they
  656. // are re-connected as necessary. If a connector IS connected, then it is
  657. // pinged, but only if a PING period has elapsed.
  658. protected static void WatchdogHandler(Object source, ElapsedEventArgs args)
  659. {
  660. // m_log.InfoFormat("[IRC-Watchdog] Status scan, pdk = {0}, icc = {1}", _pdk_, _icc_);
  661. _pdk_ = (_pdk_ + 1) % PING_PERIOD; // cycle the ping trigger
  662. _icc_++; // increment the inter-consecutive-connect-delay counter
  663. lock (m_connectors)
  664. foreach (IRCConnector connector in m_connectors)
  665. {
  666. // m_log.InfoFormat("[IRC-Watchdog] Scanning {0}", connector);
  667. if (connector.Enabled)
  668. {
  669. if (!connector.Connected)
  670. {
  671. try
  672. {
  673. // m_log.DebugFormat("[IRC-Watchdog] Connecting {1}:{2}", connector.idn, connector.m_server, connector.m_ircChannel);
  674. connector.Connect();
  675. }
  676. catch (Exception e)
  677. {
  678. m_log.ErrorFormat("[IRC-Watchdog] Exception on connector {0}: {1} ", connector.idn, e.Message);
  679. }
  680. }
  681. else
  682. {
  683. if (connector.m_pending)
  684. {
  685. if (connector.m_timeout == 0)
  686. {
  687. m_log.ErrorFormat("[IRC-Watchdog] Login timed-out for connector {0}, reconnecting", connector.idn);
  688. connector.Reconnect();
  689. }
  690. else
  691. connector.m_timeout--;
  692. }
  693. // Being marked connected is not enough to ping. Socket establishment can sometimes take a long
  694. // time, in which case the watch dog might try to ping the server before the socket has been
  695. // set up, with nasty side-effects.
  696. else if (_pdk_ == 0)
  697. {
  698. try
  699. {
  700. connector.m_writer.WriteLine(String.Format("PING :{0}", connector.m_server));
  701. connector.m_writer.Flush();
  702. }
  703. catch (Exception e)
  704. {
  705. m_log.ErrorFormat("[IRC-PingRun] Exception on connector {0}: {1} ", connector.idn, e.Message);
  706. m_log.Debug(e);
  707. connector.Reconnect();
  708. }
  709. }
  710. }
  711. }
  712. }
  713. // m_log.InfoFormat("[IRC-Watchdog] Status scan completed");
  714. }
  715. #endregion
  716. }
  717. }