"use strict";
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemotePortConnector = void 0;
const dev_tunnels_ssh_1 = require("@microsoft/dev-tunnels-ssh");
const portForwardRequestMessage_1 = require("../messages/portForwardRequestMessage");
const portForwardSuccessMessage_1 = require("../messages/portForwardSuccessMessage");
const portForwardingService_1 = require("./portForwardingService");
/**
 * Base class for services that receive SSH channels forwarded from a remote port.
 */
class RemotePortConnector extends dev_tunnels_ssh_1.SshService {
    /* @internal */
    constructor(session, remoteIPAddress, remotePort) {
        super(session);
        this.forwarding = false;
        this.remoteIPAddress = remoteIPAddress;
        this.port = remotePort;
    }
    /**
     * Port that the remote server is listening on. If the request specified port 0, this
     * property returns the actual available port that was chosen by the server.
     */
    get remotePort() {
        return this.port;
    }
    /* @internal */
    async request(request, cancellation) {
        if (this.forwarding) {
            throw new Error('Already forwarding.');
        }
        request.addressToBind = this.remoteIPAddress;
        request.port = this.remotePort;
        request.wantReply = true;
        const response = await this.session.requestResponse(request, portForwardSuccessMessage_1.PortForwardSuccessMessage, dev_tunnels_ssh_1.SessionRequestFailureMessage, cancellation);
        let result = false;
        if (response instanceof portForwardSuccessMessage_1.PortForwardSuccessMessage) {
            if (response.port !== 0) {
                this.port = response.port;
            }
            result = true;
        }
        this.forwarding = result;
        return result;
    }
    dispose() {
        if (this.forwarding) {
            this.forwarding = false;
            const request = new portForwardRequestMessage_1.PortForwardRequestMessage();
            request.requestType = portForwardingService_1.PortForwardingService.cancelPortForwardRequestType;
            request.addressToBind = this.remoteIPAddress;
            request.port = this.remotePort;
            request.wantReply = false;
            try {
                this.session.request(request).catch((e) => {
                    // Ignore async cancel failure.
                    // Error details have already been trace.
                });
            }
            catch (e) { }
        }
        super.dispose();
    }
}
exports.RemotePortConnector = RemotePortConnector;
//# sourceMappingURL=https://github.com/VSCodium/sourcemaps/releases/download/stable-221e0a382c0be3a673a4e4cab0601344a0b3de3a/node_modules-@microsoft-dev-tunnels-ssh-tcp-services-remotePortConnector.js.map