summaryrefslogtreecommitdiffstats
path: root/src/net/pvsServiceDiscovery.cpp
blob: dd6b500b9db786e180842bd544e6eb6a26a8bafb (plain) (blame)
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
/*
# Copyright (c) 2009 - OpenSLX Project, Computer Center University of Freiburg
#
# This program is free software distributed under the GPL version 2.
# See http://openslx.org/COPYING
#
# If you have any feedback please consult http://openslx.org/feedback and
# send your suggestions, praise, or complaints to feedback@openslx.org
#
# General information about OpenSLX can be found at http://openslx.org/
# -----------------------------------------------------------------------------
# src/net/pvsServiceDiscovery.cpp
#    - handle console broadcasts, tell client to connect on match
# -----------------------------------------------------------------------------
*/

#include <QtCore/QHash>
#include "src/pvs.h"
#include "pvsServiceDiscovery.h"
#include "pvsDiscoveredServer.h"
#include "src/setup.h"
#include "src/util/serviceDiscoveryUtil.h"
#include <cassert>



PVSServiceDiscovery::PVSServiceDiscovery(PVS* client)
{
    assert(client);
    bool ret = _sock.bind(SD_PORT_CLIENT);
    if (!ret)
    {
        qDebug("Could not open SERVICE DISCOVERY port");
        exit(1);
    }
    connect(&_sock, SIGNAL(readyRead()), this, SLOT(sock_dataArrival()));
    _currentServer = 0;
    _last = QDateTime::currentDateTime();
    _client = client;
    _timerId = startTimer(10000);
}

PVSServiceDiscovery::~PVSServiceDiscovery()
{
    killTimer(_timerId);
}

void PVSServiceDiscovery::connectToSession(QString name, QString passwd)
{
    _sessionName = name;
    _sessionPasswd = passwd;
    if (name.length() == 0) return;
    for (tServerList::iterator it = _servers.begin(); it != _servers.end(); it++)
    {
    	PVSDiscoveredServer *ds = *it;
        if (ds->isValid() && ds->getName() == name)
        {
        	_client->connectToHost(ds, _sessionPasswd);
        }
    }
}

void PVSServiceDiscovery::sock_dataArrival()
{
    int len;
    while ((len = _sock.pendingDatagramSize()) > -1)
    {
        if (len == 0) continue;
        char *data = new char[len];
        QHostAddress host;
        len = _sock.readDatagram(data, len, &host);
        SdFields fields = parseSdFields((unsigned char*)data, len);
        QDateTime now = QDateTime::currentDateTime();
        if (fields.contains("hsh") && fields.contains("prt") && fields.contains("aut"))
        {
            if (fields["aut"] == "SHA1")
            {
                this->handleDiscovery(
                        host,
                        atoi(fields["prt"].toUtf8().data()),
                        QByteArray::fromBase64(fields["hsh"].toAscii())
                );
            }
        }
        /*
        // DEBUG ONLY: connect to any host without matching the session name
        if (_last.secsTo(now) > 9 && fields.contains("prt"))
        {
            _last = now;
            int port = atoi(fields["prt"].toUtf8().data());
            _client->connectToHost(host, QByteArray(), port);
        }
        // ^^^^^^^^^^
        */
    }
}

void PVSServiceDiscovery::handleDiscovery(QHostAddress host, int port, QByteArray hash)
{
    int numhosts = 0; ///< while iterating we count how many entries have the same host
    for (tServerList::iterator it = _servers.begin(); it != _servers.end(); it++)
    {
        if ((**it).hasHost(host))
        {
        	ConsoleLog writeNetwork(host.toString() + " == " + (**it).getHost().toString());
            if (++numhosts >= 5) return; // ddos through faked service broadcasts? ignore...
            if ((**it).hasFingerprint(hash) && (**it).getPort() == port) // known entry...
            {
            	if ((*it)->isValid() && (*it)->getName() == _sessionName && _sessionName.length() > 0)
            	{
            		ConsoleLog writeNetwork(QString("Connecting to ").append(_sessionName));
            		_client->connectToHost((*it), _sessionPasswd);
            	}
                (**it).update(port);
                return;
            }
        }
    }
    if (_servers.length() >= 30) return; // !?
    QString oname = sha1ToReadable(hash);
    QString name = oname;
    int dup = 0;
    while (nameExists(name))
    {
    	name = "(" + QString::number(++dup) + ") " + oname;
    }
    PVSDiscoveredServer *ds = new PVSDiscoveredServer(this, host, port, hash, name);
    connect(ds, SIGNAL(validated(PVSDiscoveredServer*)), this, SLOT(sendServerToGui(PVSDiscoveredServer*)));
    _servers.push_back(ds);
    setTimerInterval();
}

bool PVSServiceDiscovery::nameExists(QString name)
{
    for (tServerList::iterator it = _servers.begin(); it != _servers.end(); it++)
    {
        if ((**it).getName() == name) return true;
    }
    return false;
}

QStringList PVSServiceDiscovery::getAllServers()
{
	QStringList hosts;
    for (tServerList::iterator it = _servers.begin(); it != _servers.end(); it++)
    {
        if ((**it).isValid()) hosts.append((**it).getName());
    }
    return hosts;
}

void PVSServiceDiscovery::sendServerToGui(PVSDiscoveredServer* ds)
{
    _client->guiAddHost(ds->getName());
}

void PVSServiceDiscovery::timerEvent(QTimerEvent *event)
{
    if (_servers.size() == 0) return;
    if (_currentServer >= _servers.size()) _currentServer = 0;
    PVSDiscoveredServer *ds = _servers.at(_currentServer);
    if (ds->getAge() >= SB_INTERVAL*2 + 1) // Entry too old?
    {
    	disconnect(ds, SIGNAL(validated(PVSDiscoveredServer*)), this, SLOT(sendServerToGui(PVSDiscoveredServer*)));
        _client->guiDelHost(ds->getName());
        delete ds;
        _servers.removeAt(_currentServer); // Clean it up
        setTimerInterval();
    }
    else
    {
        ds->validateCertificate();
    }
    ++_currentServer;
}

void PVSServiceDiscovery::setTimerInterval()
{
    killTimer(_timerId);
    _timerId = startTimer(10000 / (_servers.size() + 1));
}