File: portmanager.cpp

package info (click to toggle)
ostinato 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 4,840 kB
  • sloc: cpp: 46,226; makefile: 8
file content (278 lines) | stat: -rw-r--r-- 8,479 bytes parent folder | download | duplicates (2)
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
Copyright (C) 2010-2012 Srivats P.

This file is part of "Ostinato"

This is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
*/

#include "portmanager.h"

#include "bsdport.h"
#include "interfaceinfo.h"
#include "linuxport.h"
#include "pcapport.h"
#include "settings.h"
#include "turbo.h"
#include "winpcapport.h"

#include <QHostAddress>
#include <QStringList>

PortManager *PortManager::instance_ = NULL;

#if defined(Q_OS_WIN32)
#include <QUuid>
#include <ipHlpApi.h>
// Define the function prototypes since they are not defined in ipHlpApi.h
NETIO_STATUS WINAPI ConvertInterfaceGuidToLuid(
        const GUID *InterfaceGuid, PNET_LUID InterfaceLuid);
NETIO_STATUS WINAPI ConvertInterfaceLuidToAlias(
        const NET_LUID *InterfaceLuid, PWSTR InterfaceAlias, SIZE_T Length);

#define MyGetProcAddress(hDll, function) \
    hDll ? reinterpret_cast<decltype(&function)> (GetProcAddress(hDll, #function)) : NULL;
#endif

PortManager::PortManager()
{
    int i;
    pcap_if_t *device;
    AbstractPort::Accuracy txRateAccuracy;

    qDebug("PCAP Lib: %s", pcap_lib_version());
#ifdef Q_OS_WIN32
    qDebug("Service npf status %s\n", pcapServiceStatus(L"npf"));
    qDebug("Service npcap status %s\n", pcapServiceStatus(L"npcap"));
#endif

    qDebug("Retrieving the device list from the local machine\n"); 

#if defined(Q_OS_WIN32)
    WinPcapPort::fetchHostNetworkInfo();
#elif defined(Q_OS_LINUX)
    LinuxPort::fetchHostNetworkInfo();
#elif defined(Q_OS_BSD4)
    BsdPort::fetchHostNetworkInfo();
#endif

    txRateAccuracy = rateAccuracy();

    pcap_if_t *deviceList = GetPortList();

    for(device = deviceList, i = 0; device != NULL; device = device->next, i++)
    {
        AbstractPort *port = nullptr;
      
        qDebug("==========\n%d. %s", i, device->name);
        if (device->description)
            qDebug(" (%s)\n", device->description);

#if defined(Q_OS_WIN32)
        if (!filterAcceptsPort(device->description))
#else
        if (!filterAcceptsPort(device->name))
#endif
        {
            qDebug("%s (%s) rejected by filter. Skipping!",
                    device->name, device->description);
            i--;
            continue;
        }

#if defined(Q_OS_WIN32)
        port = new WinPcapPort(i, device->name, device->description);
#elif defined(Q_OS_LINUX)
        if (isTurboPort(device->name))
            port = createTurboPort(i, device->name);
        if (!port)
            port = new LinuxPort(i, device->name);
#elif defined(Q_OS_BSD4)
        port = new BsdPort(i, device->name);
#else
        port = new PcapPort(i, device->name);
#endif

        if (port && !port->isUsable())
        {
            qDebug("%s: unable to open %s. Skipping!", __FUNCTION__,
                    device->name);
            delete port;
            i--;
            continue;
        }

        const InterfaceInfo *intfInfo = port->interfaceInfo();
        if (intfInfo) {
            qDebug("Mac: %012llx", intfInfo->mac);
            foreach(Ip4Config ip, intfInfo->ip4)
                qDebug("Ip4: %s/%d gw: %s",
                        qPrintable(QHostAddress(ip.address).toString()),
                        ip.prefixLength,
                        qPrintable(QHostAddress(ip.gateway).toString()));
            foreach(Ip6Config ip, intfInfo->ip6)
                qDebug("Ip6: %s/%d gw: %s",
                        qPrintable(QHostAddress(ip.address.toArray()).toString()),
                        ip.prefixLength,
                        qPrintable(QHostAddress(ip.gateway.toArray()).toString()));
            qDebug("Speed: %g Mbps", intfInfo->speed);
            qDebug("Mtu: %u", intfInfo->mtu);
        }

        if (!port->setRateAccuracy(txRateAccuracy))
            qWarning("failed to set rateAccuracy (%d)", txRateAccuracy);

        portList_.append(port);
    }

    FreePortList(deviceList);

    foreach(AbstractPort *port, portList_)
        port->init();
    
#if defined(Q_OS_WIN32)
    WinPcapPort::freeHostNetworkInfo();
#elif defined(Q_OS_LINUX)
    LinuxPort::freeHostNetworkInfo();
#elif defined(Q_OS_BSD4)
    BsdPort::freeHostNetworkInfo();
#endif

    return;
}

PortManager::~PortManager()
{
    while (!portList_.isEmpty())
        delete portList_.takeFirst();
}

PortManager* PortManager::instance()
{
    if (!instance_)
        instance_ = new PortManager;

    return instance_;       
}

pcap_if_t* PortManager::GetPortList()
{
    pcap_if_t *deviceList = NULL;
    char errbuf[PCAP_ERRBUF_SIZE];

    if (pcap_findalldevs(&deviceList, errbuf) == -1)
        qDebug("Error in pcap_findalldevs_ex: %s\n", errbuf);

#if defined(Q_OS_WIN32)
    // Use windows' connection name as the description for a better UX
    ipHlpApi_ = LoadLibrary(TEXT("ipHlpApi.dll"));
    auto guid2Luid = MyGetProcAddress(ipHlpApi_, ConvertInterfaceGuidToLuid);
    auto luid2Alias = MyGetProcAddress(ipHlpApi_, ConvertInterfaceLuidToAlias);

    if (guid2Luid && luid2Alias) {
        pcap_if_t *device;
        for(device = deviceList; device != NULL; device = device->next) {
            GUID guid = static_cast<GUID>(QUuid(
                            QString(device->name).remove("\\Device\\NPF_")));
            NET_LUID luid;

            oldDescriptions_.append(device->description);
            newDescriptions_.append(new QByteArray());
            if (guid2Luid(&guid, &luid) == NO_ERROR) {
                WCHAR conn[256];
                if (luid2Alias(&luid, conn, 256) == NO_ERROR) {
                    *(newDescriptions_.last()) = QString().fromWCharArray(conn)
                                                            .toLocal8Bit();
                    device->description = newDescriptions_.last()->data();
                }
            }
        }
    }
#endif

    return deviceList;
}

void PortManager::FreePortList(pcap_if_t *deviceList)
{
#if defined(Q_OS_WIN32)
    int i = 0;
    pcap_if_t *device;
    if (oldDescriptions_.size()) {
        for(device = deviceList; device != NULL; device = device->next)
            device->description = oldDescriptions_.at(i++);
    }
    oldDescriptions_.clear();

    while (newDescriptions_.size())
        delete newDescriptions_.takeFirst();

    if (ipHlpApi_)
        FreeLibrary(ipHlpApi_);
#endif

    pcap_freealldevs(deviceList);
}

AbstractPort::Accuracy PortManager::rateAccuracy()
{
    QString rateAccuracy = appSettings->value(kRateAccuracyKey, 
                                  kRateAccuracyDefaultValue).toString();
    if (rateAccuracy == "High")
        return AbstractPort::kHighAccuracy;
    else if (rateAccuracy == "Low")
        return AbstractPort::kLowAccuracy;
    else
        qWarning("Unsupported RateAccuracy setting - %s", 
                 qPrintable(rateAccuracy));

    return AbstractPort::kHighAccuracy;
}

bool PortManager::filterAcceptsPort(const char *name)
{
    QRegExp pattern;
    QStringList includeList = appSettings->value(kPortListIncludeKey)
                                    .toStringList();
    QStringList excludeList = appSettings->value(kPortListExcludeKey)
                                    .toStringList();

    pattern.setPatternSyntax(QRegExp::Wildcard);

    // An empty (or missing) includeList accepts all ports
    // NOTE: A blank "IncludeList=" is read as a stringlist with one
    // string which is empty => treat it same as an empty stringlist
    if (includeList.isEmpty()
            || (includeList.size() == 1 && includeList.at(0).isEmpty()))
        goto _include_pass;

    foreach (QString str, includeList) {
        pattern.setPattern(str);
        if (pattern.exactMatch(name))
            goto _include_pass;
    }

    // IncludeList is not empty and port did not match a pattern
    return false;

_include_pass:
    foreach (QString str, excludeList) {
        pattern.setPattern(str);
        if (pattern.exactMatch(name))
            return false;
    }

    // Port did not match a pattern in ExcludeList
    return true;
}