IRCConnector.cs 31 KB

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