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 24KB

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