client emu can now download binary files
This commit is contained in:
@@ -10,7 +10,7 @@ const WTVShared = require('./includes/classes/WTVShared.js')['WTVShared'];
|
|||||||
* using the WTVP protocol with proper authentication and service discovery.
|
* using the WTVP protocol with proper authentication and service discovery.
|
||||||
*/
|
*/
|
||||||
class WebTVClientSimulator {
|
class WebTVClientSimulator {
|
||||||
constructor(host, port, ssid, url, outputFile = null, maxRedirects = 10, useEncryption = false, request_type_download = false) {
|
constructor(host, port, ssid, url, outputFile = null, maxRedirects = 10, useEncryption = false, request_type_download = false, debug = false) {
|
||||||
this.host = host;
|
this.host = host;
|
||||||
this.port = port;
|
this.port = port;
|
||||||
this.ssid = ssid;
|
this.ssid = ssid;
|
||||||
@@ -31,16 +31,23 @@ class WebTVClientSimulator {
|
|||||||
this.currentSocket = null;
|
this.currentSocket = null;
|
||||||
this.challengeResponse = null;
|
this.challengeResponse = null;
|
||||||
this.initial_key = null; // Store initial key from wtv-initial-key header
|
this.initial_key = null; // Store initial key from wtv-initial-key header
|
||||||
|
this.debug = debug;
|
||||||
|
|
||||||
// Load minisrv config to get the initial shared key
|
// Load minisrv config to get the initial shared key
|
||||||
this.minisrv_config = this.wtvshared.readMiniSrvConfig(true, false);
|
this.minisrv_config = this.wtvshared.readMiniSrvConfig(true, false);
|
||||||
console.log(`WebTV Client Simulator starting...`);
|
this.debugLog(`WebTV Client Simulator starting...`);
|
||||||
console.log(`Target: ${host}:${port}`);
|
this.debugLog(`Target: ${host}:${port}`);
|
||||||
console.log(`SSID: ${ssid}`);
|
this.debugLog(`SSID: ${ssid}`);
|
||||||
console.log(`Target URL after auth: ${url}`);
|
this.debugLog(`Target URL after auth: ${url}`);
|
||||||
console.log(`Encryption: ${useEncryption ? 'enabled' : 'disabled'}`);
|
this.debugLog(`Encryption: ${useEncryption ? 'enabled' : 'disabled'}`);
|
||||||
if (outputFile) {
|
if (outputFile) {
|
||||||
console.log(`Output file: ${outputFile}`);
|
this.debugLog(`Output file: ${outputFile}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
debugLog(...args) {
|
||||||
|
if (this.debug) {
|
||||||
|
console.log(...args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,14 +77,14 @@ class WebTVClientSimulator {
|
|||||||
targetPort = service.port;
|
targetPort = service.port;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`\n--- Making request to ${serviceName}:${path} at ${targetHost}:${targetPort} ---`);
|
this.debugLog(`\n--- Making request to ${serviceName}:${path} at ${targetHost}:${targetPort} ---`);
|
||||||
|
|
||||||
const socket = new net.Socket();
|
const socket = new net.Socket();
|
||||||
this.currentSocket = socket;
|
this.currentSocket = socket;
|
||||||
let responseData = Buffer.alloc(0);
|
let responseData = Buffer.alloc(0);
|
||||||
|
|
||||||
socket.connect(targetPort, targetHost, () => {
|
socket.connect(targetPort, targetHost, () => {
|
||||||
console.log(`Connected to ${targetHost}:${targetPort}`);
|
this.debugLog(`Connected to ${targetHost}:${targetPort}`);
|
||||||
|
|
||||||
let requestData;
|
let requestData;
|
||||||
|
|
||||||
@@ -89,12 +96,12 @@ class WebTVClientSimulator {
|
|||||||
requestData = this.buildRegularRequest(serviceName, path, data);
|
requestData = this.buildRegularRequest(serviceName, path, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('Sending request:');
|
this.debugLog('Sending request:');
|
||||||
if (this.encryptionEnabled) {
|
if (this.encryptionEnabled) {
|
||||||
console.log('[ENCRYPTED REQUEST]');
|
this.debugLog('[ENCRYPTED REQUEST]');
|
||||||
console.log(`Length: ${requestData.length} bytes`);
|
this.debugLog(`Length: ${requestData.length} bytes`);
|
||||||
} else {
|
} else {
|
||||||
console.log(requestData.toString());
|
this.debugLog(requestData.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.write(requestData);
|
socket.write(requestData);
|
||||||
@@ -102,32 +109,41 @@ class WebTVClientSimulator {
|
|||||||
|
|
||||||
socket.on('data', (chunk) => {
|
socket.on('data', (chunk) => {
|
||||||
responseData = Buffer.concat([responseData, chunk]);
|
responseData = Buffer.concat([responseData, chunk]);
|
||||||
console.log(`Received chunk: ${chunk.length} bytes`);
|
this.debugLog(`Received chunk: ${chunk.length} bytes`);
|
||||||
|
|
||||||
// Check if we have a complete response
|
// Check if we have a complete response
|
||||||
if (this.encryptionEnabled) {
|
if (this.encryptionEnabled) {
|
||||||
// For encrypted responses, we need to handle differently
|
// For encrypted responses, we need to handle differently
|
||||||
this.handleEncryptedResponse(responseData, resolve, reject);
|
this.handleEncryptedResponse(responseData, resolve, reject);
|
||||||
} else {
|
} else {
|
||||||
// Regular response handling
|
// Regular response handling
|
||||||
const responseStr = responseData.toString();
|
// Only check for header/body split, do not convert to string
|
||||||
if (responseStr.includes('\n\n')) {
|
// Use both CRLF and LF as in handleResponse
|
||||||
console.log('Complete response detected, processing...');
|
const crlfcrlf = Buffer.from('\r\n\r\n');
|
||||||
this.handleResponse(responseStr, resolve, reject, skipRedirects);
|
const lflf = Buffer.from('\n\n');
|
||||||
|
let idx = responseData.indexOf(crlfcrlf);
|
||||||
|
if (idx === -1) idx = responseData.indexOf(lflf);
|
||||||
|
if (idx !== -1) {
|
||||||
|
this.debugLog('Complete response detected, processing...');
|
||||||
|
this.handleResponse(responseData, resolve, reject, skipRedirects);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('close', () => {
|
socket.on('close', () => {
|
||||||
console.log('Connection closed');
|
this.debugLog('Connection closed');
|
||||||
if (responseData.length > 0 && !this.encryptionEnabled) {
|
if (responseData.length > 0 && !this.encryptionEnabled) {
|
||||||
const responseStr = responseData.toString();
|
// Only process if not already processed
|
||||||
if (!responseStr.includes('\n\n')) {
|
const crlfcrlf = Buffer.from('\r\n\r\n');
|
||||||
console.log('Processing incomplete response on close...');
|
const lflf = Buffer.from('\n\n');
|
||||||
this.handleResponse(responseStr, resolve, reject, skipRedirects);
|
let idx = responseData.indexOf(crlfcrlf);
|
||||||
|
if (idx === -1) idx = responseData.indexOf(lflf);
|
||||||
|
if (idx === -1) {
|
||||||
|
this.debugLog('Processing incomplete response on close...');
|
||||||
|
this.handleResponse(responseData, resolve, reject, skipRedirects);
|
||||||
}
|
}
|
||||||
} else if (responseData.length > 0 && this.encryptionEnabled) {
|
} else if (responseData.length > 0 && this.encryptionEnabled) {
|
||||||
console.log('Processing encrypted response on close...');
|
this.debugLog('Processing encrypted response on close...');
|
||||||
this.handleEncryptedResponse(responseData, resolve, reject);
|
this.handleEncryptedResponse(responseData, resolve, reject);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -139,7 +155,7 @@ class WebTVClientSimulator {
|
|||||||
|
|
||||||
// Set timeout
|
// Set timeout
|
||||||
socket.setTimeout(30000, () => {
|
socket.setTimeout(30000, () => {
|
||||||
console.log('Request timed out');
|
console.error('Request timed out');
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
reject(new Error('Request timeout'));
|
reject(new Error('Request timeout'));
|
||||||
});
|
});
|
||||||
@@ -167,7 +183,7 @@ class WebTVClientSimulator {
|
|||||||
// Add challenge response if we have one
|
// Add challenge response if we have one
|
||||||
if (this.challengeResponse) {
|
if (this.challengeResponse) {
|
||||||
request += `wtv-challenge-response: ${this.challengeResponse}\r\n`;
|
request += `wtv-challenge-response: ${this.challengeResponse}\r\n`;
|
||||||
console.log('Added challenge response to request');
|
this.debugLog('Added challenge response to request');
|
||||||
this.challengeResponse = null; // Clear challenge response after adding to request
|
this.challengeResponse = null; // Clear challenge response after adding to request
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,16 +277,16 @@ class WebTVClientSimulator {
|
|||||||
const bodyStart = headerEndIndex + 2;
|
const bodyStart = headerEndIndex + 2;
|
||||||
const bodyBuffer = responseData.slice(bodyStart);
|
const bodyBuffer = responseData.slice(bodyStart);
|
||||||
|
|
||||||
console.log('\nReceived encrypted response:');
|
this.debugLog('\nReceived encrypted response:');
|
||||||
console.log('Headers:');
|
this.debugLog('Headers:');
|
||||||
console.log(headerSection);
|
this.debugLog(headerSection);
|
||||||
|
|
||||||
// Parse headers
|
// Parse headers
|
||||||
const lines = headerSection.split('\n');
|
const lines = headerSection.split('\n');
|
||||||
const statusLine = lines[0].replace('\r', '');
|
const statusLine = lines[0].replace('\r', '');
|
||||||
|
|
||||||
console.log(`Status: ${statusLine}`);
|
this.debugLog(`Status: ${statusLine}`);
|
||||||
|
|
||||||
const headers = {};
|
const headers = {};
|
||||||
for (let i = 1; i < lines.length; i++) {
|
for (let i = 1; i < lines.length; i++) {
|
||||||
const line = lines[i].replace('\r', '');
|
const line = lines[i].replace('\r', '');
|
||||||
@@ -283,19 +299,19 @@ class WebTVClientSimulator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Decrypt the body if we have encryption enabled
|
// Decrypt the body if we have encryption enabled
|
||||||
let body = '';
|
let body = Buffer.alloc(0);
|
||||||
if (bodyBuffer.length > 0 && headers['wtv-encrypted'] === 'true' && this.wtvsec) {
|
if (bodyBuffer.length > 0 && headers['wtv-encrypted'] === 'true' && this.wtvsec) {
|
||||||
try {
|
try {
|
||||||
console.log('Decrypting response body...');
|
this.debugLog('Decrypting response body...');
|
||||||
const decryptedBuffer = this.wtvsec.Decrypt(1, bodyBuffer);
|
const decryptedBuffer = this.wtvsec.Decrypt(1, bodyBuffer);
|
||||||
body = Buffer.from(decryptedBuffer).toString('utf8');
|
body = Buffer.from(decryptedBuffer);
|
||||||
console.log('Body decrypted successfully');
|
this.debugLog('Body decrypted successfully');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error decrypting response body:', error);
|
console.error('Error decrypting response body:', error);
|
||||||
body = bodyBuffer.toString('utf8');
|
body = bodyBuffer;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
body = bodyBuffer.toString('utf8');
|
body = bodyBuffer;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle special headers
|
// Handle special headers
|
||||||
@@ -315,27 +331,40 @@ class WebTVClientSimulator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
handleResponse(responseData, resolve, reject, skipRedirects = false) {
|
handleResponse(responseData, resolve, reject, skipRedirects = false) {
|
||||||
console.log('\nReceived response:');
|
this.debugLog('\nReceived response:');
|
||||||
console.log(responseData);
|
this.debugLog(responseData);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// WTVP uses \n\n for header separation, not \r\n\r\n
|
// Find header/body split using CRLF CRLF (\r\n\r\n) or fallback to LF LF (\n\n)
|
||||||
const [headerSection, body] = responseData.split('\n\n', 2);
|
let idx = -1;
|
||||||
const lines = headerSection.split('\n');
|
let sepLen = 0;
|
||||||
const statusLine = lines[0].replace('\r', ''); // Remove any \r characters
|
const crlfcrlf = Buffer.from('\r\n\r\n');
|
||||||
|
const lflf = Buffer.from('\n\n');
|
||||||
console.log(`Status: ${statusLine}`);
|
idx = responseData.indexOf(crlfcrlf);
|
||||||
|
if (idx !== -1) {
|
||||||
|
sepLen = 4;
|
||||||
|
} else {
|
||||||
|
idx = responseData.indexOf(lflf);
|
||||||
|
if (idx !== -1) sepLen = 2;
|
||||||
|
}
|
||||||
|
let headerSection, bodyBuf;
|
||||||
|
if (idx !== -1) {
|
||||||
|
headerSection = responseData.slice(0, idx).toString('utf8');
|
||||||
|
bodyBuf = responseData.slice(idx + sepLen);
|
||||||
|
} else {
|
||||||
|
headerSection = responseData.toString('utf8');
|
||||||
|
bodyBuf = Buffer.alloc(0);
|
||||||
|
}
|
||||||
|
const lines = headerSection.split(/\r?\n/);
|
||||||
|
const statusLine = lines[0].replace('\r', '');
|
||||||
|
this.debugLog(`Status: ${statusLine}`);
|
||||||
// Parse headers
|
// Parse headers
|
||||||
const headers = {};
|
const headers = {};
|
||||||
for (let i = 1; i < lines.length; i++) {
|
for (let i = 1; i < lines.length; i++) {
|
||||||
const line = lines[i].replace('\r', ''); // Remove any \r characters
|
const line = lines[i].replace('\r', '');
|
||||||
const colonIndex = line.indexOf(':');
|
const colonIndex = line.indexOf(':');
|
||||||
if (colonIndex > 0) {
|
if (colonIndex > 0) {
|
||||||
const key = line.substring(0, colonIndex).toLowerCase();
|
const key = line.substring(0, colonIndex).toLowerCase();
|
||||||
const value = line.substring(colonIndex + 1).trim();
|
const value = line.substring(colonIndex + 1).trim();
|
||||||
|
|
||||||
// Handle multiple headers with the same name (like wtv-service)
|
|
||||||
if (headers[key]) {
|
if (headers[key]) {
|
||||||
if (Array.isArray(headers[key])) {
|
if (Array.isArray(headers[key])) {
|
||||||
headers[key].push(value);
|
headers[key].push(value);
|
||||||
@@ -347,20 +376,14 @@ class WebTVClientSimulator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle special headers
|
|
||||||
this.processHeaders(headers);
|
this.processHeaders(headers);
|
||||||
|
|
||||||
// Close current connection before following wtv-visit
|
|
||||||
if (this.currentSocket) {
|
if (this.currentSocket) {
|
||||||
this.currentSocket.destroy();
|
this.currentSocket.destroy();
|
||||||
this.currentSocket = null;
|
this.currentSocket = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if user-id was detected (authentication successful) and target URL not yet fetched
|
|
||||||
if (this.userIdDetected && !this.targetUrlFetched) {
|
if (this.userIdDetected && !this.targetUrlFetched) {
|
||||||
this.targetUrlFetched = true; // Set flag to prevent multiple fetches
|
this.targetUrlFetched = true;
|
||||||
console.log(`\n*** Authentication complete! Now fetching target URL: ${this.url} ***`);
|
this.debugLog(`\n*** Authentication complete! Now fetching target URL: ${this.url} ***`);
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.fetchTargetUrl()
|
this.fetchTargetUrl()
|
||||||
.then(resolve)
|
.then(resolve)
|
||||||
@@ -368,31 +391,27 @@ class WebTVClientSimulator {
|
|||||||
}, 100);
|
}, 100);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Follow wtv-visit if present and not authenticated yet, and not skipping redirects
|
|
||||||
if (headers['wtv-visit'] && !skipRedirects) {
|
if (headers['wtv-visit'] && !skipRedirects) {
|
||||||
if (this.redirectCount >= this.maxRedirects) {
|
if (this.redirectCount >= this.maxRedirects) {
|
||||||
console.log(`Maximum redirects (${this.maxRedirects}) reached, stopping`);
|
this.debugLog(`Maximum redirects (${this.maxRedirects}) reached, stopping`);
|
||||||
resolve({ headers, body, status: statusLine, stopped: true });
|
resolve({ headers, body: bodyBuf, status: statusLine, stopped: true });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.redirectCount++;
|
this.redirectCount++;
|
||||||
console.log(`Following wtv-visit (${this.redirectCount}/${this.maxRedirects}): ${headers['wtv-visit']}`);
|
this.debugLog(`Following wtv-visit (${this.redirectCount}/${this.maxRedirects}): ${headers['wtv-visit']}`);
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.followVisit(headers['wtv-visit'])
|
this.followVisit(headers['wtv-visit'])
|
||||||
.then(resolve)
|
.then(resolve)
|
||||||
.catch(reject);
|
.catch(reject);
|
||||||
}, 100); // Reduced timeout for faster response
|
}, 100);
|
||||||
} else {
|
} else {
|
||||||
if (skipRedirects && headers['wtv-visit']) {
|
if (skipRedirects && headers['wtv-visit']) {
|
||||||
console.log(`Skipping wtv-visit redirect: ${headers['wtv-visit']}`);
|
this.debugLog(`Skipping wtv-visit redirect: ${headers['wtv-visit']}`);
|
||||||
} else {
|
} else {
|
||||||
console.log('No wtv-visit header found, resolving...');
|
this.debugLog('No wtv-visit header found, resolving...');
|
||||||
}
|
}
|
||||||
resolve({ headers, body, status: statusLine });
|
resolve({ headers, body: bodyBuf, status: statusLine });
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error processing response:', error);
|
console.error('Error processing response:', error);
|
||||||
reject(error);
|
reject(error);
|
||||||
@@ -410,7 +429,7 @@ class WebTVClientSimulator {
|
|||||||
|
|
||||||
for (const serviceValue of serviceValues) {
|
for (const serviceValue of serviceValues) {
|
||||||
if (serviceValue === 'reset') {
|
if (serviceValue === 'reset') {
|
||||||
console.log('Clearing service mappings');
|
this.debugLog('Clearing service mappings');
|
||||||
this.services.clear();
|
this.services.clear();
|
||||||
} else {
|
} else {
|
||||||
// Parse service definition: "name=service-name host=host port=port flags=0x00000001 connections=1"
|
// Parse service definition: "name=service-name host=host port=port flags=0x00000001 connections=1"
|
||||||
@@ -424,7 +443,7 @@ class WebTVClientSimulator {
|
|||||||
const port = parseInt(portMatch[1]);
|
const port = parseInt(portMatch[1]);
|
||||||
|
|
||||||
this.services.set(serviceName, { host, port });
|
this.services.set(serviceName, { host, port });
|
||||||
console.log(`Registered service: ${serviceName} -> ${host}:${port}`);
|
this.debugLog(`Registered service: ${serviceName} -> ${host}:${port}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -437,9 +456,9 @@ class WebTVClientSimulator {
|
|||||||
|
|
||||||
// Handle wtv-challenge
|
// Handle wtv-challenge
|
||||||
if (headers['wtv-challenge']) {
|
if (headers['wtv-challenge']) {
|
||||||
console.log('Received wtv-challenge, processing...');
|
this.debugLog('Received wtv-challenge, processing...');
|
||||||
if (!this.wtvsec) {
|
if (!this.wtvsec) {
|
||||||
console.log('No WTVSec instance, initializing with default key...');
|
this.debugLog('No WTVSec instance, initializing with default key...');
|
||||||
this.wtvsec = new WTVSec(this.minisrv_config, this.incarnation);
|
this.wtvsec = new WTVSec(this.minisrv_config, this.incarnation);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -448,11 +467,11 @@ class WebTVClientSimulator {
|
|||||||
this.wtvsec.set_incarnation(headers["wtv-incarnation"]);
|
this.wtvsec.set_incarnation(headers["wtv-incarnation"]);
|
||||||
const challengeResponse = this.wtvsec.ProcessChallenge(headers['wtv-challenge'], CryptoJS.enc.Base64.parse(this.initial_key));
|
const challengeResponse = this.wtvsec.ProcessChallenge(headers['wtv-challenge'], CryptoJS.enc.Base64.parse(this.initial_key));
|
||||||
if (challengeResponse && challengeResponse.toString(CryptoJS.enc.Base64)) {
|
if (challengeResponse && challengeResponse.toString(CryptoJS.enc.Base64)) {
|
||||||
console.log('Challenge processed successfully, preparing response');
|
this.debugLog('Challenge processed successfully, preparing response');
|
||||||
// We'll send the challenge response in the next request
|
// We'll send the challenge response in the next request
|
||||||
this.challengeResponse = challengeResponse.toString(CryptoJS.enc.Base64);
|
this.challengeResponse = challengeResponse.toString(CryptoJS.enc.Base64);
|
||||||
//this.incarnation = this.wtvsec.incarnation;
|
//this.incarnation = this.wtvsec.incarnation;
|
||||||
console.log('Setting wtv-challenge-response header for next request');
|
this.debugLog('Setting wtv-challenge-response header for next request');
|
||||||
} else {
|
} else {
|
||||||
console.error('Failed to process challenge - no response generated');
|
console.error('Failed to process challenge - no response generated');
|
||||||
}
|
}
|
||||||
@@ -463,18 +482,18 @@ class WebTVClientSimulator {
|
|||||||
|
|
||||||
// Handle wtv-ticket
|
// Handle wtv-ticket
|
||||||
if (headers['wtv-ticket']) {
|
if (headers['wtv-ticket']) {
|
||||||
console.log('Received wtv-ticket');
|
this.debugLog('Received wtv-ticket');
|
||||||
this.ticket = headers['wtv-ticket'];
|
this.ticket = headers['wtv-ticket'];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle user-id header - indicates successful authentication
|
// Handle user-id header - indicates successful authentication
|
||||||
if (headers['user-id']) {
|
if (headers['user-id']) {
|
||||||
console.log(`*** Authentication successful! user-id detected: ${headers['user-id']} ***`);
|
this.debugLog(`*** Authentication successful! user-id detected: ${headers['user-id']} ***`);
|
||||||
this.userIdDetected = true;
|
this.userIdDetected = true;
|
||||||
|
|
||||||
// Enable encryption if requested and we have WTVSec
|
// Enable encryption if requested and we have WTVSec
|
||||||
if (this.useEncryption && this.wtvsec && !this.encryptionEnabled) {
|
if (this.useEncryption && this.wtvsec && !this.encryptionEnabled) {
|
||||||
console.log('*** Enabling encryption after successful authentication ***');
|
this.debugLog('*** Enabling encryption after successful authentication ***');
|
||||||
this.wtvsec.SecureOn(); // Initialize RC4 sessions
|
this.wtvsec.SecureOn(); // Initialize RC4 sessions
|
||||||
this.encryptionEnabled = true;
|
this.encryptionEnabled = true;
|
||||||
}
|
}
|
||||||
@@ -487,14 +506,14 @@ class WebTVClientSimulator {
|
|||||||
* Follow a wtv-visit directive
|
* Follow a wtv-visit directive
|
||||||
*/
|
*/
|
||||||
async followVisit(visitUrl) {
|
async followVisit(visitUrl) {
|
||||||
console.log(`Parsing wtv-visit URL: ${visitUrl}`);
|
this.debugLog(`Parsing wtv-visit URL: ${visitUrl}`);
|
||||||
|
|
||||||
// Parse the visit URL: service:/path or service:path
|
// Parse the visit URL: service:/path or service:path
|
||||||
const match = visitUrl.match(/^([\w-]+):\/?(.*)/);
|
const match = visitUrl.match(/^([\w-]+):\/?(.*)/);
|
||||||
if (match) {
|
if (match) {
|
||||||
const serviceName = match[1];
|
const serviceName = match[1];
|
||||||
const path = '/' + (match[2] || '');
|
const path = '/' + (match[2] || '');
|
||||||
console.log(`Parsed service: ${serviceName}, path: ${path}`);
|
this.debugLog(`Parsed service: ${serviceName}, path: ${path}`);
|
||||||
return await this.makeRequest(serviceName, path);
|
return await this.makeRequest(serviceName, path);
|
||||||
} else {
|
} else {
|
||||||
throw new Error(`Invalid wtv-visit URL: ${visitUrl}`);
|
throw new Error(`Invalid wtv-visit URL: ${visitUrl}`);
|
||||||
@@ -506,13 +525,13 @@ class WebTVClientSimulator {
|
|||||||
*/
|
*/
|
||||||
async fetchTargetUrl() {
|
async fetchTargetUrl() {
|
||||||
console.log(`Fetching target URL: ${this.url}`);
|
console.log(`Fetching target URL: ${this.url}`);
|
||||||
|
|
||||||
// If encryption is enabled, send SECURE ON first
|
// If encryption is enabled, send SECURE ON first
|
||||||
if (this.encryptionEnabled) {
|
if (this.encryptionEnabled) {
|
||||||
console.log('Sending SECURE ON command...');
|
this.debugLog('Sending SECURE ON command...');
|
||||||
try {
|
try {
|
||||||
await this.makeRequest('SECURE ON', '', '', {});
|
await this.makeRequest('SECURE ON', '', '', {});
|
||||||
console.log('Encryption successfully enabled');
|
this.debugLog('Encryption successfully enabled');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to enable encryption:', error.message);
|
console.error('Failed to enable encryption:', error.message);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -524,25 +543,31 @@ class WebTVClientSimulator {
|
|||||||
if (match) {
|
if (match) {
|
||||||
const serviceName = match[1];
|
const serviceName = match[1];
|
||||||
const path = '/' + (match[2] || '');
|
const path = '/' + (match[2] || '');
|
||||||
console.log(`Parsed target service: ${serviceName}, path: ${path}`);
|
this.debugLog(`Parsed target service: ${serviceName}, path: ${path}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await this.makeRequest(serviceName, path, null, true); // Skip redirects for target URL
|
const result = await this.makeRequest(serviceName, path, null, true); // Skip redirects for target URL
|
||||||
|
|
||||||
// Handle the response
|
// Handle the response
|
||||||
if (result.body) {
|
if (result.body) {
|
||||||
console.log('\n*** Target URL Response Body ***');
|
this.debugLog('\n*** Target URL Response Body ***');
|
||||||
if (this.outputFile) {
|
if (this.outputFile) {
|
||||||
await this.saveToFile(result.body);
|
await this.saveToFile(result.body);
|
||||||
console.log(`Content saved to: ${this.outputFile}`);
|
console.log(`Content saved to: ${this.outputFile}`);
|
||||||
} else {
|
} else {
|
||||||
console.log(result.body);
|
// Detect text content for CLI output
|
||||||
|
const contentType = result.headers['content-type'] || '';
|
||||||
|
if (/^text\//.test(contentType) || /json|xml|javascript/.test(contentType)) {
|
||||||
|
console.log(result.body.toString('utf8'));
|
||||||
|
} else {
|
||||||
|
console.log('<binary data>');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log('No body content received from target URL');
|
this.debugLog('No body content received from target URL');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('\n*** Request completed successfully ***');
|
this.debugLog('\n*** Request completed successfully ***');
|
||||||
this.cleanup();
|
this.cleanup();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|
||||||
@@ -561,13 +586,29 @@ class WebTVClientSimulator {
|
|||||||
*/
|
*/
|
||||||
processContentResponse(responseData, resolve, reject) {
|
processContentResponse(responseData, resolve, reject) {
|
||||||
try {
|
try {
|
||||||
// WTVP uses \n\n for header separation
|
// Find header/body split using CRLF CRLF (\r\n\r\n) or fallback to LF LF (\n\n)
|
||||||
const [headerSection, body] = responseData.split('\n\n', 2);
|
let idx = -1;
|
||||||
const lines = headerSection.split('\n');
|
let sepLen = 0;
|
||||||
|
const crlfcrlf = Buffer.from('\r\n\r\n');
|
||||||
|
const lflf = Buffer.from('\n\n');
|
||||||
|
idx = responseData.indexOf(crlfcrlf);
|
||||||
|
if (idx !== -1) {
|
||||||
|
sepLen = 4;
|
||||||
|
} else {
|
||||||
|
idx = responseData.indexOf(lflf);
|
||||||
|
if (idx !== -1) sepLen = 2;
|
||||||
|
}
|
||||||
|
let headerSection, bodyBuf;
|
||||||
|
if (idx !== -1) {
|
||||||
|
headerSection = responseData.slice(0, idx).toString('utf8');
|
||||||
|
bodyBuf = responseData.slice(idx + sepLen);
|
||||||
|
} else {
|
||||||
|
headerSection = responseData.toString('utf8');
|
||||||
|
bodyBuf = Buffer.alloc(0);
|
||||||
|
}
|
||||||
|
const lines = headerSection.split(/\r?\n/);
|
||||||
const statusLine = lines[0].replace('\r', '');
|
const statusLine = lines[0].replace('\r', '');
|
||||||
|
this.debugLog(`Content Status: ${statusLine}`);
|
||||||
console.log(`Content Status: ${statusLine}`);
|
|
||||||
|
|
||||||
// Parse headers
|
// Parse headers
|
||||||
const headers = {};
|
const headers = {};
|
||||||
for (let i = 1; i < lines.length; i++) {
|
for (let i = 1; i < lines.length; i++) {
|
||||||
@@ -579,15 +620,11 @@ class WebTVClientSimulator {
|
|||||||
headers[key] = value;
|
headers[key] = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close current connection
|
|
||||||
if (this.currentSocket) {
|
if (this.currentSocket) {
|
||||||
this.currentSocket.destroy();
|
this.currentSocket.destroy();
|
||||||
this.currentSocket = null;
|
this.currentSocket = null;
|
||||||
}
|
}
|
||||||
|
resolve({ headers, body: bodyBuf, status: statusLine });
|
||||||
resolve({ headers, body: body || '', status: statusLine });
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error processing content response:', error);
|
console.error('Error processing content response:', error);
|
||||||
reject(error);
|
reject(error);
|
||||||
@@ -600,7 +637,7 @@ class WebTVClientSimulator {
|
|||||||
async saveToFile(content) {
|
async saveToFile(content) {
|
||||||
const fs = require('fs').promises;
|
const fs = require('fs').promises;
|
||||||
try {
|
try {
|
||||||
await fs.writeFile(this.outputFile, content, 'utf8');
|
await fs.writeFile(this.outputFile, Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8'));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error saving to file:', error);
|
console.error('Error saving to file:', error);
|
||||||
throw error;
|
throw error;
|
||||||
@@ -630,7 +667,8 @@ function parseArgs() {
|
|||||||
outputFile: null,
|
outputFile: null,
|
||||||
maxRedirects: 10,
|
maxRedirects: 10,
|
||||||
useEncryption: false,
|
useEncryption: false,
|
||||||
request_type_download: false
|
request_type_download: false,
|
||||||
|
debug: false
|
||||||
};
|
};
|
||||||
|
|
||||||
for (let i = 0; i < args.length; i++) {
|
for (let i = 0; i < args.length; i++) {
|
||||||
@@ -671,6 +709,9 @@ function parseArgs() {
|
|||||||
case '--encryption':
|
case '--encryption':
|
||||||
config.useEncryption = true;
|
config.useEncryption = true;
|
||||||
break;
|
break;
|
||||||
|
case '--debug':
|
||||||
|
config.debug = true;
|
||||||
|
break;
|
||||||
case '--help':
|
case '--help':
|
||||||
console.log(`
|
console.log(`
|
||||||
WebTV Client Simulator
|
WebTV Client Simulator
|
||||||
@@ -686,6 +727,7 @@ Options:
|
|||||||
--max-redirects <num> Maximum number of wtv-visit redirects (default: 10)
|
--max-redirects <num> Maximum number of wtv-visit redirects (default: 10)
|
||||||
--download Enable 'wtv-request-type: download' for diskmap testing)
|
--download Enable 'wtv-request-type: download' for diskmap testing)
|
||||||
--encryption Enable RC4 encryption after authentication
|
--encryption Enable RC4 encryption after authentication
|
||||||
|
--debug Enable debug logging
|
||||||
--help Show this help message
|
--help Show this help message
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
@@ -703,7 +745,7 @@ Example:
|
|||||||
*/
|
*/
|
||||||
async function main() {
|
async function main() {
|
||||||
const config = parseArgs();
|
const config = parseArgs();
|
||||||
const simulator = new WebTVClientSimulator(config.host, config.port, config.ssid, config.url, config.outputFile, config.maxRedirects, config.useEncryption, config.request_type_download);
|
const simulator = new WebTVClientSimulator(config.host, config.port, config.ssid, config.url, config.outputFile, config.maxRedirects, config.useEncryption, config.request_type_download, config.debug);
|
||||||
|
|
||||||
// Handle graceful shutdown
|
// Handle graceful shutdown
|
||||||
process.on('SIGINT', () => {
|
process.on('SIGINT', () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user