aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/qlicenseservice/licenser.cpp
blob: 5d7c81439812024fa5d00c01a9053e806194e807 (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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* Copyright (C) 2023 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
*/

#include "licenser.h"

#include "commonsetup.h"

#include "clienthandlerfactory.h"
#include "clitoolhandler.h"
#include "version.h"
#include "utils.h"

namespace QLicenseService {

Licenser::Licenser(uint16_t tcpPort, const std::string &settingsPath)
{
    // Init daemon settings
    m_settings = new LicdSetup(e_set_type_daemon,
                               settingsPath.empty() ? DAEMON_SETTINGS_FILE : settingsPath);
    m_settings->initSettings();

    if (m_settings->get("license_key").empty()) {
        std::cout << "Warning: No license key provided in qtlicd.ini, required for cloud operation\n";
    }

    if (tcpPort == 0) {
        tcpPort = utils::strToInt(m_settings->get("tcp_listening_port"));
    }
    m_mocInterval = utils::strToInt(m_settings->get("moc_renewal_interval")) * SECS_IN_HOUR;
    // Start the HTTP client
    m_http = new HttpClient(m_settings->get("server_addr"),
            m_settings->get("reservation_access_point"),
            m_settings->get("permanent_access_point"),
            m_settings->get("version_query_access_point"));
    // Start the TCP/IP server
    m_tcpServer = new TcpServer(tcpPort);
}

Licenser::~Licenser()
{
    delete(m_settings);
    delete(m_tcpServer);
    delete(m_http);
    std::cout << "Daemon stopped." << std::endl;
}

int Licenser::listen()
{
    m_infoString = "";
    uint16_t socketId = 0; // Placeholder for whatever socket gets active
    std::string input = m_tcpServer->listenToClients(socketId);
    input = utils::trimStr(input);

    if (input.empty()) {
        if (m_floatingClients.size() > 0) {
            checkTasksDue();
        }
        return 0; //continue;
    }
    if (input == SOCKET_CLOSED_MSG) {
        std::cout << "Client disconnected, socket id " << socketId << std::endl;
        removeReservation(socketId);
        return 0;
    }

    std::cout << "Got a request: " << input << std::endl;
    //  Check if we already have this client in storage (floating one):
    if (clientInStorage(socketId)) {
        // do nothing - floating clients should only send request at startup
        std::cout << "Floating client with ID " << socketId << " sent something while working: ignoring\n";
        m_tcpServer->sendResponse(socketId, "NOK\n");
        return 0;
    }
    std::string reply = ""; // Holds server response first (if got any). After parsing, holds reply to the client
    bool removeRes = false;

    std::unique_ptr<ClientHandler> currentClient(parseInputAndCreateCLient(socketId, input));
    if (currentClient) {
        if (currentClient->parseRequest() != e_bad_request) {
            RequestType reqType = currentClient->getRequestType();
            if (reqType == RequestType::reservation_query) {
                reply = checkReservations();
            } else if (reqType == RequestType::daemon_version) {
                reply = getDaemonVersion();
            } else {
                if (currentClient->isLicenseRequestDue()) {
                    std::cout << "Initiating a request to the server\n";
                    if (sendServerRequest(currentClient->getRequest(), reply) == e_bad_connection) {
                        // Bad server connection: Check the existing license file for expiry date
                        if (!currentClient->isCachedReservationValid(reply)) {
                            reply = replyString[e_bad_connection];
                            removeRes = true;
                        }
                    } else if (currentClient->parseAndSaveResponse(reply) != 0) {
                        removeRes = true;
                    }
                } else {
                    // No need to contact server
                    reply = replyString[e_license_granted];
                }
            }
        } else {
            reply = replyString[e_bad_request];
            removeRes = true;
        }
    } else {
        reply = replyString[e_bad_request];
        removeRes = true;
    }
    if (currentClient->hasFloatingLicense()
                && !clientInStorage(socketId)
                && !removeRes) {
        // Store QA tool, Coco or Squish client (floating license) if not already stored
        if (currentClient->hasParent()) {
            if (!addClientToParent(currentClient.release())) {
                reply = replyString[e_license_rejected];
                m_infoString = " Parent reservation not found";
            }
        } else {
            std::cout << "Storing client in main cache\n";
            m_floatingClients[socketId] = currentClient.release();
        }
    }
    if (!m_infoString.empty()) {
        reply += ": ";
        reply += m_infoString;
    }
    reply +="\n";
    m_tcpServer->sendResponse(socketId, reply);
    std::cout << "Replied to socket " << socketId << ": " << reply << std::endl;

    if (removeRes) {
        // No license, remove reservation from cache (floating license)
        // or license file (site license)
        removeReservation(socketId);
        return 0;
    }

    if (m_floatingClients.size() > 0) {
        checkTasksDue();
    }
    std::cout << "Current clients in cache: " << m_floatingClients.size() << std::endl;
    return 0;
}


int Licenser::checkTasksDue() {
    // Check if there's any floating clients which has tasks to be done
    for (auto entry : m_floatingClients) {
        // First check if (parent) client has stopped and no children left
        if (entry.second->stopped() && !entry.second->hasChildren()) {
            removeReservation(entry.first);
            return 0;
        }
        // Then check if there is any server pings due
        if (entry.second->isLicenseRequestDue()) {
            std::string reply;
            if (sendServerRequest(entry.second->getRequest(), reply) != e_bad_connection) {
                std::cout << "Reported alive floating reservation with socket ID " << entry.first << std::endl;
                std::cout << "Client has " << entry.second->getNumberOfClients() << " sub-processes running\n";
                entry.second->resetTime();
            }
        }
    }
    return 0;
}


ClientHandler *Licenser::parseInputAndCreateCLient(uint16_t socketId, const std::string &incoming)
{
    // This parses client type from the input string and decides which type of client
    // to initiate into m_currentClient member

    RequestInfo request;
    request.socketId = socketId;

    // Find out which class of client is calling
    std::vector<std::string> paramList = utils::splitStr(incoming);
    std::string client;
    for ( int i = 0; i < paramList.size() ;i++ ) {
        std::string item = paramList.at(i);
        if (item == "-a" && paramList.size() > i) {
            client = paramList[i+1];
            break;
        }
    }

    if (client.empty()) {
        // Make this thing backwards compatible with old qtlicensetool
        // which does not send -a switch (app name)
        std::cout << "Warning: '-a' switch not found: Client undefined, assuming it's a CLI Tool" << std::endl;
        client = QTLICENSETOOL_APP_NAME;
    }

    ClientHandler *currentClient = ClientHandlerFactory::instance().create(client, request, *m_settings);
    if (!currentClient) {
        std::cout << "Warning: Client undefined!" << std::endl;
        return nullptr;
    }
    currentClient->params = paramList;
    return currentClient;
}

int Licenser::sendServerRequest(const RequestInfo &request, std::string &reply)
{
    std::string auth;
    std::cout << "Payload: " << request.payload << std::endl;

    // Generate auth hash for HTTP headers
    std::string hash;
    utils::doHmacHashSha256(request.payload, m_settings->get("server_secret"), hash);
    // For the HTTP 'Authorization' field
    auth = "apikey " + hash;

    // Send the request
    if (m_http->sendRequest(reply, request.payload, request.serverAddr, auth) != 0) {
        return e_bad_connection;
    }
    return e_got_response;
}

std::string Licenser::checkReservations()
{
    // Open all license files
    std::string dir = WORKING_DIR;
    std::string filter = LICENSE_FILE_PREFIX;
    std::vector<std::string> files = utils::getDirListing(dir, filter);

    std::stringstream reply;
    reply << "Current reservations: \n";
    for (auto file : files) {
        file = DIR_SEPARATOR + file;
        file = WORKING_DIR + file;
        std::cout << "File list: " << file << std::endl;
        std::string data;
        if (utils::readFile(data, file) != 0) {
            std::cout << "Couldn't read license file: " << file << std::endl;
            continue;
        }
        JsonHandler json(data);
        reply << "\n--- License ID " << json.get("license_number") << " ---\n";
        reply << " User ID: " << json.get("user_id") << std::endl;
        reply << " Expiry date: " << json.get("expiry_date") << std::endl;
        reply << " Reservation ID: " << json.get("reservation_id") << std::endl;
    }
    return reply.str();
}


bool Licenser::addClientToParent(ClientHandler *const client)
{
    bool found = false;
    for (auto parent : m_floatingClients) {
        if (parent.second->getReservationId() == client->getParentReservationId()) {
            parent.second->addChildClient(client);
            found = true;
            std::cout << "Stored client under reservation ID "
                << client->getParentReservationId() << std::endl;
            break;
        }
    }
    if (!found) {
        std::cout << "Warning! Not able to add current client under reservation ID "
                << client->getParentReservationId() << std::endl;
        return false;
    }
    return true;
}


void Licenser::removeReservation(int socketId) {
    // Close the socket
    m_tcpServer->closeClientSocket(socketId);
    // Check if the client had a floating license, or is a child of one.
    // Need to loop through all of them because socketId can be under any parent
    for (auto element : m_floatingClients) {
        ClientHandler* client = element.second;
        if (element.first == socketId) {
            if (!client->stopped()) {
                client->prepareRelease();
                // Don't remove parent yet, it might have child processes left
            }
            if (!client->hasChildren()) {
                // If client has no running children left, we can release the reservation and remove client
                std::string reply;
                client->release();
                client->buildRequestJson();
                if (sendServerRequest(client->getRequest(), reply) != e_bad_connection) {
                    // if connection succeeds, we can forget about this client
                    std::cout << "Removing floating reservation with ID " << client->getReservationId() << std::endl;
                    m_floatingClients.erase(socketId);
                    delete client;

                }
            }
            return;
        } else if (client->removeChildClient(socketId)) {
            std::cout << "Removed child client under reservation ID " << client->getReservationId() << std::endl;
            return;
        }
    }
    return;
}


bool Licenser::clientInStorage(uint16_t socketId) {
    for (auto client : m_floatingClients) {
        if (client.first == socketId) {
            return true;
        }
        if (client.second->hasChildren()) {
            if (client.second->clientInStorage(socketId)) {
                return true;
            }
        }
    }
    return false;
}


std::string Licenser::getDaemonVersion()
{
    std::string version = "Qt License Daemon (qtlicd) v";
    version += DAEMON_VERSION;
    return version;
}

} // namespace QLicenseService