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