IRCConnector.cs 32 KB

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