32 lines
10 KiB
JavaScript
32 lines
10 KiB
JavaScript
import {AudioController} from './audio-controller.mjs';
|
|
import net from 'node:net';import fs from 'node:fs/promises';import {spawn,execFile} from 'node:child_process';import {promisify} from 'node:util';import crypto from 'node:crypto';import {defaults,validate,prepareSave} from './config.mjs';import {T,packet,Parser} from './protocol.mjs';import {Chrome} from './cdp.mjs';import {convert,adpcm} from './media.mjs';
|
|
const exec=promisify(execFile),dir=process.env.STATE_DIRECTORY||'/var/lib/mars-browser',sock=process.env.RUNTIME_DIRECTORY?process.env.RUNTIME_DIRECTORY+'/admin.sock':'/run/mars-browser/admin.sock';
|
|
let stopping=false;
|
|
let engineVersion='Nicht geprüft';
|
|
let cfg=validate(defaults),listener=null,sessions=new Map(),revision=0,adminBusy=false,listenerError='';
|
|
try{cfg=validate(JSON.parse(await fs.readFile(dir+'/config.json','utf8')));}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
const audioServer=process.env.PULSE_SERVER;const audio=new AudioController({managed:process.env.MARS_MANAGED_AUDIO==='1',server:audioServer});const clock=()=>Number(process.hrtime.bigint()/1000000n)>>>0;
|
|
function send(s,t,b){if(!s.socket.destroyed)s.socket.write(packet(t,b,clock()));}
|
|
function status(){return {config:cfg,revision,engineVersion,listen:!!listener?.listening,listenerError:listenerError,sessions:[...sessions.values()].map(s=>({id:s.id,peer:s.socket.remoteAddress,width:s.w,height:s.h,codec:s.codec,frames:s.frames,audio:!!s.audio,url:s.url||''})),audioAvailable:audio.available,audioPid:audio.pid,audioError:audio.error};}
|
|
function close(s){if(s.closing)return s.closing;s.dead=true;clearInterval(s.tick);clearTimeout(s.authTimer);s.socket.destroy();s.audio?.kill();s.closing=(async()=>{if(s.chrome)await s.chrome.close().catch(()=>{});if(s.module)await exec('/usr/bin/pactl',['unload-module',s.module],{timeout:3000}).catch(()=>{});sessions.delete(s.id);})();return s.closing;}
|
|
async function startAudio(s){if(!cfg.audio||!s.wantAudio)return {};if(!audio.available)return {};const name='mars_'+s.id;const {stdout}=await exec('/usr/bin/pactl',['load-module','module-null-sink','sink_name='+name],{timeout:5000});s.module=stdout.trim();if(!/^\d+$/.test(s.module))throw Error('PulseAudio Modul');s.sink=name;return {PULSE_SINK:name};}
|
|
function captureAudio(s){if(!s.sink)return;const rate=cfg.audioRate,ch=cfg.audioChannels,frames=Math.floor(rate/20),size=frames*ch*2;let buf=Buffer.alloc(0);s.audio=spawn('/usr/bin/ffmpeg',['-nostdin','-loglevel','error','-f','pulse','-i',s.sink+'.monitor','-ac',String(ch),'-ar',String(rate),'-f','s16le','pipe:1'],{stdio:['ignore','pipe','ignore']});s.audio.on('error',e=>send(s,T.ERROR,e.message));s.audio.on('exit',()=>{s.audio=null;});s.audio.stdout.on('data',b=>{buf=Buffer.concat([buf,b]);while(buf.length>=size){let pcm=buf.subarray(0,size);buf=buf.subarray(size);if(s.socket.writableLength>128*1024)continue;const h=Buffer.alloc(8);h.writeUInt32BE(rate);h[4]=ch;h[5]=cfg.audioCodec==='ima-adpcm'?2:1;h.writeUInt16BE(frames,6);send(s,T.AUDIO,Buffer.concat([h,h[5]===2?adpcm(pcm,ch):Buffer.from(pcm).swap16()]));}});}
|
|
async function frame(s){if(s.dead||!s.ready||s.rendering||s.socket.writableLength>65536)return;s.rendering=true;try{const {data}=await s.chrome.call('Page.captureScreenshot',{format:'jpeg',quality:cfg.quality,fromSurface:true});const jpeg=Buffer.from(data,'base64'),hash=crypto.createHash('sha256').update(jpeg).digest('hex');if(hash===s.hash)return;const pixels=await convert(jpeg,s.w,s.h,s.codec);if(s.dead||s.socket.writableLength>65536)return;const h=Buffer.alloc(6);h.writeUInt16BE(s.w);h.writeUInt16BE(s.h,2);h[4]={jpeg:1,rgb565:2,rle565:3}[s.codec];send(s,T.FRAME,Buffer.concat([h,pixels]));s.hash=hash;s.frames++;}catch(e){send(s,T.ERROR,e.message);await close(s);}finally{s.rendering=false;}}
|
|
function urlAllowed(v){const u=new URL(v);if(!['http:','https:'].includes(u.protocol)||u.username||u.password)throw Error('Nur HTTP(S) ohne Zugangsdaten');if(!cfg.allowPrivate&&(/^(localhost|.*\.localhost|.*\.local)$/i.test(u.hostname)||net.isIP(u.hostname.replace(/^\[|\]$/g,''))))throw Error('Lokale und numerische Ziele deaktiviert; Netzwerkfilter zusätzlich erforderlich');return u.href;}
|
|
async function message(s,t,b){s.last=Date.now();if(!s.auth){if(t!==T.AUTH||b.length!==64||!crypto.timingSafeEqual(b,Buffer.from(cfg.token)))throw Error('Anmeldung fehlgeschlagen');s.auth=true;clearTimeout(s.authTimer);send(s,T.HELLO,JSON.stringify({width:cfg.width,height:cfg.height,codec:cfg.codec,audio:cfg.audio&&audio.available}));return;}
|
|
if(!s.ready){if(t!==T.HELLO||s.chrome||b.length!==6)throw Error('HELLO erwartet');s.w=Math.min(cfg.width,b.readUInt16BE(0));s.h=Math.min(cfg.height,b.readUInt16BE(2));if(s.w<160||s.h<100)throw Error('Auflösung');const bits=b[4];s.codec=(bits&({jpeg:1,rgb565:2,rle565:4}[cfg.codec]))?cfg.codec:bits&2?'rgb565':bits&4?'rle565':bits&1?'jpeg':null;if(!s.codec)throw Error('Kein gemeinsamer Codec');s.wantAudio=!!b[5];s.chrome=new Chrome();const env=await startAudio(s);if(s.dead){if(s.module)await exec("/usr/bin/pactl",["unload-module",s.module],{timeout:3000}).catch(()=>{});return;}await s.chrome.start({...cfg,width:s.w,height:s.h},env);if(s.dead){await s.chrome.close();return;}s.ready=true;send(s,T.READY);captureAudio(s);s.tick=setInterval(()=>{if(Date.now()-s.last>cfg.idleSeconds*1000)close(s);else frame(s);},Math.ceil(1000/cfg.fps));return;}
|
|
const c=s.chrome;switch(t){case T.NAV:{if(b.length>4096)throw Error('URL zu lang');const url=urlAllowed(b.toString('utf8'));const r=await c.call('Page.navigate',{url});if(r.errorText)throw Error(r.errorText);s.url=url;s.hash=null;break;}case T.TEXT:if(b.length>4096)throw Error('Text zu lang');await c.call('Input.insertText',{text:b.toString('utf8')});break;
|
|
case T.MOUSE:{if(b.length!==8)throw Error('Mouse');const type=['mouseMoved','mousePressed','mouseReleased','mouseWheel'][b[0]],button=['none','left','middle','right'][b[1]];if(!type||!button)throw Error('Mouse');const mask=[0,1,4,2][b[1]];if(b[0]===1)s.buttons=(s.buttons||0)|mask;if(b[0]===2)s.buttons=(s.buttons||0)&~mask;const p={type,x:Math.min(s.w-1,b.readUInt16BE(2)),y:Math.min(s.h-1,b.readUInt16BE(4)),button,buttons:s.buttons||0};if(b[0]===3){p.deltaX=0;p.deltaY=b.readInt16BE(6);}else if(b[0]!==0)p.clickCount=1;await c.call('Input.dispatchMouseEvent',p);break;}
|
|
case T.KEY:{if(b.length<2||b.length>65)throw Error('Key');const key=b.subarray(1).toString();const map={Enter:13,Backspace:8,Tab:9,Escape:27,ArrowLeft:37,ArrowUp:38,ArrowRight:39,ArrowDown:40,Delete:46,Home:36,End:35,PageUp:33,PageDown:34};await c.call('Input.dispatchKeyEvent',{type:b[0]?'keyDown':'keyUp',key,windowsVirtualKeyCode:map[key]||0});break;}
|
|
case T.BACK:case T.FORWARD:{const h=await c.call('Page.getNavigationHistory');const e=h.entries[h.currentIndex+(t===T.BACK?-1:1)];if(e)await c.call('Page.navigateToHistoryEntry',{entryId:e.id});break;}case T.RELOAD:await c.call('Page.reload');break;case T.STOP:await c.call('Page.stopLoading');break;case T.PING:send(s,T.PONG);break;default:throw Error('Unbekannte Nachricht');}}
|
|
function accept(socket){if(stopping||adminBusy||sessions.size>=cfg.maxSessions){socket.end(packet(T.ERROR,'Sitzungslimit'));return;}socket.setNoDelay(true);const s={id:crypto.randomBytes(8).toString('hex'),socket,frames:0,last:Date.now(),chain:Promise.resolve(),queued:0};sessions.set(s.id,s);s.authTimer=setTimeout(()=>close(s),5000);const parser=new Parser((t,b)=>{if(++s.queued>64){close(s);return;}s.chain=s.chain.then(async()=>{if(!s.dead)await message(s,t,b);}).catch(e=>{if(!s.dead){send(s,T.ERROR,e.message);if(!s.ready)close(s);}}).finally(()=>s.queued--);});socket.on('data',b=>{try{parser.feed(b);}catch{close(s);}});socket.on('error',()=>close(s));socket.on('close',()=>close(s));}
|
|
async function apply(next,tolerateAudioFailure=false){await Promise.all([...sessions.values()].map(close));if(listener){await new Promise(r=>listener.close(r));listener=null;}listenerError='';try{await audio.ensure(next.enabled&&next.audio);}catch(e){if(!tolerateAudioFailure)throw e;console.error('Audio: '+e.message);}if(next.enabled){const l=net.createServer(accept);await new Promise((resolve,reject)=>{l.once('error',reject);l.listen(next.port,next.bind,()=>{l.removeListener('error',reject);resolve();});});l.on('error',e=>{listenerError=e.message;});listener=l;}}
|
|
async function version(){try{engineVersion=(await exec('/usr/bin/'+cfg.engine,['--version'],{timeout:5000})).stdout.trim();}catch{engineVersion='Nicht installiert oder nicht ausführbar';}}
|
|
try{await apply(cfg,true);}catch(e){listenerError=e.message;}
|
|
await version();setInterval(version,60000).unref();
|
|
// Recover a crashed audio subprocess without restarting NetWare or the listener.
|
|
setInterval(async()=>{if(stopping||adminBusy||!audio.managed||!cfg.enabled||!cfg.audio||audio.available)return;adminBusy=true;try{await Promise.all([...sessions.values()].filter(s=>s.sink).map(close));await audio.ensure(true);}catch(e){console.error('Audio: '+e.message);}finally{adminBusy=false;}},5000).unref();
|
|
await fs.mkdir(dir,{recursive:true,mode:0o700});await fs.rm(sock,{force:true});
|
|
const admin=net.createServer(c=>{let b='';c.setTimeout(15000,()=>c.destroy());c.on('error',()=>{});c.on('data',async chunk=>{b+=chunk.toString();if(b.length>16384)return c.destroy();if(!b.includes('\n'))return;c.pause();try{const r=JSON.parse(b.split('\n')[0]);if(r.op==='get')return c.end(JSON.stringify(status())+'\n');if(adminBusy)throw Error('Änderung läuft');adminBusy=true;try{if(r.op==='save'||r.op==='rotate-token'){if(r.revision!==revision)throw Error('Konfiguration neu laden');const next=prepareSave(r.op==='rotate-token'?cfg:r.config,cfg,r.op==='rotate-token');const old=cfg;try{await apply(next);const temp=dir+'/config.tmp';await fs.writeFile(temp,JSON.stringify(next,null,2),{mode:0o600});await fs.rename(temp,dir+'/config.json');cfg=next;revision++;await version();}catch(e){await apply(old,true).catch(e=>{listenerError=e.message;});throw e;}}else if(r.op==='disconnect'){const s=sessions.get(r.id);if(s)await close(s);}else throw Error('Aktion');c.end(JSON.stringify(status())+'\n');}finally{adminBusy=false;}}catch(e){c.end(JSON.stringify({error:e.message})+'\n');}});});admin.listen(sock,()=>fs.chmod(sock,0o600));
|
|
for(const sig of ['SIGTERM','SIGINT'])process.on(sig,async()=>{if(stopping)return;stopping=true;admin.close();await Promise.all([...sessions.values()].map(close));listener?.close();await audio.stop();process.exit(0);});
|