OmnomIRC.js 11 KB

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