summaryrefslogtreecommitdiffstats
path: root/resource/listener.cpp
blob: 23a5a708b6ddeddc896ca848605423473584d6f5 (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
#include "listener.h"

#include "common/console.h"
#include "common/commands.h"
#include "common/handshake_generated.h"
#include "common/revisionupdate_generated.h"

#include <QLocalSocket>
#include <QTimer>

Listener::Listener(const QString &resource, QObject *parent)
    : QObject(parent),
      m_server(new QLocalServer(this)),
      m_revision(0)
{
    connect(m_server, &QLocalServer::newConnection,
             this, &Listener::acceptConnection);
    Console::main()->log(QString("Trying to open %1").arg(resource));
    if (!m_server->listen(resource)) {
        // FIXME: multiple starts need to be handled here
        m_server->removeServer(resource);
        if (!m_server->listen(resource)) {
            Console::main()->log("Utter failure to start server");
            exit(-1);
        }
    }

    if (m_server->isListening()) {
        Console::main()->log(QString("Listening on %1").arg(m_server->serverName()));
    }

    QTimer::singleShot(2000, this, SLOT(checkConnections()));
}

Listener::~Listener()
{
}

void Listener::setRevision(unsigned long long revision)
{
    if (m_revision != revision) {
        m_revision = revision;
        updateClientsWithRevision();
    }
}

unsigned long long Listener::revision() const
{
    return m_revision;
}

void Listener::closeAllConnections()
{
    //TODO: close all client connectionsin m_connections
    for (Client &client: m_connections) {
        if (client.socket) {
            client.socket->close();
            delete client.socket;
            client.socket = 0;
        }
    }
}

void Listener::acceptConnection()
{
    Console::main()->log(QString("Accepting connection"));
    QLocalSocket *socket = m_server->nextPendingConnection();

    if (!socket) {
        return;
    }

    Console::main()->log("Got a connection");
    Client client("Unknown Client" /*fixme: actual names!*/, socket);
    connect(socket, &QIODevice::readyRead,
            this, &Listener::readFromSocket);
    m_connections << client;
    connect(socket, &QLocalSocket::disconnected,
            this, &Listener::clientDropped);

}

void Listener::clientDropped()
{
    QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender());
    if (!socket) {
        return;
    }

    Console::main()->log("Dropping connection...");
    QMutableVectorIterator<Client> it(m_connections);
    while (it.hasNext()) {
        const Client &client = it.next();
        if (client.socket == socket) {
            Console::main()->log(QString("    dropped... %1").arg(client.name));
            it.remove();
            break;
        }
    }

    checkConnections();
}

void Listener::checkConnections()
{
    if (m_connections.isEmpty()) {
        m_server->close();
        emit noClients();
    }
}

void Listener::readFromSocket()
{
    QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender());
    if (!socket) {
        return;
    }

    Console::main()->log("Reading from socket...");
    for (Client &client: m_connections) {
        if (client.socket == socket) {
            Console::main()->log(QString("    Client: %1").arg(client.name));
            client.commandBuffer += socket->readAll();
            // FIXME: schedule these rather than process them all at once
            //        right now this can lead to starvation of clients due to
            //        one overly active client
            while (processClientBuffer(client)) {}
            break;
        }
    }
}

bool Listener::processClientBuffer(Client &client)
{
    static const int headerSize = (sizeof(int) * 2);
    Console::main()->log(QString("processing %1").arg(client.commandBuffer.size()));
    if (client.commandBuffer.size() < headerSize) {
        return false;
    }

    int commandId, size;
    commandId = *(int*)client.commandBuffer.constData();
    size = *(int*)(client.commandBuffer.constData() + sizeof(int));

    if (size <= client.commandBuffer.size() - headerSize) {
        QByteArray data = client.commandBuffer.mid(headerSize, size);
        client.commandBuffer.remove(0, headerSize + size);

        switch (commandId) {
            case Commands::HandshakeCommand: {
                auto buffer = Akonadi::GetHandshake(data.constData());
                Console::main()->log(QString("    Handshake from %1").arg(buffer->name()->c_str()));
                sendCurrentRevision(client);
                break;
            }
            default:
                // client.hasSentCommand = true;
                break;
        }

        return client.commandBuffer.size() >= headerSize;
    } else {
        return false;
    }
}

void Listener::sendCurrentRevision(Client &client)
{
    if (!client.socket || !client.socket->isValid()) {
        return;
    }

    auto command = Akonadi::CreateRevisionUpdate(m_fbb, m_revision);
    Akonadi::FinishRevisionUpdateBuffer(m_fbb, command);
    Commands::write(client.socket, Commands::RevisionUpdateCommand, m_fbb);
    m_fbb.Clear();
}

void Listener::updateClientsWithRevision()
{
    auto command = Akonadi::CreateRevisionUpdate(m_fbb, m_revision);
    Akonadi::FinishRevisionUpdateBuffer(m_fbb, command);

    for (const Client &client: m_connections) {
        if (!client.socket || !client.socket->isValid()) {
            continue;
        }

        Commands::write(client.socket, Commands::RevisionUpdateCommand, m_fbb);
    }
    m_fbb.Clear();
}