1
0

IRCConnector.cs 33 KB

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