08b1b67721cd8b048884a529c83d361642e24331
[quassel.git] / src / core / identserver.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include <logger.h>
22 #include <set>
23
24 #include "corenetwork.h"
25 #include "identserver.h"
26
27 IdentServer::IdentServer(bool strict, QObject *parent) : QObject(parent), _strict(strict), _socketId(0), _requestId(0) {
28     connect(&_server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
29     connect(&_v6server, SIGNAL(newConnection()), this, SLOT(incomingConnection()));
30 }
31
32 IdentServer::~IdentServer() = default;
33
34 bool IdentServer::startListening() {
35     uint16_t port = 10113;
36
37     bool success = false;
38     if (_v6server.listen(QHostAddress("::1"), port)) {
39         quInfo() << qPrintable(
40                 tr("Listening for identd clients on IPv6 %1 port %2")
41                         .arg("::1")
42                         .arg(_v6server.serverPort())
43         );
44
45         success = true;
46     }
47
48     if (_server.listen(QHostAddress("127.0.0.1"), port)) {
49         success = true;
50
51         quInfo() << qPrintable(
52                 tr("Listening for identd clients on IPv4 %1 port %2")
53                         .arg("127.0.0.1")
54                         .arg(_server.serverPort())
55         );
56     }
57
58     if (!success) {
59         quError() << qPrintable(
60                 tr("Identd could not open any network interfaces to listen on! No identd functionality will be available"));
61     }
62
63     return success;
64 }
65
66 void IdentServer::stopListening(const QString &msg) {
67     bool wasListening = false;
68     if (_server.isListening()) {
69         wasListening = true;
70         _server.close();
71     }
72     if (_v6server.isListening()) {
73         wasListening = true;
74         _v6server.close();
75     }
76     if (wasListening) {
77         if (msg.isEmpty())
78             quInfo() << "No longer listening for identd clients.";
79         else
80             quInfo() << qPrintable(msg);
81     }
82 }
83
84 void IdentServer::incomingConnection() {
85     auto *server = qobject_cast<QTcpServer *>(sender());
86     Q_ASSERT(server);
87     while (server->hasPendingConnections()) {
88         QTcpSocket *socket = server->nextPendingConnection();
89         connect(socket, SIGNAL(readyRead()), this, SLOT(respond()));
90     }
91 }
92
93 void IdentServer::respond() {
94     QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
95     Q_ASSERT(socket);
96
97     qint64 transactionId = _socketId;
98
99     if (socket->canReadLine()) {
100         QByteArray query = socket->readLine();
101         if (query.endsWith("\r\n"))
102             query.chop(2);
103         else if (query.endsWith("\n"))
104             query.chop(1);
105
106         QList<QByteArray> split = query.split(',');
107
108         bool success = false;
109
110         quint16 localPort;
111         if (!split.empty()) {
112             localPort = split[0].trimmed().toUShort(&success, 10);
113         }
114
115         Request request{socket, localPort, query, transactionId, _requestId++};
116         if (!success) {
117             responseUnavailable(request);
118         } else if (!responseAvailable(request)) {
119             if (hasSocketsBelowId(transactionId)) {
120                 _requestQueue.emplace_back(request);
121             } else {
122                 responseUnavailable(request);
123             }
124         }
125     }
126 }
127
128 bool IdentServer::responseAvailable(Request request) {
129     QString user;
130     bool success = true;
131     if (_connections.contains(request.localPort)) {
132         user = _connections[request.localPort];
133     } else {
134         success = false;
135     }
136
137     QString data;
138     if (success) {
139         data += request.query + " : USERID : Quassel : " + user + "\r\n";
140
141         request.socket->write(data.toUtf8());
142         request.socket->flush();
143         request.socket->close();
144     }
145     return success;
146 }
147
148 void IdentServer::responseUnavailable(Request request) {
149     QString data = request.query + " : ERROR : NO-USER\r\n";
150
151     request.socket->write(data.toUtf8());
152     request.socket->flush();
153     request.socket->close();
154 }
155
156
157 bool IdentServer::addSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort,
158                             const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId) {
159     Q_UNUSED(localAddress)
160     Q_UNUSED(peerAddress)
161     Q_UNUSED(peerPort)
162
163     const CoreNetwork *network = qobject_cast<CoreNetwork *>(sender());
164     _connections[localPort] = network->coreSession()->strictCompliantIdent(identity);;
165     processWaiting(socketId);
166     return true;
167 }
168
169
170 bool IdentServer::removeSocket(const CoreIdentity *identity, const QHostAddress &localAddress, quint16 localPort,
171                                const QHostAddress &peerAddress, quint16 peerPort, qint64 socketId) {
172     Q_UNUSED(identity)
173     Q_UNUSED(localAddress)
174     Q_UNUSED(peerAddress)
175     Q_UNUSED(peerPort)
176
177     _connections.remove(localPort);
178     processWaiting(socketId);
179     return true;
180 }
181
182 qint64 IdentServer::addWaitingSocket() {
183     qint64 newSocketId = _socketId++;
184     _waiting.push_back(newSocketId);
185     return newSocketId;
186 }
187
188 bool IdentServer::hasSocketsBelowId(qint64 id) {
189     return std::any_of(_waiting.begin(), _waiting.end(), [=](qint64 socketId) {
190         return socketId <= id;
191     });
192 }
193
194 void IdentServer::removeWaitingSocket(qint64 socketId) {
195     _waiting.remove(socketId);
196 }
197
198 void IdentServer::processWaiting(qint64 socketId) {
199     qint64 lowestSocketId = std::numeric_limits<qint64 >::max();
200     for (qint64 id : _waiting) {
201         if (id < lowestSocketId) {
202             lowestSocketId = id;
203         }
204     }
205     removeWaitingSocket(socketId);
206     _requestQueue.remove_if([=](Request request) {
207         if (request.transactionId < lowestSocketId) {
208             responseUnavailable(request);
209             return true;
210         } else if (request.transactionId > socketId) {
211             return responseAvailable(request);
212         } else {
213             return false;
214         }
215     });
216 }
217
218 bool operator==(const Request &a, const Request &b) {
219     return a.requestId == b.requestId;
220 }