OmnomIRC.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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.orgins[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. logger.debug('Child recieved command '+c+' with message '+msg);
  152. switch(c){
  153. case 'Q':
  154. if(typeof app != 'undefined' && typeof irc == 'undefined'){
  155. app.close();
  156. }else if(typeof irc != 'undefined'){
  157. irc.quit(options.irc.messages.quit);
  158. }
  159. break;
  160. case 'M':
  161. if(typeof irc != 'undefined'){
  162. msg = JSON.parse(msg);
  163. if(msg.message){
  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. app = require('http').createServer(function(req,res){
  207. if(toobusy()){
  208. res.writeHead(503,{
  209. 'Content-type': 'text/plain'
  210. });
  211. res.write('503 Server busy.\n');
  212. res.end();
  213. return;
  214. }
  215. req.addListener('end',function(){
  216. logger.debug('served static content for '+req.url);
  217. var uri = url.parse(req.url).pathname,
  218. serveFile = function(filename,req,res){
  219. try{
  220. stats = fs.lstatSync(filename);
  221. }catch(e){
  222. res.writeHead(404,{
  223. 'Content-type': 'text/plain'
  224. });
  225. res.write('404 Not Found.\n');
  226. res.end();
  227. return;
  228. }
  229. if(stats.isFile()){
  230. var fileStream,
  231. mimetype = mimeTypes[path.extname(filename).split('.')[1]];
  232. res.writeHead(200,{
  233. 'Content-Type': mimetype
  234. });
  235. fileStream = fs.createReadStream(filename);
  236. fileStream.pipe(res);
  237. }else if(stats.isDirectory()){
  238. if(fs.existsSync(path.join(filename,'index.html'))){
  239. serveFile(path.join(filename,'index.html'),req,res);
  240. }else if(fs.existsSync(path.join(filename,'index.htm'))){
  241. serveFile(path.join(filename,'index.htm'),req,res);
  242. }else if(fs.existsSync(path.join(filename,'index.txt'))){
  243. serveFile(path.join(filename,'index.txt'),req,res);
  244. }else{
  245. res.writeHead(200,{
  246. 'Content-Type': 'text/plain'
  247. });
  248. res.write('Index of '+url+'\n');
  249. res.write('TODO, show index');
  250. res.end();
  251. }
  252. }else{
  253. res.writeHead(500,{
  254. 'Content-Type': 'text/plain'
  255. });
  256. res.write('500 Internal server error\n');
  257. res.end();
  258. }
  259. },
  260. filepath = unescape(uri);
  261. if(filepath.substr(0,5) == '/api/'){
  262. filepath = path.join(options.paths.api,filepath.substr(5));
  263. logger.debug('Attempting to run api script '+filepath);
  264. if(fs.existsSync(filepath)){
  265. fs.readFile(filepath,function(e,data){
  266. if(e){
  267. logger.error(e);
  268. res.end('null;');
  269. }else{
  270. var output = '',
  271. sandbox = {
  272. log: function(text){
  273. output += text;
  274. },
  275. error: function(msg){
  276. logger.error(msg);
  277. },
  278. info: function(msg){
  279. logger.info(msg);
  280. },
  281. debug: function(msg){
  282. logger.debug(msg);
  283. },
  284. head: {
  285. 'Content-Type': 'text/javascript'
  286. },
  287. returnCode: 200,
  288. vm: vm,
  289. fs: fs,
  290. options: options
  291. };
  292. vm.runInNewContext(data,sandbox,filepath);
  293. res.writeHead(sandbox.returnCode,sandbox.head);
  294. res.end(output);
  295. }
  296. });
  297. }else{
  298. res.writeHead(404,{
  299. 'Content-Type': 'text/javascript'
  300. });
  301. res.end('null;');
  302. }
  303. }else{
  304. serveFile(path.join(options.paths.www,filepath),req,res);
  305. }
  306. }).resume();
  307. }).listen(options.port),
  308. io = require('socket.io').listen(app);
  309. io.set('log level',options.loglevel);
  310. io.log = logger;
  311. if(typeof options.redis.password != 'undefined'){
  312. var eh = function(e){
  313. throw e;
  314. };
  315. pub.auth(options.redis.ppassword,eh);
  316. sub.auth(options.redis.ppassword,eh);
  317. client.auth(options.redis.ppassword,eh);
  318. }
  319. io.set('store', new RedisStore({
  320. redisPub : pub,
  321. redisSub : sub,
  322. redisClient : client
  323. }));
  324. io.sockets.on('connection',function(socket){
  325. socket.on('join',function(data){
  326. socket.join(data.name);
  327. data.title = data.name;
  328. socket.emit('join',{
  329. name: data.name
  330. });
  331. sendUserList(data.name);
  332. socket.get('nick',function(e,nick){
  333. logger.debug(nick+' joined '+data.name);
  334. fromServer(data.name,nick+' joined the channel');
  335. });
  336. });
  337. socket.on('part',function(data){
  338. socket.leave(data.name);
  339. socket.get('nick',function(e,nick){
  340. logger.debug(nick+' left '+data.name);
  341. sendUserList(data.name);
  342. });
  343. });
  344. socket.on('disconnect',function(data){
  345. var rooms = io.sockets.manager.rooms,
  346. i,
  347. room;
  348. for(i in rooms){
  349. if(rooms[i] != '' && typeof rooms[i] == 'string'){
  350. try{
  351. room = rooms[i].substr(1);
  352. }catch(e){}
  353. sendUserList(room);
  354. }
  355. }
  356. });
  357. socket.on('message',function(data){
  358. logger.debug('message sent to '+data.room);
  359. io.sockets.in(data.room).emit('message',data);
  360. process.send('M'+JSON.stringify(data));
  361. });
  362. socket.on('echo',function(data){
  363. logger.debug('echoing to '+data.room);
  364. socket.emit('message',data);
  365. });
  366. socket.on('names',function(data){
  367. var sockets = io.sockets.clients(data.name),
  368. i;
  369. runWithUserList(data.name,function(users){
  370. var temp = [],i;
  371. for(i in users) i && i != null && temp.push(users[i]);
  372. users = temp;
  373. fromServer(data.name,data.name+" users:\n\t\t"+users.join("\n\t\t"),socket);
  374. sendUserList(data.name);
  375. });
  376. });
  377. socket.on('auth',function(data){
  378. logger.info(data.nick+' registered');
  379. // TODO - authorize
  380. socket.set('nick',data.nick.substr(0,12));
  381. socket.emit('authorized',{
  382. nick: data.nick.substr(0,12)
  383. });
  384. });
  385. var runWithUserList = function(room,callback){
  386. var sockets = io.sockets.clients(room),
  387. i = 0,
  388. ret = [],
  389. getNext = function(){
  390. if(i < sockets.length){
  391. sockets[i].get('nick',function(e,nick){
  392. if(e){
  393. logger.error(e);
  394. }else if(!inArray(ret,nick)){
  395. logger.debug(room+' '+nick);
  396. ret.push(nick);
  397. }
  398. i++;
  399. getNext();
  400. });
  401. }else{
  402. callback(ret);
  403. }
  404. };
  405. getNext();
  406. },
  407. inArray = function(arr,val){
  408. for(var i in arr){
  409. if(arr[i] == val){
  410. return true;
  411. }
  412. }
  413. return false;
  414. },
  415. sendUserList = function(room){
  416. if(typeof room != 'undefined'){
  417. runWithUserList(room,function(users){
  418. io.sockets.in(room).emit('names',{
  419. room: room,
  420. names: users
  421. });
  422. });
  423. }
  424. },message = function(room,from,message,origin,socket){
  425. if(typeof socket == 'undefined'){
  426. socket = io.sockets.in(room);
  427. }
  428. socket.emit('message',{
  429. message: message,
  430. room: room,
  431. from: from,
  432. origin: origin
  433. })
  434. },
  435. fromServer = function(room,message,socket){
  436. if(typeof socket == 'undefined'){
  437. socket = io.sockets.in(room);
  438. }
  439. socket.emit('message',{
  440. message: message,
  441. room: room,
  442. from: 0,
  443. origin: 2
  444. });
  445. };
  446. });
  447. }
  448. process.on('uncaughtException',function(e){
  449. if(typeof logger != 'undefined'){
  450. logger.error(e);
  451. }else{
  452. console.error(e);
  453. }
  454. });