irc.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. var net = require('net');
  2. var IRCserver = require('./server');
  3. var IRCuser = require('./user');
  4. var IRCchannel = require('./channel');
  5. var connection = null;
  6. var recvData = '';
  7. var users = [];
  8. var servers = [];
  9. var channels = [];
  10. var me = null;
  11. var events = {};
  12. function addInternalEvents(){
  13. events.netSynced.unshift(function(){
  14. for(var i=0; i<users.length; i++){
  15. var user = users[i];
  16. if(user.uplink == me){
  17. irc.uplink.introduceUser(user);
  18. }
  19. }
  20. for(var i=0; i<channels.length; i++){
  21. irc.uplink.syncChannel(channels[i]);
  22. }
  23. });
  24. events.newTagMessage.unshift(function(inputTags, newTags, msg){
  25. if(!newTags){
  26. var newTags = {};
  27. }
  28. if('label' in inputTags) newTags['label'] = inputTags['label']; // labeled-response
  29. newTags['time'] = new Date().toISOString(); // server-time
  30. newTags['msgid'] = randomID('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', 22);
  31. return [inputTags, newTags, msg];
  32. });
  33. }
  34. function randomID(characters, length){
  35. var result = '';
  36. var charactersLength = characters.length;
  37. for(var i=0; i<length; i++ ) {
  38. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  39. }
  40. return result;
  41. }
  42. function findServer(s){
  43. for(var i=0; i<servers.length; i++){
  44. srv = servers[i];
  45. if(srv.sid == s || srv.name == s) return srv;
  46. }
  47. return null;
  48. }
  49. function findUser(u){
  50. for(var i=0; i<users.length; i++){
  51. usr = users[i];
  52. if(usr.uid == u || usr.name == u) return usr;
  53. }
  54. return null;
  55. }
  56. function findChannel(c){
  57. for(var i=0; i<channels.length; i++){
  58. usr = channels[i];
  59. if(channels[i].name == c) return channels[i];
  60. }
  61. return null;
  62. }
  63. function removeServer(server){
  64. var length = servers.length;
  65. var done = false;
  66. do {
  67. for(var i=0; i<length; i++){
  68. if(servers.length != length) break;
  69. if(servers[i].uplink == server){
  70. removeServer(servers[i]); // remove connected servers recursively
  71. }
  72. }
  73. if(i == length) done = true;
  74. } while(!done);
  75. for(var i=users.length-1; i>=0; i--){
  76. if(users[i].uplink == server){
  77. quitUser(users[i]); // remove users connected to this server
  78. }
  79. }
  80. for(var i=servers.length-1; i>=0; i--){ // finally, remove the given server
  81. if(servers[i] == server){
  82. console.log('Removing server '+servers[i].name);
  83. events.doEvent('serverDelete', server);
  84. servers.splice(i, 1);
  85. delete server;
  86. break;
  87. }
  88. }
  89. }
  90. function getChannel(name){
  91. var lowerName = name.toLowerCase();
  92. var channel = null;
  93. for(var i=0; i<channels.length; i++){
  94. if(channels[i].name == lowerName){
  95. channel = channels[i];
  96. break;
  97. }
  98. }
  99. if(!channel){
  100. console.log('Creating channel '+name);
  101. channel = new IRCchannel;
  102. channel.setEvents(events);
  103. channel.name = name;
  104. channels.push(channel);
  105. events.doEvent('channelCreate', channel);
  106. }
  107. return channel;
  108. }
  109. function killUser(user){
  110. console.log('KILL');
  111. console.log(user);
  112. // TODO
  113. }
  114. function newUser(nick, distance, TS, ident, host, uid, account, umodes, vhost, cloakedHost, ip, realname, uplink){ // nick, distance, TS, ident, host, uid, account, umodes, vhost, cloakedHost, ip, realname, uplink
  115. var user;
  116. if((user = findUser(uid)) || (user = findUser(nick))){
  117. console.log(user);
  118. throw 'User already exists';
  119. }
  120. console.log('Introducing user '+nick);
  121. user = new IRCuser;
  122. user.setEvents(events);
  123. user.introduce(nick, distance, TS, ident, host, uid, account, umodes, vhost, cloakedHost, ip, realname, uplink);
  124. users.push(user);
  125. events.doEvent('userCreate', user);
  126. return user;
  127. }
  128. function newServer(name, sid, desc, distance, uplink){
  129. if(findServer(sid) || findServer(name)){
  130. throw 'Server already exists';
  131. }
  132. console.log('Introducing server '+name+' (SID='+sid+', uplink="'+uplink.name+'")');
  133. server = new IRCserver;
  134. server.setEvents(events);
  135. server.introduce(name, sid, desc, distance, uplink);
  136. servers.push(server);
  137. events.doEvent('serverCreate', server);
  138. return server;
  139. }
  140. function ircSendData(tags, from, cmd, args){
  141. var data = makeTagsString(tags);
  142. if(from){
  143. data += ':' + from + ' ';
  144. }
  145. data += cmd;
  146. if(args) for(var i=0; i<args.length; i++){
  147. var arg = args[i];
  148. if(arg.indexOf(' ') >= 0){ // valid for last arg only
  149. arg = ':' + arg;
  150. }
  151. data += ' ' + arg;
  152. }
  153. console.log('<<< '+data);
  154. data += "\r\n";
  155. connection.write(data);
  156. }
  157. function ircDataReceived(data){
  158. data = data.toString('utf8');
  159. recvData += data;
  160. var buffer = '';
  161. for(var i=0; i<recvData.length; i++){
  162. var c = recvData.charAt(i);
  163. switch(c){
  164. default: buffer += c; break;
  165. case '\r': case '\n':
  166. if(buffer.length > 0)
  167. ircMessage(buffer);
  168. buffer = '';
  169. break;
  170. }
  171. }
  172. recvData = buffer;
  173. }
  174. function makeTagsString(tags){
  175. if(!irc.uplink.supportsTags) return '';
  176. if(!tags) return '';
  177. var tagText = '';
  178. for(name in tags){
  179. var value = tags[name].replace(/;/g, '\\:').replace(/ /g, '\\s').replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
  180. if(tagText.length == 0){
  181. tagText += '@';
  182. } else {
  183. tagText += ';';
  184. }
  185. tagText += name;
  186. if(value.length > 0){
  187. tagText += '=' + value;
  188. }
  189. }
  190. if(tagText.length > 0){
  191. tagText += ' ';
  192. }
  193. return tagText;
  194. }
  195. function ircMessage(data){
  196. var msg = irc.parseLine(data);
  197. irc.uplink.processMessage(msg);
  198. }
  199. function ircConnectionClosed(e){
  200. events.doEvent('uplinkLost', me);
  201. console.log('Closed: '+e);
  202. process.exit(1);
  203. }
  204. function processReplyTags(inputTags, newTags, msg){
  205. newTags = events.doEvent('newTagMessage', inputTags, newTags, msg);
  206. return newTags[1];
  207. }
  208. function newTags(newTags){
  209. return events.doEvent('newTagMessage', {}, newTags, null)[1];
  210. }
  211. function quitUser(user){
  212. if(user.uplink == me){ // out bot was killed?
  213. console.log('Tried to kill ' + user.name + '!');
  214. irc.uplink.introduceUser(user); // re-introduce
  215. for(var i=0; i<user.channels.length; i++){
  216. irc.uplink.joinChannel(user, user.channels[i]);
  217. }
  218. return;
  219. }
  220. console.log('Removing user '+user.name);
  221. for(var i=0; i<channels.length; i++){
  222. channels[i].removeUser(user);
  223. }
  224. for(var i=0; i<users.length; i++){
  225. if(users[i] == user){
  226. users.splice(i, 1);
  227. events.doEvent('userDelete', user);
  228. delete user;
  229. break;
  230. }
  231. }
  232. }
  233. function removeEmptyChannels(){
  234. for(var i=channels.length - 1; i >= 0; i--){
  235. if(channels[i].users.length == 0){
  236. storeChannelData(channels[i]);
  237. console.log('Removing channel '+channels[i].name);
  238. var channel = channels[i];
  239. channels.splice(i, 1);
  240. delete channel;
  241. }
  242. }
  243. }
  244. function storeChannelData(channel){
  245. // TODO maybe move a level up
  246. }
  247. setInterval(removeEmptyChannels, 1000);
  248. var irc = {
  249. 'users': users,
  250. 'channels': channels,
  251. 'servers': servers,
  252. 'getChannel': getChannel,
  253. 'uplink': null,
  254. 'setConnection': function(host, port, protocol){
  255. irc.uplink = require('./protocol/' + protocol);
  256. me = new IRCserver;
  257. me.setEvents(events);
  258. me.introduce('serwisy.pirc.pl', '11K', 'Serwisy', 0, null);
  259. servers.push(me);
  260. irc.uplink.setHandlers({
  261. send: ircSendData,
  262. findServer: findServer,
  263. findUser: findUser,
  264. killUser: killUser,
  265. newServer: newServer,
  266. newUser: newUser,
  267. getChannel: getChannel,
  268. quitUser: quitUser,
  269. removeServer: removeServer,
  270. findChannel: findChannel,
  271. randomID: randomID,
  272. newTags: newTags
  273. });
  274. irc.uplink.setSettings({
  275. ID: me.sid,
  276. password: 'myservicespassword',
  277. name: me.name,
  278. description: me.description,
  279. version: 'k4be-services',
  280. me: me,
  281. maxUsers: 0
  282. });
  283. addInternalEvents();
  284. irc.uplink.setEvents(events);
  285. connection = new net.Socket();
  286. connection.connect(port, host, irc.uplink.connected.bind(this));
  287. connection.on('data', ircDataReceived);
  288. connection.on('close', ircConnectionClosed);
  289. },
  290. 'setEvents': function(newEvents){
  291. events = newEvents;
  292. },
  293. 'makeUser': function(nick, ident, host, realname){
  294. var user = new IRCuser;
  295. user.setEvents(events);
  296. var uid = irc.uplink.makeUid();
  297. var umodes = { 'SERVICEUSER': true, 'BOT': true, 'OPER': true }; // TODO make it configurable
  298. user.introduce(nick, 0, Math.floor(new Date() / 1000).toString(10), ident, host, uid, null, umodes, null, null, null, realname, me);
  299. users.push(user);
  300. return user;
  301. },
  302. 'messagedata': function() {
  303. this.text = '';
  304. this.args = [];
  305. this.tags = [];
  306. this.command = '';
  307. this.sender = {
  308. 'nick': '',
  309. 'ident': '',
  310. 'host': '',
  311. 'server': false,
  312. 'user': false
  313. };
  314. this.time = new Date();
  315. this.reply = function(tags, cmd, args){
  316. var outTags = processReplyTags(this.tags, tags, this);
  317. ircSendData(outTags, this.sender.nick, cmd, args);
  318. }
  319. this.originalString = '';
  320. },
  321. 'parseTags': function(tagsLine){
  322. var tags = [];
  323. var tagState = 'keyName';
  324. var keyValue;
  325. var keyName = '';
  326. for(var i = 0; i < tagsLine.length; i++){
  327. var cchar = tagsLine.charAt(i);
  328. switch(tagState){
  329. case 'keyName':
  330. switch(cchar){
  331. case '=':
  332. tagState = 'keyValue';
  333. keyValue = '';
  334. break;
  335. case ';':
  336. tags[keyName] = '';
  337. keyName = ''; // staying in tagStateKeyName
  338. break;
  339. default: keyName += cchar; break;
  340. }
  341. break;
  342. case 'keyValue':
  343. switch(cchar){
  344. case '\\': tagState = 'keyValueEscape'; break;
  345. case ';':
  346. tags[keyName] = keyValue;
  347. keyName = '';
  348. tagState = 'keyName';
  349. break;
  350. default: keyValue += cchar; break;
  351. }
  352. break;
  353. case 'keyValueEscape':
  354. switch(cchar){
  355. case ':': keyValue += ';'; break;
  356. case 's': keyValue += ' '; break;
  357. case 'r': keyValue += '\r'; break;
  358. case 'n': keyValue += '\n'; break;
  359. default: keyValue += cchar; break;
  360. }
  361. tagState = 'keyValue';
  362. break;
  363. }
  364. }
  365. if(keyName.length > 0) tags[keyName] = keyValue; // flush last tag
  366. return tags;
  367. },
  368. 'parseLine': function(line){
  369. var ircmsg = new irc.messagedata();
  370. var line = line.trim();
  371. line.replace(/^\s+|\s+$/gm,'');
  372. if(line == ''){
  373. return;
  374. }
  375. ircmsg.originalString = line;
  376. var msglen = line.length;
  377. var pstate = 'start';
  378. var currArg = '';
  379. var tags = '';
  380. var haveText = false;
  381. console.log('>>> ' + line);
  382. for(var i = 0; i < msglen; i++){
  383. var cchar = line.charAt(i);
  384. switch(pstate){
  385. case 'start':
  386. switch(cchar){
  387. case '@': pstate = 'tags'; break;
  388. case ':': pstate = 'senderNick'; break;
  389. default:
  390. pstate = 'command';
  391. ircmsg.command += cchar;
  392. break;
  393. }
  394. break;
  395. case 'tags':
  396. switch(cchar){
  397. case ' ':
  398. pstate = 'start';
  399. ircmsg.tags = irc.parseTags(tags);
  400. break;
  401. default: tags += cchar; break;
  402. }
  403. break;
  404. case 'senderNick':
  405. switch(cchar){
  406. case '!': pstate = 'senderUser'; break;
  407. case '@': pstate = 'senderHost'; break;
  408. case ' ': pstate = 'command'; break;
  409. default: ircmsg.sender.nick += cchar; break;
  410. }
  411. break;
  412. case 'senderUser':
  413. switch(cchar){
  414. case '@': pstate = 'senderHost'; break;
  415. case ' ': pstate = 'command'; break;
  416. default: ircmsg.sender.ident += cchar; break;
  417. }
  418. break;
  419. case 'senderHost':
  420. switch(cchar){
  421. case ' ': pstate = 'command'; break;
  422. default: ircmsg.sender.host += cchar; break;
  423. }
  424. break;
  425. case 'command':
  426. switch(cchar){
  427. case ' ': pstate = 'args'; break;
  428. default: ircmsg.command += cchar; break;
  429. }
  430. break;
  431. case 'args':
  432. switch(cchar){
  433. case ' ':
  434. if(currArg != ''){
  435. ircmsg.args.push(currArg);
  436. }
  437. currArg = '';
  438. break;
  439. case ':':
  440. if(prevChar == ' '){
  441. pstate = 'message';
  442. haveText = true;
  443. } else {
  444. currArg += cchar;
  445. }
  446. break;
  447. default: currArg += cchar; break;
  448. }
  449. break;
  450. case 'message':
  451. ircmsg.text += cchar;
  452. break;
  453. }
  454. var prevChar = cchar;
  455. }
  456. if(pstate == 'args'){
  457. ircmsg.args.push(currArg);
  458. }
  459. ircmsg.sender = irc.uplink.processSender(ircmsg.sender);
  460. if(!ircmsg.sender){
  461. return false;
  462. }
  463. if(!ircmsg.sender.server && !ircmsg.sender.user){
  464. if(ircmsg.sender.ident == '' && ircmsg.sender.host == '' && ircmsg.sender.nick.indexOf('.')!=-1){
  465. ircmsg.sender.server = true;
  466. } else {
  467. ircmsg.sender.user = true;
  468. }
  469. }
  470. if(!haveText){
  471. ircmsg.text = ircmsg.args[ircmsg.args.length-1]; // handling last argument as text if : is missing
  472. } else {
  473. ircmsg.args.push(ircmsg.text); // handling text as a last argument as required by the protocol
  474. }
  475. // add u@h
  476. /* if(ircmsg.sender.user){
  477. if(ircmsg.sender.ident) users.getUser(ircmsg.sender.nick).setIdent(ircmsg.sender.ident);
  478. if(ircmsg.sender.host) users.getUser(ircmsg.sender.nick).setHost(ircmsg.sender.host);
  479. }*/
  480. // process known tags
  481. /* if('time' in ircmsg.tags){
  482. ircmsg.time = parseISOString(ircmsg.tags['time']);
  483. }
  484. if('account' in ircmsg.tags){
  485. users.getUser(ircmsg.sender.nick).setAccount(ircmsg.tags['account']);
  486. }*/
  487. // console.log(ircmsg);
  488. return ircmsg;
  489. }
  490. };
  491. module.exports = irc;