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

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