aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/qlicenseservice/licenser.cpp
blob: f2364d68dbb26dafe9dfae43e5063866dc6cfb57 (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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/* Copyright (C) 2022 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
*/

#include "licenser.h"

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

#include "hmac_sha256.h"

namespace QLicenseService {

Licenser::Licenser(uint16_t tcpPort)
{
    // Init daemon settings
    settings = new LicdSetup(e_set_type_daemon);

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

    // Check if our setup already has some hw id - generate one if not
    if (settings->get("hw_id").empty()) {
        setHwId();
    }

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

Licenser::~Licenser()
{
    delete(m_currentClient);
    delete(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;

    if (parseInputAndCreateCLient(socketId, input)) {
        if (m_currentClient->parseRequest() != e_bad_request) {
            RequestType reqType = m_currentClient->getRequestType();
            if (reqType == RequestType::reservation_query) {
                reply = checkReservations();
            } else if (reqType == RequestType::daemon_version) {
                reply = getDaemonVersion();
            } else {
                if (m_currentClient->isLicenseRequestDue()) {
                    std::cout << "Initiating a request to the server\n";
                    if (sendServerRequest(reply) == e_bad_connection) {
                        // Bad server connection: Check the existing license file for expiry date
                        if (!m_currentClient->isCachedReservationValid(reply)) {
                            reply = replyString[e_bad_connection];
                            removeRes = true;
                        }
                    } else if (m_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 (m_currentClient->hasFloatingLicense()
                && !clientInStorage(socketId)
                && !removeRes) {
        // Store QA tool, Coco or Squish client (floating license) if not already stored
        if (m_currentClient->hasParent()) {
            if (!addClientToParent()) {
                reply = replyString[e_license_rejected];
                m_infoString = " Parent reservation not found";
            }
        } else {
            std::cout << "Storing client in main cache\n";
            m_floatingClients[socketId] = std::move(m_currentClient);
        }
    }
    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(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;
}


bool 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;
    }

    m_currentClient = ClientHandlerFactory::instance().create(client, request, *settings);
    if (!m_currentClient) {
        std::cout << "Warning: Client undefined!" << std::endl;
        return false;
    }
    m_currentClient->params = paramList;
    return true;
}

int Licenser::sendServerRequest(std::string &reply)
{
    std::string auth;
    RequestInfo request = m_currentClient->getRequest();
    std::cout << "Payload: " << request.payload << std::endl;

    // Generate auth hash for HTTP headers
    std::string hash;
    doHmacHashSha256(request.payload, 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;
}

void Licenser::doHmacHashSha256(const std::string &payload, const std::string &secret, std::string &authKey)
{
    std::stringstream ss_result;
    ss_result << "";

    // Allocate memory for the HMAC
    std::vector<uint8_t> out(SHA256_HASH_SIZE);

    // Call hmac-sha256 function
    hmac_sha256(secret.data(), secret.size(), payload.data(), payload.size(),
                out.data(), out.size());

    // Convert to string with std::hex
    for (uint8_t x : out) {
        ss_result << std::hex << std::setfill('0') << std::setw(2) << (int)x;
    }
    authKey = ss_result.str();
    JsonHandler pay(payload);
}


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()
{
    bool found = false;
    for (auto parent : m_floatingClients) {
        if (parent.second->getReservationId() == m_currentClient->getParentReservationId()) {
            parent.second->addChildClient(m_currentClient);
            found = true;
            std::cout << "Stored client under reservation ID "
                << m_currentClient->getParentReservationId() << std::endl;
            break;
        }
    }
    if (!found) {
        std::cout << "Warning! Not able to add current client under reservation ID "
                << m_currentClient->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();
                m_currentClient = client;
                if (sendServerRequest(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;
}

void Licenser::setHwId() {
    std::cout << "No HW ID found, generating it ... ";
    std::string hwInfo = utils::getSystemHwInfoString();
    std::string hash;
    doHmacHashSha256(hwInfo, settings->get("server_secret"), hash);
    std::string settingsString;
    utils::readFile(settingsString, DAEMON_SETTINGS_FILE);
    std::vector<std::string> lines = utils::splitStr(settingsString, '\n');
    settingsString = "";
    std::string wanted = "hw_id=";
    for (std::string line : lines) {
        if (line.substr(0, wanted.length()) == wanted) {
            line = wanted + hash;
        }
        line += '\n';
        settingsString += line;
    }
    utils::writeToFile(DAEMON_SETTINGS_FILE, settingsString);
    settings->set("hw_id", hash);
    return;
}

} // namespace QLicenseService