1
0

IRCConnector.cs 31 KB

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