// 7plus interoperability: radix-216, 31-bit words and per-line CRC checks. // Format reference: 7PLUS 2.25 by Axel Bauda DG1BBQ (original C sources). // This module never executes attachments or writes decoded files to the BBS. import {readFile,stat} from 'node:fs/promises'; import path from 'node:path'; import {createHash} from 'node:crypto'; import {safeName,mimeOf} from './attachments.mjs'; const alphabet=[]; for(const [start,end]of [[0x21,0x29],[0x2b,0x7e],[0x80,0x90],[0x92,0x92],[0x94,0xfc]])for(let b=start;b<=end;b++)alphabet.push(b); const digits=new Int16Array(256).fill(-1);alphabet.forEach((b,i)=>digits[b]=i); const table=Array.from({length:256},(_,n)=>{let v=n<<8;for(let bit=0;bit<8;bit++)v=((v<<1)^((v&0x8000)?0x1021:0))&0xffff;return v;}); function crc(bytes){let value=0;for(const byte of bytes)value=table[value>>>8]^(((value&255)<<8)|byte);return value;} function digit(byte){const n=digits[byte];if(n<0||n===undefined)throw new Error('Carattere 7plus non valido');return n;} function miniValid(line){const at=line.indexOf(Buffer.from([0xb0,0xb1]));return at>=0&&line.length>at+4&&crc(line.subarray(0,at+4))%216===digits[line[at+4]];} function secondValid(line){return line.length===69&&(crc(Buffer.from(line.subarray(0,67)).reverse())&0x7fff)===digit(line[67])+216*digit(line[68]);} const digest=bytes=>createHash('sha256').update(bytes).digest('hex'); export function decodeSevenLine(line){ if(line.length!==69)throw new Error('Riga 7plus incompleta (attesi 69 byte)'); const sequence=digit(line[64])+216*digit(line[65])+216*216*digit(line[66]); if((crc(line.subarray(0,64))&0x3fff)!==(sequence&0x3fff)||!secondValid(line))throw new Error('Controllo CRC della riga non valido'); const out=Buffer.alloc(62); for(let block=0;block<2;block++){ let bits=0n;for(let word=0;word<8;word++){const at=(block*8+word)*4;let value=0;for(let j=3;j>=0;j--)value=value*216+digit(line[at+j]);if(value>0x7fffffff)throw new Error('Parola 7plus fuori intervallo');bits=(bits<<31n)|BigInt(value);} for(let i=30;i>=0;i--){out[block*31+i]=Number(bits&255n);bits>>=8n;} } return {number:sequence>>>14,data:out}; } export function scanSevenPlus(bytes,id,sender=''){ const lines=bytes.toString('latin1').split(/\r\n|\n|\r/),blocks=[]; const from=lines.find(l=>/^From:\s*/i.test(l))?.replace(/^From:\s*/i,'').trim().toUpperCase()||String(sender).toUpperCase(); for(let i=0;i255||part>total||size<1||size>32*1024*1024||blockLines<1||blockLines>512||Math.ceil(Math.ceil(size/62)/blockLines)!==total)issue='Metadati 7plus non validi'; if(!miniValid(Buffer.from(header,'latin1')))issue='CRC dell’intestazione non valido'; if(!footer||!stamp||!miniValid(Buffer.from(footer,'latin1')))issue='Fine parte mancante o CRC della chiusura non valido'; const key=digest(Buffer.from([from,name.toUpperCase(),size,total,blockLines,stamp||''].join('|'))); const footName=footer?.match(/^ stop_7\+\.\s+\(([^)]+)\)/i)?.[1]?.toUpperCase();const stem=name.replace(/\.[^.]+$/,'').toUpperCase();const expectedFoot=total===1?stem+'.7PL':stem+'.P'+part.toString(16).toUpperCase().padStart(2,'0')+'/'+total.toString(16).toUpperCase().padStart(2,'0');if(footName!==expectedFoot)issue='Chiusura della parte discordante con l’intestazione'; const valid=new Map();let bad=0; if(!issue)for(const line of body){if(!line.length)continue;try{const decoded=decodeSevenLine(line);const expected=Math.min(blockLines,Math.ceil(size/62)-(part-1)*blockLines);if(decoded.number>=expected)throw new Error('Numero riga fuori parte');const prior=valid.get(decoded.number);if(prior&&!prior.equals(decoded.data)){issue='Righe duplicate discordanti';throw new Error(issue);}valid.set(decoded.number,decoded.data);}catch{bad++;}} blocks.push({id,from,name,part,total,size,blockLines,stamp,key,issue,valid,bad,hash:digest(Buffer.from(header+'\n'+body.map(b=>b.toString('latin1')).join('\n')+'\n'+footer,'latin1'))}); } return blocks; } export function assembleSevenPlus(blocks){ if(!blocks.length)return null;const first=blocks[0],group=blocks.filter(b=>b.key===first.key),parts=new Map();for(const b of group){if(!parts.has(b.part))parts.set(b.part,[]);parts.get(b.part).push(b);} const metadata={name:first.name,part:first.part,total:first.total,size:first.size,availableParts:[...parts.keys()].sort((a,b)=>a-b),missingParts:[],damagedParts:[],messageIds:[...new Set(group.map(b=>b.id))].sort((a,b)=>a-b),state:'incomplete',issues:[]}; if(first.total<1||first.total>255||first.part<1||first.part>first.total||first.blockLines<1||first.blockLines>512||first.size<1||first.size>32*1024*1024||Math.ceil(Math.ceil(first.size/62)/first.blockLines)!==first.total){metadata.state='damaged';metadata.issues.push('Metadati 7plus fuori limite');return {metadata,file:null};} const pieces=[]; for(let part=1;part<=first.total;part++){ const candidates=parts.get(part);if(!candidates){metadata.missingParts.push(part);continue;} const rows=new Map();let conflict=false; for(const block of candidates.filter(b=>!b.issue))for(const [number,bytes]of block.valid){if(rows.has(number)&&!rows.get(number).equals(bytes))conflict=true;else rows.set(number,bytes);} const count=Math.min(first.blockLines,Math.ceil(first.size/62)-(part-1)*first.blockLines);let missing=false; for(let n=0;nb.issue).filter(Boolean))]; if(metadata.missingParts.length||metadata.damagedParts.length){metadata.state=metadata.missingParts.length?'incomplete':'damaged';return {metadata,file:null};} const data=Buffer.concat(pieces).subarray(0,first.size),mime=mimeOf(data,first.name); if(data.length!==first.size||(/\.jpe?g$/i.test(first.name)&&(mime!=='image/jpeg'||data[data.length-2]!==255||data[data.length-1]!==217))){metadata.state='damaged';metadata.issues.push('Il file ricostruito non corrisponde al formato o alla dimensione dichiarata');return {metadata,file:null};} metadata.state='complete';metadata.sha256=digest(data); return {metadata,file:{name:first.name,size:data.length,mime,data,reconstructed:true,parts:first.total}}; } export class SevenPlus{ constructor(root){this.root=root;this.scanned=new Map();this.cache=new Map();} async forMessage(id,list){ const blocks=[]; for(const item of list){ const file=path.join(this.root,'BPQMailChat','Mail','m_'+String(item.id).padStart(6,'0')+'.mes'); try{const info=await stat(file);if(info.size>2*1024*1024)continue;const key=info.size+':'+info.mtimeMs;let cached=this.scanned.get(item.id);if(cached?.key!==key){cached={key,blocks:scanSevenPlus(await readFile(file),item.id,item.from)};this.scanned.set(item.id,cached);}blocks.push(...cached.blocks);}catch{} } const visible=new Set(list.map(m=>m.id));for(const key of this.scanned.keys())if(!visible.has(key))this.scanned.delete(key); const requested=blocks.find(b=>b.id===Number(id));if(!requested)return null; const group=blocks.filter(b=>b.key===requested.key);const signature=digest(Buffer.from(group.map(b=>b.hash+':'+b.id).join('|')));let result=this.cache.get(signature); if(!result){result=assembleSevenPlus([requested,...group.filter(b=>b!==requested)]);this.cache.set(signature,result);let total=0;for(const r of this.cache.values())total+=r.file?.size||0;while(this.cache.size>16||total>64*1024*1024){const key=this.cache.keys().next().value;total-=this.cache.get(key).file?.size||0;this.cache.delete(key);}} return {...result,metadata:{...result.metadata,part:requested.part}}; } }