From c96859f7ac22e36fea01d97792af30b216e89110 Mon Sep 17 00:00:00 2001 From: ale Date: Sat, 27 Dec 2025 04:09:36 +0100 Subject: [PATCH] fix tls connect Signed-off-by: ale --- src/core/xmpp-stream.js | 81 +++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 24 deletions(-) diff --git a/src/core/xmpp-stream.js b/src/core/xmpp-stream.js index e0643fa..06dd36e 100644 --- a/src/core/xmpp-stream.js +++ b/src/core/xmpp-stream.js @@ -25,6 +25,12 @@ class StreamParser extends EventEmitter { this.parse(); } + reset() { + this.buffer = ''; + this.depth = 0; + this.streamStarted = false; + } + parse() { // Find complete stanzas in buffer let startIdx = 0; @@ -148,6 +154,11 @@ class XMPPStream extends EventEmitter { } setupSocket() { + // Reset parser for stream restart (after TLS upgrade) + if (this.parser) { + this.parser.reset(); + } + this.socket.on('data', (data) => { try { if (this.parser) { @@ -308,33 +319,55 @@ class XMPPStream extends EventEmitter { }); this.send(proceed); - // Get TLS options - const tlsOptions = this.getTLSOptions(); - - // Upgrade socket to TLS - const secureSocket = tls.connect({ - socket: this.socket, - ...tlsOptions, - rejectUnauthorized: false - }, () => { - this.logger.debug('TLS upgrade successful'); - - // Update socket and restart stream - this.socket = secureSocket; - this.secure = true; - - // Setup socket handlers for new socket - this.setupSocket(); - - // Reset state for stream restart - this.setState('wait-for-stream'); - this.streamId = this.generateStreamId(); + // Small delay to ensure data is flushed before upgrading + setImmediate(() => { + this.upgradeTLS(); }); + } - secureSocket.on('error', (error) => { - this.logger.error('TLS upgrade error:', error); + upgradeTLS() { + try { + // Get TLS options + const tlsOptions = this.getTLSOptions(); + + // Remove old data handler - we'll recreate it + this.socket.removeAllListeners('data'); + + // Create TLS socket wrapping the existing plain socket + const tlsSocket = new tls.TLSSocket(this.socket, { + ...tlsOptions, + isServer: true, + rejectUnauthorized: false + }); + + tlsSocket.on('secure', () => { + this.logger.debug('TLS upgrade successful'); + + // Update socket reference + this.socket = tlsSocket; + this.secure = true; + + // Re-setup socket handlers with new socket + this.setupSocket(); + + // Reset stream for restart + this.setState('wait-for-stream'); + this.streamId = this.generateStreamId(); + }); + + tlsSocket.on('error', (error) => { + this.logger.error('TLS upgrade error:', error); + this.close(); + }); + + tlsSocket.on('close', () => { + this.handleClose(); + }); + + } catch (error) { + this.logger.error('Error upgrading TLS:', error); this.close(); - }); + } } getTLSOptions() {