OmnomIRC.js 11 KB

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