aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/projectexplorer/devicesupport/deviceusedportsgatherer.cpp
blob: 714d311a1ef288fa1d1fa7a86b70ea97ebada97e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "deviceusedportsgatherer.h"

#include "idevice.h"
#include "sshparameters.h"
#include "../projectexplorertr.h"

#include <remotelinux/remotelinux_constants.h>

#include <utils/port.h>
#include <utils/portlist.h>
#include <utils/qtcprocess.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/url.h>

using namespace Utils;

namespace ProjectExplorer {
namespace Internal {

class DeviceUsedPortsGathererPrivate
{
public:
    std::unique_ptr<Process> process;
    QList<Port> usedPorts;
    IDevice::ConstPtr device;
    PortsGatheringMethod portsGatheringMethod;
    QString m_errorString;
};

} // namespace Internal

DeviceUsedPortsGatherer::DeviceUsedPortsGatherer(QObject *parent)
    : QObject(parent)
    , d(new Internal::DeviceUsedPortsGathererPrivate)
{}

DeviceUsedPortsGatherer::~DeviceUsedPortsGatherer()
{
    stop();
    delete d;
}

void DeviceUsedPortsGatherer::start()
{
    const auto emitError = [this](const QString &errorString) {
        d->m_errorString = errorString;
        emit done(false);
    };

    d->usedPorts.clear();
    d->m_errorString.clear();
    QTC_ASSERT(d->device, emitError("No device given"); return);

    d->portsGatheringMethod = d->device->portsGatheringMethod();
    QTC_ASSERT(d->portsGatheringMethod.commandLine, emitError("Not implemented"); return);
    QTC_ASSERT(d->portsGatheringMethod.parsePorts, emitError("Not implemented"); return);

    const QAbstractSocket::NetworkLayerProtocol protocol = QAbstractSocket::AnyIPProtocol;

    d->process.reset(new Process);
    d->process->setCommand(d->portsGatheringMethod.commandLine(protocol));

    connect(d->process.get(), &Process::done, this, [this, emitError] {
        if (d->process->result() == ProcessResult::FinishedWithSuccess) {
            d->usedPorts.clear();
            const QList<Port> usedPorts = d->portsGatheringMethod.parsePorts(
                d->process->rawStdOut());
            for (const Port port : usedPorts) {
                if (d->device->freePorts().contains(port))
                    d->usedPorts << port;
            }
            emit done(true);
        } else {
            const QString errorString = d->process->errorString();
            const QString stdErr = d->process->readAllStandardError();
            const QString outputString
                = stdErr.isEmpty() ? stdErr : Tr::tr("Remote error output was: %1").arg(stdErr);
            emitError(Utils::joinStrings({errorString, outputString}, '\n'));
        }
        stop();
    });
    d->process->start();
}

void DeviceUsedPortsGatherer::stop()
{
    if (d->process) {
        d->process->disconnect();
        d->process.release()->deleteLater();
    }
}

void DeviceUsedPortsGatherer::setDevice(const IDeviceConstPtr &device)
{
    d->device = device;
}

QList<Port> DeviceUsedPortsGatherer::usedPorts() const
{
    return d->usedPorts;
}

QString DeviceUsedPortsGatherer::errorString() const
{
    return d->m_errorString;
}

// PortGatherer

PortsGatherer::PortsGatherer(RunControl *runControl)
   : RunWorker(runControl)
{
    setId("PortGatherer");

    connect(&m_portsGatherer, &DeviceUsedPortsGatherer::done, this, [this](bool success) {
        if (success) {
            m_portList = device()->freePorts();
            appendMessage(Tr::tr("Found %n free ports.", nullptr, m_portList.count()),
                          NormalMessageFormat);
            reportStarted();
        } else {
            reportFailure(m_portsGatherer.errorString());
        }
    });
}

void PortsGatherer::start()
{
    appendMessage(Tr::tr("Checking available ports..."), NormalMessageFormat);
    m_portsGatherer.setDevice(device());
    m_portsGatherer.start();
}

QUrl PortsGatherer::findEndPoint()
{
    QUrl result;
    result.setScheme(urlTcpScheme());
    result.setHost(device()->sshParameters().host());
    result.setPort(m_portList.getNextFreePort(m_portsGatherer.usedPorts()).number());
    return result;
}

void PortsGatherer::stop()
{
    m_portsGatherer.stop();
    reportStopped();
}

namespace Internal {

// SubChannelProvider

/*!
    \class ProjectExplorer::SubChannelProvider

    \internal

    This is a helper RunWorker implementation to either use or not
    use port forwarding for one SubChannel in the ChannelProvider
    implementation.

    By default it is assumed that no forwarding is needed, i.e.
    end points provided by the shared endpoint resource provider
    are directly accessible.
*/

class SubChannelProvider : public RunWorker
{
public:
    SubChannelProvider(RunControl *runControl, PortsGatherer *portsGatherer)
        : RunWorker(runControl)
        , m_portGatherer(portsGatherer)
    {
        setId("SubChannelProvider");
    }

    void start() final
    {
        m_channel.setScheme(urlTcpScheme());
        if (device()->extraData(RemoteLinux::Constants::SshForwardDebugServerPort).toBool())
            m_channel.setHost("localhost");
        else
            m_channel.setHost(device()->toolControlChannel(IDevice::ControlChannelHint()).host());
        if (m_portGatherer)
            m_channel.setPort(m_portGatherer->findEndPoint().port());
        reportStarted();
    }

    QUrl channel() const { return m_channel; }

private:
    QUrl m_channel;
    PortsGatherer *m_portGatherer = nullptr;
};

} // Internal

// ChannelProvider

/*!
    \class ProjectExplorer::ChannelProvider

    \internal

    The class implements a \c RunWorker to provide
    to provide a set of urls indicating usable connection end
    points for 'server-using' tools (typically one, like plain
    gdbserver and the Qml tooling, but two for mixed debugging).

    Urls can describe local or tcp servers that are directly
    accessible to the host tools.

    The tool implementations can assume that any needed port
    forwarding setup is setup and handled transparently by
    a \c ChannelProvider instance.

    If there are multiple subchannels needed that need to share a
    common set of resources on the remote side, a device implementation
    can provide a "SharedEndpointGatherer" RunWorker.

    If none is provided, it is assumed that the shared resource
    is open TCP ports, provided by the device's PortGatherer i
    implementation.

    FIXME: The current implementation supports only the case
    of "any number of TCP channels that do not need actual
    forwarding.
*/

ChannelProvider::ChannelProvider(RunControl *runControl, int requiredChannels)
   : RunWorker(runControl)
{
    setId("ChannelProvider");
    auto portsGatherer = new PortsGatherer(runControl);

    for (int i = 0; i < requiredChannels; ++i) {
        auto channelProvider = new Internal::SubChannelProvider(runControl, portsGatherer);
        m_channelProviders.append(channelProvider);
        addStartDependency(channelProvider);
    }
}

ChannelProvider::~ChannelProvider() = default;

QUrl ChannelProvider::channel(int i) const
{
    if (Internal::SubChannelProvider *provider = m_channelProviders.value(i))
        return provider->channel();
    return {};
}

} // namespace ProjectExplorer