The easy to use and full featured Irc Bot everyone is talking about!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IRC.cs 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Net;
  9. using System.Net.NetworkInformation;
  10. using System.Net.Sockets;
  11. using Combot.IRCServices.Messaging;
  12. using Combot.IRCServices.Commanding;
  13. using Combot.IRCServices.TCP;
  14. namespace Combot.IRCServices
  15. {
  16. public partial class IRC
  17. {
  18. public List<Channel> Channels = new List<Channel>();
  19. public Messages Message;
  20. public Commands Command;
  21. public event Action ConnectEvent;
  22. public event Action DisconnectEvent;
  23. public event Action<TCPError> TCPErrorEvent;
  24. public event Action<Exception> ExceptionThrown;
  25. public string Nickname;
  26. public Dictionary<string, PrivilegeMode> PrivilegeMapping = new Dictionary<string, PrivilegeMode>() { { "+", PrivilegeMode.v }, { "%", PrivilegeMode.h }, { "@", PrivilegeMode.o }, { "&", PrivilegeMode.a }, { "~", PrivilegeMode.q }, { "!", PrivilegeMode.q } };
  27. private int ReadTimeout;
  28. private int AllowedFailedReads;
  29. private int MessageSendDelay;
  30. private Thread TCPReader;
  31. private Thread KeepAlive;
  32. private DateTime LastMessageSend;
  33. private event Action<string> TCPMessageEvent;
  34. private readonly TCPInterface _TCP;
  35. private readonly ReaderWriterLockSlim ChannelRWLock;
  36. private readonly ReaderWriterLockSlim MessageSendLock;
  37. public IRC(int maxMessageLength, int messageSendDelay = 0, int readTimeout = 5000, int allowedFailedReads = 0)
  38. {
  39. Nickname = string.Empty;
  40. ChannelRWLock = new ReaderWriterLockSlim();
  41. MessageSendLock = new ReaderWriterLockSlim();
  42. ReadTimeout = readTimeout;
  43. AllowedFailedReads = allowedFailedReads;
  44. LastMessageSend = DateTime.Now;
  45. MessageSendDelay = messageSendDelay;
  46. _TCP = new TCPInterface();
  47. Message = new Messages(this);
  48. Command = new Commands(this, maxMessageLength, messageSendDelay);
  49. TCPMessageEvent += Message.ParseTCPMessage;
  50. _TCP.TCPConnectionEvent += HandleTCPConnection;
  51. _TCP.TCPErrorEvent += HandleTCPError;
  52. Message.ErrorMessageEvent += HandleErrorMessage;
  53. Message.PingEvent += HandlePing;
  54. Message.ServerReplyEvent += HandleReply;
  55. Message.ChannelModeChangeEvent += HandleChannelModeChange;
  56. Message.UserModeChangeEvent += HandleUserModeChange;
  57. Message.NickChangeEvent += HandleNickChange;
  58. Message.JoinChannelEvent += HandleJoin;
  59. Message.PartChannelEvent += HandlePart;
  60. Message.KickEvent += HandleKick;
  61. Message.QuitEvent += HandleQuit;
  62. }
  63. /// <summary>
  64. /// Starts a TCP connection to the specified host.
  65. /// </summary>
  66. /// <param name="IP">The IP address of the host.</param>
  67. /// <param name="port">The port for the tcp connection.</param>
  68. /// <param name="readTimeout">The timeout for read operations in milliseconds.</param>
  69. /// <param name="allowedFailedCount">Number of times a read can fail before disconnecting.</param>
  70. /// <returns></returns>
  71. public bool Connect(IPAddress IP, int port)
  72. {
  73. bool result = false;
  74. try
  75. {
  76. if (!_TCP.Connected)
  77. {
  78. result = _TCP.Connect(IP, port, ReadTimeout, AllowedFailedReads);
  79. if (result)
  80. {
  81. TCPReader = new Thread(ReadTCPMessages);
  82. TCPReader.IsBackground = true;
  83. TCPReader.Start();
  84. KeepAlive = new Thread(() => CheckConnection(IP, port));
  85. KeepAlive.IsBackground = true;
  86. KeepAlive.Start();
  87. if (ConnectEvent != null)
  88. {
  89. ConnectEvent();
  90. }
  91. }
  92. }
  93. }
  94. catch(Exception ex)
  95. {
  96. ThrowException(ex);
  97. }
  98. return result;
  99. }
  100. /// <summary>
  101. /// Disconencts from the active TCP connection.
  102. /// </summary>
  103. /// <returns></returns>
  104. public void Disconnect()
  105. {
  106. try
  107. {
  108. if (_TCP.Connected)
  109. {
  110. _TCP.Disconnect();
  111. }
  112. if (KeepAlive.IsAlive)
  113. {
  114. KeepAlive.Join();
  115. }
  116. if (TCPReader.IsAlive)
  117. {
  118. TCPReader.Join();
  119. }
  120. ChannelRWLock.EnterWriteLock();
  121. Channels = new List<Channel>();
  122. ChannelRWLock.ExitWriteLock();
  123. if (DisconnectEvent != null)
  124. {
  125. DisconnectEvent();
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. ThrowException(ex, "Disconnect Exception");
  131. }
  132. }
  133. /// <summary>
  134. /// Logs in the specified nick using their Username and Realname.
  135. /// </summary>
  136. /// <param name="serverName">The server's name.</param>
  137. /// <param name="nick">The nick information for the login.</param>
  138. public void Login(string serverName, Nick nick)
  139. {
  140. try
  141. {
  142. Nickname = nick.Nickname;
  143. Command.SendNick(nick.Nickname);
  144. Command.SendUser(nick.Username, nick.Host, serverName, nick.Realname);
  145. }
  146. catch (Exception ex)
  147. {
  148. ThrowException(ex, "Login Exception.");
  149. }
  150. }
  151. /// <summary>
  152. /// Parses a given mode and parameter string to generate a channel mode list.
  153. /// </summary>
  154. /// <param name="modeString">The mode string that contains the mode info.</param>
  155. /// <param name="parameterString">The parameter string that is associated with the mode info.</param>
  156. /// <returns></returns>
  157. public List<ChannelModeInfo> ParseChannelModeString(string modeString, string parameterString)
  158. {
  159. List<ChannelModeInfo> modeInfos = new List<ChannelModeInfo>();
  160. try
  161. {
  162. string[] modeArgs = parameterString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  163. char[] modeInfo = modeString.ToCharArray();
  164. bool set = true;
  165. int argIndex = 0;
  166. foreach (char mode in modeInfo)
  167. {
  168. if (mode.Equals('-'))
  169. {
  170. set = false;
  171. }
  172. else if (mode.Equals('+'))
  173. {
  174. set = true;
  175. }
  176. else
  177. {
  178. ChannelModeInfo newMode = new ChannelModeInfo();
  179. newMode.Set = set;
  180. ChannelMode foundMode;
  181. bool validMode = Enum.TryParse(mode.ToString(), false, out foundMode);
  182. if (validMode)
  183. {
  184. newMode.Mode = foundMode;
  185. if (modeArgs.GetUpperBound(0) >= argIndex)
  186. {
  187. switch (newMode.Mode)
  188. {
  189. case ChannelMode.k:
  190. case ChannelMode.l:
  191. case ChannelMode.b:
  192. case ChannelMode.e:
  193. case ChannelMode.I:
  194. case ChannelMode.v:
  195. case ChannelMode.h:
  196. case ChannelMode.o:
  197. case ChannelMode.a:
  198. case ChannelMode.q:
  199. newMode.Parameter = modeArgs[argIndex];
  200. argIndex++;
  201. break;
  202. default:
  203. newMode.Parameter = string.Empty;
  204. break;
  205. }
  206. }
  207. else
  208. {
  209. newMode.Parameter = string.Empty;
  210. }
  211. modeInfos.Add(newMode);
  212. }
  213. }
  214. }
  215. }
  216. catch (Exception ex)
  217. {
  218. ThrowException(ex, "Unable to parse Channel Mode.");
  219. }
  220. return modeInfos;
  221. }
  222. public List<UserModeInfo> ParseUserModeString(string modeString)
  223. {
  224. List<UserModeInfo> userModes = new List<UserModeInfo>();
  225. try
  226. {
  227. bool set = true;
  228. char[] modeArr = modeString.ToCharArray();
  229. for (int i = 1; i <= modeArr.GetUpperBound(0); i++)
  230. {
  231. UserModeInfo newMode = new UserModeInfo();
  232. if (modeArr[i].Equals('-'))
  233. {
  234. set = false;
  235. }
  236. else if (modeArr[i].Equals('+'))
  237. {
  238. set = true;
  239. }
  240. else if (modeArr[i].Equals('*'))
  241. {
  242. newMode.Mode = UserMode.o;
  243. newMode.Set = set;
  244. userModes.Add(newMode);
  245. }
  246. else
  247. {
  248. UserMode foundMode;
  249. bool validMode = Enum.TryParse(modeArr[i].ToString(), false, out foundMode);
  250. if (validMode)
  251. {
  252. newMode.Mode = foundMode;
  253. newMode.Set = set;
  254. userModes.Add(newMode);
  255. }
  256. }
  257. }
  258. }
  259. catch (Exception ex)
  260. {
  261. ThrowException(ex, "Unable to parse User Mode.");
  262. }
  263. return userModes;
  264. }
  265. private void ReadTCPMessages()
  266. {
  267. while (_TCP.Connected)
  268. {
  269. string response = ReadTCPMessage();
  270. if (TCPMessageEvent != null && response != null && response != string.Empty)
  271. {
  272. TCPMessageEvent(response);
  273. }
  274. }
  275. }
  276. private string ReadTCPMessage()
  277. {
  278. if (_TCP.Connected)
  279. {
  280. return _TCP.Read();
  281. }
  282. return null;
  283. }
  284. internal void SendTCPMessage(string message)
  285. {
  286. if (_TCP.Connected)
  287. {
  288. MessageSendLock.EnterWriteLock();
  289. TimeSpan sinceLastMessage = (DateTime.Now - LastMessageSend);
  290. if (sinceLastMessage.TotalMilliseconds < MessageSendDelay)
  291. {
  292. Thread.Sleep((int)(MessageSendDelay - sinceLastMessage.TotalMilliseconds));
  293. }
  294. LastMessageSend = DateTime.Now;
  295. string replaceWith = string.Empty;
  296. string parsedMessage = message.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
  297. _TCP.Write(parsedMessage);
  298. MessageSendLock.ExitWriteLock();
  299. }
  300. }
  301. private void CheckConnection(IPAddress IP, int port)
  302. {
  303. int diconnectCount = 0;
  304. bool disconnectActivated = false;
  305. while (_TCP.Connected)
  306. {
  307. Thread.Sleep(5000);
  308. bool stillConnected = NetworkInterface.GetIsNetworkAvailable();
  309. if (stillConnected)
  310. {
  311. Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  312. try
  313. {
  314. s.Connect(IP, port);
  315. }
  316. catch
  317. {
  318. stillConnected = false;
  319. }
  320. }
  321. if (!stillConnected)
  322. {
  323. diconnectCount++;
  324. }
  325. else
  326. {
  327. diconnectCount = 0;
  328. }
  329. if (diconnectCount >= 5 && !disconnectActivated)
  330. {
  331. disconnectActivated = true;
  332. Task.Run(() =>
  333. {
  334. Disconnect();
  335. });
  336. }
  337. }
  338. }
  339. /// <summary>
  340. /// Responds with PONG on a PING with the specified arguments.
  341. /// </summary>
  342. /// <param name="sender"></param>
  343. /// <param name="e"></param>
  344. private void HandlePing(object sender, PingInfo e)
  345. {
  346. Command.SendPong(e.Message);
  347. }
  348. private void HandleTCPConnection(int e)
  349. {
  350. if (DisconnectEvent != null)
  351. {
  352. DisconnectEvent();
  353. }
  354. }
  355. private void HandleTCPError(TCPError e)
  356. {
  357. if (TCPErrorEvent != null)
  358. {
  359. TCPErrorEvent(e);
  360. }
  361. }
  362. private void HandleErrorMessage(object sender, ErrorMessage e)
  363. {
  364. Disconnect();
  365. }
  366. private void HandleReply(object sender, IReply e)
  367. {
  368. if (e.GetType() == typeof(ServerReplyMessage))
  369. {
  370. ServerReplyMessage msg = (ServerReplyMessage)e;
  371. switch (msg.ReplyCode)
  372. {
  373. // If we get a WHO response, we parse and add the nicks to the specified channel if they are not there already.
  374. case IRCReplyCode.RPL_WHOREPLY:
  375. ChannelRWLock.EnterWriteLock();
  376. string[] msgSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  377. if (msgSplit.GetUpperBound(0) > 0)
  378. {
  379. string target = msgSplit[0];
  380. if (target.StartsWith("&") || target.StartsWith("#"))
  381. {
  382. if (msgSplit.GetUpperBound(0) >= 7)
  383. {
  384. string nickname = msgSplit[4];
  385. string realname = msgSplit[7];
  386. string username = msgSplit[1];
  387. string host = msgSplit[2];
  388. string modeString = msgSplit[5];
  389. Channel channel = Channels.Find(chan => chan.Name == target);
  390. if (channel != null)
  391. {
  392. Nick nick = channel.GetNick(nickname);
  393. bool nickFound = true;
  394. if (nick == null)
  395. {
  396. nickFound = false;
  397. nick = new Nick();
  398. }
  399. nick.Nickname = nickname;
  400. nick.Host = host;
  401. nick.Realname = realname;
  402. nick.Username = username;
  403. nick.Modes = new List<UserMode>();
  404. nick.Privileges = new List<PrivilegeMode>();
  405. char[] modeArr = modeString.ToCharArray();
  406. for (int i = 1; i <= modeArr.GetUpperBound(0); i++)
  407. {
  408. if (PrivilegeMapping.ContainsKey(modeArr[i].ToString()))
  409. {
  410. nick.Privileges.Add(PrivilegeMapping[modeArr[i].ToString()]);
  411. }
  412. else if (modeArr[i].ToString() == "*")
  413. {
  414. nick.Modes.Add(UserMode.o);
  415. }
  416. else
  417. {
  418. UserMode foundMode;
  419. bool valid = Enum.TryParse(modeArr[i].ToString(), false, out foundMode);
  420. if (valid)
  421. {
  422. nick.Modes.Add(foundMode);
  423. }
  424. }
  425. }
  426. if (!nickFound)
  427. {
  428. channel.AddNick(nick);
  429. }
  430. }
  431. }
  432. }
  433. }
  434. ChannelRWLock.ExitWriteLock();
  435. break;
  436. // On a topic reply, update the channel's topic
  437. case IRCReplyCode.RPL_TOPIC:
  438. ChannelRWLock.EnterWriteLock();
  439. string[] topicSplit = msg.Message.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  440. if (topicSplit.GetUpperBound(0) > 0)
  441. {
  442. string topicChan = topicSplit[0];
  443. Channel topicChannel = Channels.Find(chan => chan.Name == topicChan);
  444. if (topicChannel != null)
  445. {
  446. topicChannel.Topic = topicSplit[1].Remove(0, 1);
  447. }
  448. }
  449. ChannelRWLock.ExitWriteLock();
  450. break;
  451. default:
  452. break;
  453. }
  454. }
  455. else
  456. {
  457. ServerErrorMessage msg = (ServerErrorMessage)e;
  458. }
  459. }
  460. /// <summary>
  461. /// Update a channel's mode.
  462. /// </summary>
  463. /// <param name="sender"></param>
  464. /// <param name="e"></param>
  465. private void HandleChannelModeChange(object sender, ChannelModeChangeInfo e)
  466. {
  467. ChannelRWLock.EnterWriteLock();
  468. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  469. if (channel != null)
  470. {
  471. foreach (ChannelModeInfo mode in e.Modes)
  472. {
  473. switch (mode.Mode)
  474. {
  475. case ChannelMode.v:
  476. case ChannelMode.h:
  477. case ChannelMode.o:
  478. case ChannelMode.a:
  479. case ChannelMode.q:
  480. Nick changedNick = channel.GetNick(mode.Parameter);
  481. if (changedNick != null)
  482. {
  483. PrivilegeMode priv;
  484. Enum.TryParse(mode.Mode.ToString(), out priv);
  485. if (mode.Set)
  486. {
  487. changedNick.AddPrivilege(priv);
  488. }
  489. else
  490. {
  491. changedNick.RemovePrivilege(priv);
  492. }
  493. }
  494. break;
  495. case ChannelMode.b:
  496. if (mode.Set)
  497. {
  498. channel.AddBan(mode.Parameter);
  499. }
  500. else
  501. {
  502. channel.RemoveBan(mode.Parameter);
  503. }
  504. break;
  505. case ChannelMode.k:
  506. if (mode.Set)
  507. {
  508. channel.AddMode(mode.Mode);
  509. channel.Key = mode.Parameter;
  510. }
  511. else
  512. {
  513. channel.RemoveMode(mode.Mode);
  514. channel.Key = string.Empty;
  515. }
  516. break;
  517. default:
  518. if (mode.Set)
  519. {
  520. channel.AddMode(mode.Mode);
  521. }
  522. else
  523. {
  524. channel.RemoveMode(mode.Mode);
  525. }
  526. break;
  527. }
  528. }
  529. Command.SendWho(channel.Name);
  530. }
  531. ChannelRWLock.ExitWriteLock();
  532. }
  533. /// <summary>
  534. /// Update a nick's mode.
  535. /// </summary>
  536. /// <param name="sender"></param>
  537. /// <param name="e"></param>
  538. private void HandleUserModeChange(object sender, UserModeChangeInfo e)
  539. {
  540. ChannelRWLock.EnterWriteLock();
  541. for (int i = 0; i < Channels.Count; i++)
  542. {
  543. Nick changedNick = Channels[i].GetNick(e.Nick.Nickname);
  544. if (changedNick != null)
  545. {
  546. foreach (UserModeInfo mode in e.Modes)
  547. {
  548. if (mode.Set)
  549. {
  550. changedNick.AddMode(mode.Mode);
  551. }
  552. else
  553. {
  554. changedNick.RemoveMode(mode.Mode);
  555. }
  556. }
  557. }
  558. }
  559. ChannelRWLock.ExitWriteLock();
  560. }
  561. /// <summary>
  562. /// Update a nick to use their new nickname.
  563. /// </summary>
  564. /// <param name="sender"></param>
  565. /// <param name="e"></param>
  566. private void HandleNickChange(object sender, NickChangeInfo e)
  567. {
  568. ChannelRWLock.EnterWriteLock();
  569. for (int i = 0; i < Channels.Count; i++)
  570. {
  571. Nick newNick = Channels[i].GetNick(e.OldNick.Nickname);
  572. if (newNick != null)
  573. {
  574. if (e.OldNick.Nickname == Nickname)
  575. {
  576. Nickname = e.NewNick.Nickname;
  577. }
  578. newNick.Nickname = e.NewNick.Nickname;
  579. }
  580. }
  581. ChannelRWLock.ExitWriteLock();
  582. }
  583. /// <summary>
  584. /// Add a nick to a channel on join.
  585. /// </summary>
  586. /// <param name="sender"></param>
  587. /// <param name="e"></param>
  588. private void HandleJoin(object sender, JoinChannelInfo e)
  589. {
  590. ChannelRWLock.EnterWriteLock();
  591. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  592. if (channel != null)
  593. {
  594. channel.AddNick(e.Nick);
  595. }
  596. else
  597. {
  598. Channel newChannel = new Channel();
  599. newChannel.Name = e.Channel;
  600. newChannel.Nicks.Add(e.Nick);
  601. Channels.Add(newChannel);
  602. Command.SendWho(newChannel.Name);
  603. }
  604. ChannelRWLock.ExitWriteLock();
  605. }
  606. /// <summary>
  607. /// Remove a nick from a channel on part.
  608. /// </summary>
  609. /// <param name="sender"></param>
  610. /// <param name="e"></param>
  611. private void HandlePart(object sender, PartChannelInfo e)
  612. {
  613. ChannelRWLock.EnterWriteLock();
  614. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  615. if (channel != null)
  616. {
  617. if (e.Nick.Nickname == Nickname)
  618. {
  619. Channels.Remove(channel);
  620. }
  621. else
  622. {
  623. channel.RemoveNick(e.Nick.Nickname);
  624. }
  625. }
  626. ChannelRWLock.ExitWriteLock();
  627. }
  628. /// <summary>
  629. /// Remove a nick from a channel on kick.
  630. /// </summary>
  631. /// <param name="sender"></param>
  632. /// <param name="e"></param>
  633. private void HandleKick(object sender, KickInfo e)
  634. {
  635. ChannelRWLock.EnterWriteLock();
  636. Channel channel = Channels.Find(chan => chan.Name == e.Channel);
  637. if (channel != null)
  638. {
  639. if (e.KickedNick.Nickname == Nickname)
  640. {
  641. Channels.Remove(channel);
  642. }
  643. else
  644. {
  645. channel.RemoveNick(e.KickedNick.Nickname);
  646. }
  647. }
  648. ChannelRWLock.ExitWriteLock();
  649. }
  650. /// <summary>
  651. /// Remove a nick from all channels on quit.
  652. /// </summary>
  653. /// <param name="sender"></param>
  654. /// <param name="e"></param>
  655. private void HandleQuit(object sender, QuitInfo e)
  656. {
  657. ChannelRWLock.EnterWriteLock();
  658. for (int i = 0; i < Channels.Count; i++)
  659. {
  660. Channels[i].RemoveNick(e.Nick.Nickname);
  661. }
  662. ChannelRWLock.ExitWriteLock();
  663. }
  664. private void ThrowException(Exception ex)
  665. {
  666. ThrowException(ex, "Irc Service threw exception.");
  667. }
  668. private void ThrowException(Exception ex, string message)
  669. {
  670. Exception newEx = new Exception(message, ex);
  671. if (ExceptionThrown != null)
  672. {
  673. ExceptionThrown(newEx);
  674. }
  675. }
  676. }
  677. }