OmnomIRC.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #!node
  2. process.chdir(__dirname);
  3. var fs = require('fs'),
  4. url = require('url'),
  5. path = require('path'),
  6. vm = require('vm'),
  7. toobusy = function(){return false;},//require('toobusy'),
  8. noop = function(){},
  9. cluster = require('cluster'),
  10. ircClient = require('node-irc'),
  11. logger = {
  12. log: function(msg){
  13. if(options.loglevel > 2){
  14. console.log(msg);
  15. }
  16. },
  17. debug: function(msg){
  18. if(options.loglevel > 2){
  19. console.log('DEBUG - '+msg);
  20. }
  21. },
  22. warn: function(msg){
  23. if(options.loglevel > 1){
  24. console.log('WARN - '+msg);
  25. }
  26. },
  27. info: function(msg){
  28. if(options.loglevel > 1){
  29. console.log('INFO - '+msg);
  30. }
  31. },
  32. error: function(msg){
  33. if(options.loglevel > 0){
  34. console.error(msg);
  35. }
  36. }
  37. },
  38. options = global.options = (function(){
  39. var defaults = {
  40. port: 80,
  41. loglevel: 3,
  42. threads: require('os').cpus().length,
  43. redis: {
  44. port: 6379,
  45. host: 'localhost'
  46. },
  47. debug: false,
  48. paths: {
  49. www: './www/',
  50. api: './api/',
  51. plugins: './plugins/'
  52. },
  53. irc: {
  54. host: 'irp.irc.omnimaga.org',
  55. port: 6667,
  56. nick: 'oirc3',
  57. name: 'OmnomIRC3',
  58. channels: [
  59. '#omnimaga'
  60. ],
  61. messages: {
  62. quit: 'Server closed'
  63. }
  64. },
  65. origins: [
  66. ['O','OmnomIRC'],
  67. ['#','IRC']
  68. ]
  69. },
  70. i,
  71. options;
  72. try{
  73. options = JSON.parse(fs.readFileSync('./options.json'));
  74. defaults = (function merge(options,defaults){
  75. for(var i in options){
  76. if(typeof defaults[i] != 'object' || defaults[i] instanceof Array){
  77. defaults[i] = options[i];
  78. }else{
  79. defaults[i] = merge(options[i],defaults[i]);
  80. }
  81. }
  82. return defaults
  83. })(options,defaults);
  84. }catch(e){
  85. console.warn('Using default settings. Please create options.json');
  86. console.error(e);
  87. }
  88. defaults.origins.unshift(['S','Server'],['?','Unknown']);
  89. options = {};
  90. for(i in defaults){
  91. Object.defineProperty(options,i,{
  92. value: defaults[i],
  93. enumerable: true,
  94. writable: false
  95. });
  96. }
  97. return options;
  98. })(),
  99. origin = function(name){
  100. for(var i in options.origins){
  101. if(options.origins[i][1] == name){
  102. return i;
  103. }
  104. }
  105. return 1;
  106. };
  107. if(typeof fs.existsSync == 'undefined') fs.existsSync = path.existsSync; // legacy support
  108. if(cluster.isMaster){
  109. var iWorker;
  110. cluster.on('exit', function(worker, code, signal) {
  111. console.log('worker ' + worker.process.pid + ' died');
  112. });
  113. iWorker = global.iw = cluster.fork();
  114. iWorker.on('online',function(){
  115. logger.info('First worker online');
  116. iWorker.send('S');
  117. });
  118. for(var i=1;i<options.threads;i++){
  119. cluster.fork().on('online',function(){
  120. logger.info('Child socket worker online');
  121. });
  122. }
  123. for(i in cluster.workers){
  124. var worker = cluster.workers[i];
  125. worker.on('message',function(msg){
  126. var c = msg[0];
  127. msg = msg.substr(1);
  128. logger.debug('Parent recieved command '+c+' with message '+msg);
  129. switch(c){
  130. case 'M':
  131. iWorker.send('M'+msg);
  132. break;
  133. }
  134. });
  135. }
  136. if(options.debug){
  137. require('repl').start({
  138. prompt: '> ',
  139. useGlobal: true
  140. }).on('exit',function(){
  141. for(var i in cluster.workers){
  142. cluster.workers[i].send('Q');
  143. }
  144. process.exit();
  145. });
  146. }
  147. }else{
  148. process.on('message',function(msg){
  149. var c = msg[0];
  150. msg = msg.substr(1);
  151. switch(c){
  152. case 'Q':
  153. if(typeof app != 'undefined' && typeof irc == 'undefined'){
  154. app.close();
  155. }else if(typeof irc != 'undefined'){
  156. irc.quit(options.irc.messages.quit);
  157. }
  158. break;
  159. case 'M':
  160. if(typeof irc != 'undefined'){
  161. msg = JSON.parse(msg);
  162. if(typeof msg.message != 'udefined'){
  163. msg.message = msg.message.replace(/[\r]/g,'');
  164. irc.say(msg.room,'('+options.origins[msg.origin][0]+')'+'<'+msg.from+'> '+msg.message);
  165. }
  166. }
  167. break;
  168. case 'S':
  169. logger.info('Child starting irc');
  170. irc = new ircClient(options.irc.host,options.irc.port,options.irc.nick,options.irc.name);
  171. irc.on('ready',function(){
  172. logger.info('Connected to IRC');
  173. for(var i in options.irc.channels){
  174. irc.join(options.irc.channels[i]);
  175. //irc.client.send('WHO %s\n',options.irc.channels[i]);
  176. }
  177. });
  178. irc.on('CHANMSG',function(d){
  179. console.log(d);
  180. message(d.reciever,d.sender,d.message,origin('IRC'));
  181. });
  182. // Beginnings of names handler
  183. /*irc.on('names',function(chan,nicks){
  184. for(var i in nicks){
  185. logger.debug('[NICKS] Channel '+chan+' '+nicks[i]);
  186. }
  187. });*/
  188. irc.connect();
  189. logger.debug('Connecting to IRC');
  190. break;
  191. }
  192. });
  193. logger.info('Child starting socket.io');
  194. var RedisStore = require('socket.io/lib/stores/redis'),
  195. redis = require('socket.io/node_modules/redis'),
  196. pub = redis.createClient(options.redis.port,options.redis.host),
  197. sub = redis.createClient(options.redis.port,options.redis.host),
  198. client = redis.createClient(options.redis.port,options.redis.host),
  199. mimeTypes = {
  200. 'html': 'text/html',
  201. 'js': 'text/javascript',
  202. 'css': 'text/css',
  203. 'png': 'image/png',
  204. 'jpg': 'image/jpeg'
  205. },
  206. message = function(room,from,message,origin,socket){
  207. if(typeof socket == 'undefined'){
  208. socket = io.sockets.in(room);
  209. }
  210. socket.emit('message',{
  211. message: message,
  212. room: room,
  213. from: from,
  214. origin: origin
  215. })
  216. },
  217. app = require('http').createServer(function(req,res){
  218. if(toobusy()){
  219. res.writeHead(503,{
  220. 'Content-type': 'text/plain'
  221. });
  222. res.write('503 Server busy.\n');
  223. res.end();
  224. return;
  225. }
  226. req.addListener('end',function(){
  227. logger.debug('served static content for '+req.url);
  228. var uri = url.parse(req.url).pathname,
  229. serveFile = function(filename,req,res){
  230. try{
  231. stats = fs.lstatSync(filename);
  232. }catch(e){
  233. res.writeHead(404,{
  234. 'Content-type': 'text/plain'
  235. });
  236. res.write('404 Not Found.\n');
  237. res.end();
  238. return;
  239. }
  240. if(stats.isFile()){
  241. var fileStream,
  242. mimetype = mimeTypes[path.extname(filename).split('.')[1]];
  243. res.writeHead(200,{
  244. 'Content-Type': mimetype
  245. });
  246. fileStream = fs.createReadStream(filename);
  247. fileStream.pipe(res);
  248. }else if(stats.isDirectory()){
  249. if(fs.existsSync(path.join(filename,'index.html'))){
  250. serveFile(path.join(filename,'index.html'),req,res);
  251. }else if(fs.existsSync(path.join(filename,'index.htm'))){
  252. serveFile(path.join(filename,'index.htm'),req,res);
  253. }else if(fs.existsSync(path.join(filename,'index.txt'))){
  254. serveFile(path.join(filename,'index.txt'),req,res);
  255. }else{
  256. res.writeHead(200,{
  257. 'Content-Type': 'text/plain'
  258. });
  259. res.write('Index of '+url+'\n');
  260. res.write('TODO, show index');
  261. res.end();
  262. }
  263. }else{
  264. res.writeHead(500,{
  265. 'Content-Type': 'text/plain'
  266. });
  267. res.write('500 Internal server error\n');
  268. res.end();
  269. }
  270. },
  271. filepath = unescape(uri);
  272. if(filepath.substr(0,5) == '/api/'){
  273. filepath = path.join(options.paths.api,filepath.substr(5));
  274. logger.debug('Attempting to run api script '+filepath);
  275. if(fs.existsSync(filepath)){
  276. fs.readFile(filepath,function(e,data){
  277. if(e){
  278. logger.error(e);
  279. res.end('null;');
  280. }else{
  281. var output = '',
  282. sandbox = {
  283. log: function(text){
  284. output += text;
  285. },
  286. error: function(msg){
  287. logger.error(msg);
  288. },
  289. info: function(msg){
  290. logger.info(msg);
  291. },
  292. debug: function(msg){
  293. logger.debug(msg);
  294. },
  295. head: {
  296. 'Content-Type': 'text/javascript'
  297. },
  298. returnCode: 200,
  299. vm: vm,
  300. fs: fs,
  301. options: options
  302. };
  303. vm.runInNewContext(data,sandbox,filepath);
  304. res.writeHead(sandbox.returnCode,sandbox.head);
  305. res.end(output);
  306. }
  307. });
  308. }else{
  309. res.writeHead(404,{
  310. 'Content-Type': 'text/javascript'
  311. });
  312. res.end('null;');
  313. }
  314. }else{
  315. serveFile(path.join(options.paths.www,filepath),req,res);
  316. }
  317. }).resume();
  318. }).listen(options.port),
  319. io = require('socket.io').listen(app);
  320. io.set('log level',options.loglevel);
  321. io.log = logger;
  322. if(typeof options.redis.password != 'undefined'){
  323. var eh = function(e){
  324. throw e;
  325. };
  326. pub.auth(options.redis.ppassword,eh);
  327. sub.auth(options.redis.ppassword,eh);
  328. client.auth(options.redis.ppassword,eh);
  329. }
  330. io.set('store', new RedisStore({
  331. redisPub : pub,
  332. redisSub : sub,
  333. redisClient : client
  334. }));
  335. io.sockets.on('connection',function(socket){
  336. socket.on('join',function(data){
  337. socket.join(data.name);
  338. data.title = data.name;
  339. socket.emit('join',{
  340. name: data.name
  341. });
  342. sendUserList(data.name);
  343. socket.get('nick',function(e,nick){
  344. logger.debug(nick+' joined '+data.name);
  345. fromServer(data.name,nick+' joined the channel');
  346. });
  347. });
  348. socket.on('part',function(data){
  349. socket.leave(data.name);
  350. socket.get('nick',function(e,nick){
  351. logger.debug(nick+' left '+data.name);
  352. sendUserList(data.name);
  353. });
  354. });
  355. socket.on('disconnect',function(data){
  356. var rooms = io.sockets.manager.rooms,
  357. i,
  358. room;
  359. for(i in rooms){
  360. if(rooms[i] != '' && typeof rooms[i] == 'string'){
  361. try{
  362. room = rooms[i].substr(1);
  363. }catch(e){}
  364. sendUserList(room);
  365. }
  366. }
  367. });
  368. socket.on('message',function(data){
  369. data.message = data.message.
  370. logger.debug('message sent to '+data.room);
  371. io.sockets.in(data.room).emit('message',data);
  372. process.send('M'+JSON.stringify(data));
  373. });
  374. socket.on('echo',function(data){
  375. logger.debug('echoing to '+data.room);
  376. socket.emit('message',data);
  377. });
  378. socket.on('names',function(data){
  379. var sockets = io.sockets.clients(data.name),
  380. i;
  381. runWithUserList(data.name,function(users){
  382. var temp = [],i;
  383. for(i in users) i && i != null && temp.push(users[i]);
  384. users = temp;
  385. fromServer(data.name,data.name+" users:\n\t\t"+users.join("\n\t\t"),socket);
  386. sendUserList(data.name);
  387. });
  388. });
  389. socket.on('auth',function(data){
  390. logger.info(data.nick+' registered');
  391. // TODO - authorize
  392. data.nick = data.nick.replace(/[\r\n]/g,'');
  393. socket.set('nick',data.nick.substr(0,12));
  394. socket.emit('authorized',{
  395. nick: data.nick.substr(0,12)
  396. });
  397. });
  398. var runWithUserList = function(room,callback){
  399. var sockets = io.sockets.clients(room),
  400. i = 0,
  401. ret = [],
  402. getNext = function(){
  403. if(i < sockets.length){
  404. sockets[i].get('nick',function(e,nick){
  405. if(e){
  406. logger.error(e);
  407. }else if(!inArray(ret,nick)){
  408. logger.debug(room+' '+nick);
  409. ret.push(nick);
  410. }
  411. i++;
  412. getNext();
  413. });
  414. }else{
  415. callback(ret);
  416. }
  417. };
  418. getNext();
  419. },
  420. inArray = function(arr,val){
  421. for(var i in arr){
  422. if(arr[i] == val){
  423. return true;
  424. }
  425. }
  426. return false;
  427. },
  428. sendUserList = function(room){
  429. if(typeof room != 'undefined'){
  430. runWithUserList(room,function(users){
  431. io.sockets.in(room).emit('names',{
  432. room: room,
  433. names: users
  434. });
  435. });
  436. }
  437. },
  438. fromServer = function(room,message,socket){
  439. if(typeof socket == 'undefined'){
  440. socket = io.sockets.in(room);
  441. }
  442. socket.emit('message',{
  443. message: message,
  444. room: room,
  445. from: 0,
  446. origin: 2
  447. });
  448. };
  449. });
  450. }
  451. process.on('uncaughtException',function(e){
  452. if(typeof logger != 'undefined'){
  453. logger.error(e);
  454. }else{
  455. console.error(e);
  456. }
  457. });