aboutsummaryrefslogtreecommitdiffstats
path: root/src/licenser.cpp
blob: 3bd5f6b8be349524a46b8186fb99a3ba7c927adb (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
/* Copyright (C) 2022 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
*/

#include "licenser.h"

#include "clitoolhandler.h"
#include "cocohandler.h"
#include "mochandler.h"
#include "pluginhandler.h"
#include "squishhandler.h"
#include "squishidehandler.h"
#include "version.h"

#include "hmac_sha256.h"

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

    // 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")) * 3600; // 3600 = 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_server = new TcpServer(tcpPort);
}

Licenser::~Licenser()
{
    delete(m_currentClient);
    delete(settings);
    delete(m_server);
    delete(m_http);
    std::cout << "Daemon stopped." << std::endl;
}

int Licenser::listen()
{
    m_infoString = "";
    int socket = 0; // Placeholder for whatever socket gets active
    std::string input = m_server->listenToClients(socket);
    input = utils::trimStr(input);
    if (input.empty()) {
        if (m_floatingClients.size() > 0) {
            checkReportsDue();
        }
        return 0; //continue;
    }
    if (input == CLIENT_CLOSED_MSG) {
        std::cout << "Client disconnected, socket id " << socket << std::endl;
        removeClient(socket);
        return 0;
    }

    std::cout << "Got a request: " << input << std::endl;

    std::string reply = ""; // Holds server response first (if got any). After parsing, holds reply to the client

    int clientType = parseInputAndCreateCLient(socket, input);
    if (clientType != (int)ClientType::client_undefined)
    {
        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 {
                std::cout << "Initiating a request to the server\n";
                if (m_currentClient->isLicenseRequestDue()) {
                    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];
                        }
                    } else {
                        m_currentClient->parseAndSaveResponse(reply);
                    }
                } else {
                    // No need to contact server
                    reply = replyString[e_license_granted];
                }
            }
        } else {
            reply = replyString[e_bad_request];
        }
    } else {
        reply = replyString[e_bad_request];
    }

    if (m_currentClient->hasFloatingLicense()
            && reply == replyString[e_license_granted]) {
        // QA tool, Coco or Squish (client with floating license):
        // Store it in cache, but only if license has ben granted
        std::cout << "Storing client in cache\n";
        m_floatingClients.push_back(m_currentClient);
    }

    reply += m_infoString;
    reply +="\n";
    m_server->sendResponse(socket, reply);
    std::cout << "Replied to socket " << socket << ": " << reply << std::endl;

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


int Licenser::checkReportsDue() {
    // Check if there's any floating clients which has periodic reports due
    ClientHandler *client;
    for (int i = 0 ; i <  m_floatingClients.size(); i++) {
        client = m_floatingClients[i];
        if (client->isLicenseRequestDue()) {
            std::string reply;
            //std::cout << "Reporting to server (socket ID " << client->getSocketId() << std::endl;
            if (sendServerRequest(reply) != e_bad_connection) {
                std::cout << "Reported alive floating reservation with socket ID " << client->getSocketId() << std::endl;
                client->resetTimer();
            }
        }
    }
    return 0;
}


int 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
    ClientType retVal = ClientType::client_undefined;
    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[0] == 'a') {
            client = utils::trimStr(item.substr(1, item.length() -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;
    }
    if (client == MOCWRAPPER_APP_NAME) {
        std::cout << "MOC calling" << std::endl;
        request.client = ClientType::client_moc;
        request.updateIntervalSecs = utils::strToInt(settings->get("moc_renewal_interval"));
        m_currentClient = new MocHandler(request, *settings);
    } else if (client == CREATOR_APPNAME || client == DESIGN_STUDIO_APP_NAME) {
        // No need to have them separately - it's a Plugin making the calls for both
        request.client = ClientType::client_plugin;
        m_currentClient = new PluginHandler(request, *settings);
    } else if (client == QTLICENSETOOL_APP_NAME) {
        request.client = ClientType::client_CLI;
        m_currentClient = new CliToolHandler(request, *settings);
    } else if (client == SQUISH_IDE_APP_NAME) {
        request.client = ClientType::client_squish_ide;
        m_currentClient = new SquishIdeHandler(request, *settings);
    } else if (client == SQUISH_APP_NAME) {
        request.updateIntervalSecs =
                    utils::strToInt(settings->get("squish_report_interval"));
        request.client = ClientType::client_squish;
        m_currentClient = new SquishHandler(request, *settings);
    } else if (client == COCO_APP_NAME) {
        request.updateIntervalSecs =
                    utils::strToInt(settings->get("coco_report_interval"));
        request.client = ClientType::client_coco;
        m_currentClient = new CocoHandler(request, *settings);
    }
    else {
        std::cout << "Warning: Client undefined!" << std::endl;
        return (int)ClientType::client_undefined;
    }
    m_currentClient->params = paramList;
    return m_currentClient->getClientType();
}

int Licenser::sendServerRequest(std::string &reply)
{
    std::string auth;
    RequestInfo request = m_currentClient->getRequest();
    if (request.client != ClientType::client_CLI) {
        // Generate auth hash for HTTP headers (CLI tool does not need it)
        std::string hash;
        doHmacHashSha256(request.payload, settings->get("server_secret"), hash); // 19755982232ff7b6f6d0f3c57ffc1c0e4f03060e7175d478f7b146fb1e000507";
        // Bearer is the same hash (?)
        auth = "apikey " + hash;
        //auth += ", Bearer " + hash;
    }

    // Send the request
    std::cout << "Sending request: " << request.payload << std::endl;
    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();
}

void Licenser::removeClient(int socketId) {
    // Check if the client had a floating license:
    int index = -1;
    ClientHandler *client;
    for (int i = 0; i < m_floatingClients.size(); i++) {
        client = m_floatingClients[i];
        if (client->getSocketId() == socketId) {
            index = i;
            m_currentClient = client;
            break;
        }
    }
    if (index == -1 ) {
        // non-floating
        return;
    }
    // Client has a floating license - need to release the reservation now

    m_currentClient->prepareRelease();
    std::string reply;

    if (sendServerRequest(reply) != e_bad_connection) {
        // if connection succeeds, we can forget about that client
        std::cout << "Removing floating reservation with socket ID " << m_currentClient->getSocketId() << std::endl;
        m_floatingClients.erase(m_floatingClients.begin() + index);
    }

    return;
}

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