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