aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSami Littow <sami.littow@qt.io>2022-11-18 12:04:32 +0200
committerSami Littow <sami.littow@qt.io>2022-11-18 12:04:32 +0200
commitd42382745b488415a60b3bfe94fadb2dc0bdc51c (patch)
treeb8af0cbe1164a5cf294c5594d18edc839a57e144
parent1c7f3b7f4a76553a5c898d4a93365f4a7e52a71c (diff)
Windows version added
qtlongterm removed (replaced by qtlicensetool) Version queries added (server, daemon) License query added Code refactoring
-rwxr-xr-x[-rw-r--r--].gitignore0
-rw-r--r--3rdParty/curl/websockets.h79
-rw-r--r--3rdparty/curl/include/curl/curl.h (renamed from 3rdParty/curl/curl.h)6
-rw-r--r--3rdparty/curl/include/curl/curlver.h (renamed from 3rdParty/curl/curlver.h)11
-rw-r--r--3rdparty/curl/include/curl/easy.h (renamed from 3rdParty/curl/easy.h)0
-rw-r--r--3rdparty/curl/include/curl/header.h (renamed from 3rdParty/curl/header.h)8
-rw-r--r--3rdparty/curl/include/curl/mprintf.h (renamed from 3rdParty/curl/mprintf.h)0
-rw-r--r--3rdparty/curl/include/curl/multi.h (renamed from 3rdParty/curl/multi.h)2
-rw-r--r--3rdparty/curl/include/curl/options.h (renamed from 3rdParty/curl/options.h)2
-rw-r--r--3rdparty/curl/include/curl/stdcheaders.h (renamed from 3rdParty/curl/stdcheaders.h)0
-rw-r--r--3rdparty/curl/include/curl/system.h (renamed from 3rdParty/curl/system.h)0
-rw-r--r--3rdparty/curl/include/curl/typecheck-gcc.h (renamed from 3rdParty/curl/typecheck-gcc.h)128
-rw-r--r--3rdparty/curl/include/curl/urlapi.h (renamed from 3rdParty/curl/urlapi.h)0
-rw-r--r--3rdparty/curl/lib/libcurl.libbin0 -> 2178578 bytes
-rw-r--r--3rdparty/dirent/dirent.h1212
-rw-r--r--3rdparty/hmac_sha256/CMakeLists.txt (renamed from 3rdParty/hmac_sha256/CMakeLists.txt)0
-rw-r--r--3rdparty/hmac_sha256/LICENSE (renamed from 3rdParty/hmac_sha256/LICENSE)0
-rw-r--r--3rdparty/hmac_sha256/README.md (renamed from 3rdParty/hmac_sha256/README.md)0
-rw-r--r--3rdparty/hmac_sha256/hmac_sha256.c (renamed from 3rdParty/hmac_sha256/hmac_sha256.c)0
-rw-r--r--3rdparty/hmac_sha256/hmac_sha256.h (renamed from 3rdParty/hmac_sha256/hmac_sha256.h)0
-rw-r--r--3rdparty/hmac_sha256/sha256.c (renamed from 3rdParty/hmac_sha256/sha256.c)0
-rw-r--r--3rdparty/hmac_sha256/sha256.h (renamed from 3rdParty/hmac_sha256/sha256.h)0
-rw-r--r--3rdparty/windowsdaemon/windowsdaemon.cpp441
-rw-r--r--CMakeLists.txt77
-rw-r--r--CMakePresets.json70
-rw-r--r--GHANGELOG13
-rw-r--r--INSTALL_linux.txt58
-rw-r--r--INSTALL_win.txt65
-rw-r--r--Licenses/LICENSE.txt704
-rw-r--r--Licenses/LICENSE_thirdParty.txt30
-rw-r--r--README.md190
-rwxr-xr-xbuild_linux.sh (renamed from build.sh)18
-rw-r--r--build_windows.bat22
-rw-r--r--dummy_licheck.cpp13
-rw-r--r--httpclient.cpp150
-rw-r--r--include/commonsetup.h42
-rw-r--r--include/httpclient.h82
-rw-r--r--include/jsonhandler.h18
-rw-r--r--include/licdsetup.h51
-rw-r--r--include/licenser.h128
-rw-r--r--include/tcpclient.h72
-rw-r--r--include/tcpserver.h39
-rw-r--r--include/utils.h302
-rw-r--r--include/version.h22
-rw-r--r--jsonhandler.cpp74
-rw-r--r--licd.ini8
-rw-r--r--licdsetup.cpp305
-rw-r--r--licenser.cpp378
-rw-r--r--linux_daemon/linuxdaemon.cpp65
-rw-r--r--linux_daemon/linuxdaemon.h12
-rwxr-xr-xlinux_service_scripts/installer.sh5
-rwxr-xr-xlinux_service_scripts/uninstaller.sh4
-rw-r--r--mocwrapper/CMakeLists.txt27
-rw-r--r--mocwrapper/mocwrapper.cpp319
-rw-r--r--mocwrapper/mocwrapper.h53
-rw-r--r--qtlicensetool/CMakeLists.txt30
-rw-r--r--qtlicensetool/qtlicensetool.cpp206
-rw-r--r--qtlicensetool/qtlicensetool.h53
-rw-r--r--qtlongterm/CMakeLists.txt17
-rw-r--r--qtlongterm/qtlongterm.cpp183
-rw-r--r--qtlongterm/qtlongterm.h33
-rw-r--r--tcpclient.cpp76
-rw-r--r--tcpserver.cpp204
-rw-r--r--utils.cpp258
64 files changed, 4693 insertions, 1672 deletions
diff --git a/.gitignore b/.gitignore
index 11a783e..11a783e 100644..100755
--- a/.gitignore
+++ b/.gitignore
diff --git a/3rdParty/curl/websockets.h b/3rdParty/curl/websockets.h
deleted file mode 100644
index e128526..0000000
--- a/3rdParty/curl/websockets.h
+++ /dev/null
@@ -1,79 +0,0 @@
-#ifndef CURLINC_WEBSOCKETS_H
-#define CURLINC_WEBSOCKETS_H
-/***************************************************************************
- * _ _ ____ _
- * Project ___| | | | _ \| |
- * / __| | | | |_) | |
- * | (__| |_| | _ <| |___
- * \___|\___/|_| \_\_____|
- *
- * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
- *
- * This software is licensed as described in the file COPYING, which
- * you should have received as part of this distribution. The terms
- * are also available at https://curl.se/docs/copyright.html.
- *
- * You may opt to use, copy, modify, merge, publish, distribute and/or sell
- * copies of the Software, and permit persons to whom the Software is
- * furnished to do so, under the terms of the COPYING file.
- *
- * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
- * KIND, either express or implied.
- *
- * SPDX-License-Identifier: curl
- *
- ***************************************************************************/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* generic in/out flag bits */
-#define CURLWS_TEXT (1<<0)
-#define CURLWS_BINARY (1<<1)
-#define CURLWS_CONT (1<<2)
-#define CURLWS_CLOSE (1<<3)
-#define CURLWS_PING (1<<4)
-
-/*
- * NAME curl_ws_recv()
- *
- * DESCRIPTION
- *
- * Receives data from the websocket connection. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- */
-CURL_EXTERN CURLcode curl_ws_recv(CURL *curl, void *buffer, size_t buflen,
- size_t *recv, unsigned int *recvflags);
-
-/* sendflags for curl_ws_send() */
-#define CURLWS_NOCOMPRESS (1<<5)
-#define CURLWS_PONG (1<<6)
-
-/*
- * NAME curl_easy_send()
- *
- * DESCRIPTION
- *
- * Sends data over the websocket connection. Use after successful
- * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
- */
-CURL_EXTERN CURLcode curl_ws_send(CURL *curl, const void *buffer,
- size_t buflen, size_t *sent,
- unsigned int sendflags);
-
-/* bits for the CURLOPT_WS_OPTIONS bitmask: */
-#define CURLWS_RAW_MODE (1<<0)
-
-struct curl_ws_metadata {
- int age; /* zero */
- int recvflags; /* See the CURLWS_* defines */
-};
-
-CURL_EXTERN struct curl_ws_metadata *curl_ws_meta(CURL *curl);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CURLINC_WEBSOCKETS_H */
diff --git a/3rdParty/curl/curl.h b/3rdparty/curl/include/curl/curl.h
index b708454..7a1b561 100644
--- a/3rdParty/curl/curl.h
+++ b/3rdparty/curl/include/curl/curl.h
@@ -568,7 +568,7 @@ typedef enum {
CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
that failed */
- CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialize ENGINE */
+ CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
accepted and we failed to login */
CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
@@ -2154,9 +2154,6 @@ typedef enum {
/* specify which protocols that libcurl is allowed to follow directs to */
CURLOPT(CURLOPT_REDIR_PROTOCOLS_STR, CURLOPTTYPE_STRINGPOINT, 319),
- /* websockets options */
- CURLOPT(CURLOPT_WS_OPTIONS, CURLOPTTYPE_LONG, 320),
-
CURLOPT_LASTENTRY /* the last unused */
} CURLoption;
@@ -3112,7 +3109,6 @@ CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
#include "urlapi.h"
#include "options.h"
#include "header.h"
-#include "websockets.h"
/* the typechecker doesn't work in C++ (yet) */
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
diff --git a/3rdParty/curl/curlver.h b/3rdparty/curl/include/curl/curlver.h
index 912dbcc..8bceb53 100644
--- a/3rdParty/curl/curlver.h
+++ b/3rdparty/curl/include/curl/curlver.h
@@ -24,19 +24,20 @@
*
***************************************************************************/
-/* This header file contains nothing but libcurl version info */
+/* This header file contains nothing but libcurl version info.
+ This was made its own header file in 7.11.2 */
/* This is the global package copyright */
#define LIBCURL_COPYRIGHT "1996 - 2022 Daniel Stenberg, <daniel@haxx.se>."
/* This is the version number of the libcurl package from which this header
file origins: */
-#define LIBCURL_VERSION "7.86.0-DEV"
+#define LIBCURL_VERSION "7.85.0"
/* The numeric version number is also available "in parts" by using these
defines: */
#define LIBCURL_VERSION_MAJOR 7
-#define LIBCURL_VERSION_MINOR 86
+#define LIBCURL_VERSION_MINOR 85
#define LIBCURL_VERSION_PATCH 0
/* This is the numeric version of the libcurl version number, meant for easier
@@ -58,7 +59,7 @@
CURL_VERSION_BITS() macro since curl's own configure script greps for it
and needs it to contain the full number.
*/
-#define LIBCURL_VERSION_NUM 0x075600
+#define LIBCURL_VERSION_NUM 0x075500
/*
* This is the date and time when the full source package was created. The
@@ -69,7 +70,7 @@
*
* "2007-11-23"
*/
-#define LIBCURL_TIMESTAMP "[unreleased]"
+#define LIBCURL_TIMESTAMP "2022-08-31"
#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
#define CURL_AT_LEAST_VERSION(x,y,z) \
diff --git a/3rdParty/curl/easy.h b/3rdparty/curl/include/curl/easy.h
index 9c7e63a..9c7e63a 100644
--- a/3rdParty/curl/easy.h
+++ b/3rdparty/curl/include/curl/easy.h
diff --git a/3rdParty/curl/header.h b/3rdparty/curl/include/curl/header.h
index 1598c6f..6af29c0 100644
--- a/3rdParty/curl/header.h
+++ b/3rdparty/curl/include/curl/header.h
@@ -24,10 +24,6 @@
*
***************************************************************************/
-#ifdef __cplusplus
-extern "C" {
-#endif
-
struct curl_header {
char *name; /* this might not use the same case */
char *value;
@@ -67,8 +63,4 @@ CURL_EXTERN struct curl_header *curl_easy_nextheader(CURL *easy,
int request,
struct curl_header *prev);
-#ifdef __cplusplus
-} /* end of extern "C" */
-#endif
-
#endif /* CURLINC_HEADER_H */
diff --git a/3rdParty/curl/mprintf.h b/3rdparty/curl/include/curl/mprintf.h
index cb948dc..cb948dc 100644
--- a/3rdParty/curl/mprintf.h
+++ b/3rdparty/curl/include/curl/mprintf.h
diff --git a/3rdParty/curl/multi.h b/3rdparty/curl/include/curl/multi.h
index 2f3ec37..3010492 100644
--- a/3rdParty/curl/multi.h
+++ b/3rdparty/curl/include/curl/multi.h
@@ -124,7 +124,7 @@ struct curl_waitfd {
/*
* Name: curl_multi_init()
*
- * Desc: initialize multi-style curl usage
+ * Desc: inititalize multi-style curl usage
*
* Returns: a new CURLM handle to use in all 'curl_multi' functions.
*/
diff --git a/3rdParty/curl/options.h b/3rdparty/curl/include/curl/options.h
index a792687..c8ac827 100644
--- a/3rdParty/curl/options.h
+++ b/3rdparty/curl/include/curl/options.h
@@ -33,7 +33,7 @@ typedef enum {
CURLOT_VALUES, /* (a defined set or bitmask) */
CURLOT_OFF_T, /* curl_off_t (a range of values) */
CURLOT_OBJECT, /* pointer (void *) */
- CURLOT_STRING, /* (char * to null-terminated buffer) */
+ CURLOT_STRING, /* (char * to zero terminated buffer) */
CURLOT_SLIST, /* (struct curl_slist *) */
CURLOT_CBPTR, /* (void * passed as-is to a callback) */
CURLOT_BLOB, /* blob (struct curl_blob *) */
diff --git a/3rdParty/curl/stdcheaders.h b/3rdparty/curl/include/curl/stdcheaders.h
index 82e1b5f..82e1b5f 100644
--- a/3rdParty/curl/stdcheaders.h
+++ b/3rdparty/curl/include/curl/stdcheaders.h
diff --git a/3rdParty/curl/system.h b/3rdparty/curl/include/curl/system.h
index 8d56b8a..8d56b8a 100644
--- a/3rdParty/curl/system.h
+++ b/3rdparty/curl/include/curl/system.h
diff --git a/3rdParty/curl/typecheck-gcc.h b/3rdparty/curl/include/curl/typecheck-gcc.h
index d8cc919..2dabcb4 100644
--- a/3rdParty/curl/typecheck-gcc.h
+++ b/3rdparty/curl/include/curl/typecheck-gcc.h
@@ -27,8 +27,8 @@
/* wraps curl_easy_setopt() with typechecking */
/* To add a new kind of warning, add an
- * if (curlcheck_sometype_option(_curl_opt))
- * if (!curlcheck_sometype(value))
+ * if(curlcheck_sometype_option(_curl_opt))
+ * if(!curlcheck_sometype(value))
* _curl_easy_setopt_err_sometype();
* block and define curlcheck_sometype_option, curlcheck_sometype and
* _curl_easy_setopt_err_sometype below
@@ -43,72 +43,72 @@
#define curl_easy_setopt(handle, option, value) \
__extension__({ \
__typeof__(option) _curl_opt = option; \
- if (__builtin_constant_p(_curl_opt)) { \
- if (curlcheck_long_option(_curl_opt)) \
- if (!curlcheck_long(value)) \
+ if(__builtin_constant_p(_curl_opt)) { \
+ if(curlcheck_long_option(_curl_opt)) \
+ if(!curlcheck_long(value)) \
_curl_easy_setopt_err_long(); \
- if (curlcheck_off_t_option(_curl_opt)) \
- if (!curlcheck_off_t(value)) \
+ if(curlcheck_off_t_option(_curl_opt)) \
+ if(!curlcheck_off_t(value)) \
_curl_easy_setopt_err_curl_off_t(); \
- if (curlcheck_string_option(_curl_opt)) \
- if (!curlcheck_string(value)) \
+ if(curlcheck_string_option(_curl_opt)) \
+ if(!curlcheck_string(value)) \
_curl_easy_setopt_err_string(); \
- if (curlcheck_write_cb_option(_curl_opt)) \
- if (!curlcheck_write_cb(value)) \
+ if(curlcheck_write_cb_option(_curl_opt)) \
+ if(!curlcheck_write_cb(value)) \
_curl_easy_setopt_err_write_callback(); \
- if ((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \
- if (!curlcheck_resolver_start_callback(value)) \
+ if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \
+ if(!curlcheck_resolver_start_callback(value)) \
_curl_easy_setopt_err_resolver_start_callback(); \
- if ((_curl_opt) == CURLOPT_READFUNCTION) \
- if (!curlcheck_read_cb(value)) \
+ if((_curl_opt) == CURLOPT_READFUNCTION) \
+ if(!curlcheck_read_cb(value)) \
_curl_easy_setopt_err_read_cb(); \
- if ((_curl_opt) == CURLOPT_IOCTLFUNCTION) \
- if (!curlcheck_ioctl_cb(value)) \
+ if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \
+ if(!curlcheck_ioctl_cb(value)) \
_curl_easy_setopt_err_ioctl_cb(); \
- if ((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \
- if (!curlcheck_sockopt_cb(value)) \
+ if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \
+ if(!curlcheck_sockopt_cb(value)) \
_curl_easy_setopt_err_sockopt_cb(); \
- if ((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \
- if (!curlcheck_opensocket_cb(value)) \
+ if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \
+ if(!curlcheck_opensocket_cb(value)) \
_curl_easy_setopt_err_opensocket_cb(); \
- if ((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \
- if (!curlcheck_progress_cb(value)) \
+ if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \
+ if(!curlcheck_progress_cb(value)) \
_curl_easy_setopt_err_progress_cb(); \
- if ((_curl_opt) == CURLOPT_DEBUGFUNCTION) \
- if (!curlcheck_debug_cb(value)) \
+ if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \
+ if(!curlcheck_debug_cb(value)) \
_curl_easy_setopt_err_debug_cb(); \
- if ((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \
- if (!curlcheck_ssl_ctx_cb(value)) \
+ if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \
+ if(!curlcheck_ssl_ctx_cb(value)) \
_curl_easy_setopt_err_ssl_ctx_cb(); \
- if (curlcheck_conv_cb_option(_curl_opt)) \
- if (!curlcheck_conv_cb(value)) \
+ if(curlcheck_conv_cb_option(_curl_opt)) \
+ if(!curlcheck_conv_cb(value)) \
_curl_easy_setopt_err_conv_cb(); \
- if ((_curl_opt) == CURLOPT_SEEKFUNCTION) \
- if (!curlcheck_seek_cb(value)) \
+ if((_curl_opt) == CURLOPT_SEEKFUNCTION) \
+ if(!curlcheck_seek_cb(value)) \
_curl_easy_setopt_err_seek_cb(); \
- if (curlcheck_cb_data_option(_curl_opt)) \
- if (!curlcheck_cb_data(value)) \
+ if(curlcheck_cb_data_option(_curl_opt)) \
+ if(!curlcheck_cb_data(value)) \
_curl_easy_setopt_err_cb_data(); \
- if ((_curl_opt) == CURLOPT_ERRORBUFFER) \
- if (!curlcheck_error_buffer(value)) \
+ if((_curl_opt) == CURLOPT_ERRORBUFFER) \
+ if(!curlcheck_error_buffer(value)) \
_curl_easy_setopt_err_error_buffer(); \
- if ((_curl_opt) == CURLOPT_STDERR) \
- if (!curlcheck_FILE(value)) \
+ if((_curl_opt) == CURLOPT_STDERR) \
+ if(!curlcheck_FILE(value)) \
_curl_easy_setopt_err_FILE(); \
- if (curlcheck_postfields_option(_curl_opt)) \
- if (!curlcheck_postfields(value)) \
+ if(curlcheck_postfields_option(_curl_opt)) \
+ if(!curlcheck_postfields(value)) \
_curl_easy_setopt_err_postfields(); \
- if ((_curl_opt) == CURLOPT_HTTPPOST) \
- if (!curlcheck_arr((value), struct curl_httppost)) \
+ if((_curl_opt) == CURLOPT_HTTPPOST) \
+ if(!curlcheck_arr((value), struct curl_httppost)) \
_curl_easy_setopt_err_curl_httpost(); \
- if ((_curl_opt) == CURLOPT_MIMEPOST) \
- if (!curlcheck_ptr((value), curl_mime)) \
+ if((_curl_opt) == CURLOPT_MIMEPOST) \
+ if(!curlcheck_ptr((value), curl_mime)) \
_curl_easy_setopt_err_curl_mimepost(); \
- if (curlcheck_slist_option(_curl_opt)) \
- if (!curlcheck_arr((value), struct curl_slist)) \
+ if(curlcheck_slist_option(_curl_opt)) \
+ if(!curlcheck_arr((value), struct curl_slist)) \
_curl_easy_setopt_err_curl_slist(); \
- if ((_curl_opt) == CURLOPT_SHARE) \
- if (!curlcheck_ptr((value), CURLSH)) \
+ if((_curl_opt) == CURLOPT_SHARE) \
+ if(!curlcheck_ptr((value), CURLSH)) \
_curl_easy_setopt_err_CURLSH(); \
} \
curl_easy_setopt(handle, _curl_opt, value); \
@@ -118,30 +118,30 @@
#define curl_easy_getinfo(handle, info, arg) \
__extension__({ \
__typeof__(info) _curl_info = info; \
- if (__builtin_constant_p(_curl_info)) { \
- if (curlcheck_string_info(_curl_info)) \
- if (!curlcheck_arr((arg), char *)) \
+ if(__builtin_constant_p(_curl_info)) { \
+ if(curlcheck_string_info(_curl_info)) \
+ if(!curlcheck_arr((arg), char *)) \
_curl_easy_getinfo_err_string(); \
- if (curlcheck_long_info(_curl_info)) \
- if (!curlcheck_arr((arg), long)) \
+ if(curlcheck_long_info(_curl_info)) \
+ if(!curlcheck_arr((arg), long)) \
_curl_easy_getinfo_err_long(); \
- if (curlcheck_double_info(_curl_info)) \
- if (!curlcheck_arr((arg), double)) \
+ if(curlcheck_double_info(_curl_info)) \
+ if(!curlcheck_arr((arg), double)) \
_curl_easy_getinfo_err_double(); \
- if (curlcheck_slist_info(_curl_info)) \
- if (!curlcheck_arr((arg), struct curl_slist *)) \
+ if(curlcheck_slist_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_slist *)) \
_curl_easy_getinfo_err_curl_slist(); \
- if (curlcheck_tlssessioninfo_info(_curl_info)) \
- if (!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \
+ if(curlcheck_tlssessioninfo_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \
_curl_easy_getinfo_err_curl_tlssesssioninfo(); \
- if (curlcheck_certinfo_info(_curl_info)) \
- if (!curlcheck_arr((arg), struct curl_certinfo *)) \
+ if(curlcheck_certinfo_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_certinfo *)) \
_curl_easy_getinfo_err_curl_certinfo(); \
- if (curlcheck_socket_info(_curl_info)) \
- if (!curlcheck_arr((arg), curl_socket_t)) \
+ if(curlcheck_socket_info(_curl_info)) \
+ if(!curlcheck_arr((arg), curl_socket_t)) \
_curl_easy_getinfo_err_curl_socket(); \
- if (curlcheck_off_t_info(_curl_info)) \
- if (!curlcheck_arr((arg), curl_off_t)) \
+ if(curlcheck_off_t_info(_curl_info)) \
+ if(!curlcheck_arr((arg), curl_off_t)) \
_curl_easy_getinfo_err_curl_off_t(); \
} \
curl_easy_getinfo(handle, _curl_info, arg); \
diff --git a/3rdParty/curl/urlapi.h b/3rdparty/curl/include/curl/urlapi.h
index e15c213..e15c213 100644
--- a/3rdParty/curl/urlapi.h
+++ b/3rdparty/curl/include/curl/urlapi.h
diff --git a/3rdparty/curl/lib/libcurl.lib b/3rdparty/curl/lib/libcurl.lib
new file mode 100644
index 0000000..06f6bcd
--- /dev/null
+++ b/3rdparty/curl/lib/libcurl.lib
Binary files differ
diff --git a/3rdparty/dirent/dirent.h b/3rdparty/dirent/dirent.h
new file mode 100644
index 0000000..d135596
--- /dev/null
+++ b/3rdparty/dirent/dirent.h
@@ -0,0 +1,1212 @@
+/*
+ * Dirent interface for Microsoft Visual Studio
+ *
+ * Copyright (C) 1998-2019 Toni Ronkko
+ * This file is part of dirent. Dirent may be freely distributed
+ * under the MIT license. For all details and documentation, see
+ * https://github.com/tronkko/dirent
+ */
+#ifndef DIRENT_H
+#define DIRENT_H
+
+/* Hide warnings about unreferenced local functions */
+#if defined(__clang__)
+# pragma clang diagnostic ignored "-Wunused-function"
+#elif defined(_MSC_VER)
+# pragma warning(disable:4505)
+#elif defined(__GNUC__)
+# pragma GCC diagnostic ignored "-Wunused-function"
+#endif
+
+/*
+ * Include windows.h without Windows Sockets 1.1 to prevent conflicts with
+ * Windows Sockets 2.0.
+ */
+#ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+#endif
+#include <windows.h>
+
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+#include <string.h>
+#include <stdlib.h>
+#include <malloc.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <ctype.h>
+
+/* Indicates that d_type field is available in dirent structure */
+#define _DIRENT_HAVE_D_TYPE
+
+/* Indicates that d_namlen field is available in dirent structure */
+#define _DIRENT_HAVE_D_NAMLEN
+
+/* Entries missing from MSVC 6.0 */
+#if !defined(FILE_ATTRIBUTE_DEVICE)
+# define FILE_ATTRIBUTE_DEVICE 0x40
+#endif
+
+/* File type and permission flags for stat(), general mask */
+#if !defined(S_IFMT)
+# define S_IFMT _S_IFMT
+#endif
+
+/* Directory bit */
+#if !defined(S_IFDIR)
+# define S_IFDIR _S_IFDIR
+#endif
+
+/* Character device bit */
+#if !defined(S_IFCHR)
+# define S_IFCHR _S_IFCHR
+#endif
+
+/* Pipe bit */
+#if !defined(S_IFFIFO)
+# define S_IFFIFO _S_IFFIFO
+#endif
+
+/* Regular file bit */
+#if !defined(S_IFREG)
+# define S_IFREG _S_IFREG
+#endif
+
+/* Read permission */
+#if !defined(S_IREAD)
+# define S_IREAD _S_IREAD
+#endif
+
+/* Write permission */
+#if !defined(S_IWRITE)
+# define S_IWRITE _S_IWRITE
+#endif
+
+/* Execute permission */
+#if !defined(S_IEXEC)
+# define S_IEXEC _S_IEXEC
+#endif
+
+/* Pipe */
+#if !defined(S_IFIFO)
+# define S_IFIFO _S_IFIFO
+#endif
+
+/* Block device */
+#if !defined(S_IFBLK)
+# define S_IFBLK 0
+#endif
+
+/* Link */
+#if !defined(S_IFLNK)
+# define S_IFLNK 0
+#endif
+
+/* Socket */
+#if !defined(S_IFSOCK)
+# define S_IFSOCK 0
+#endif
+
+/* Read user permission */
+#if !defined(S_IRUSR)
+# define S_IRUSR S_IREAD
+#endif
+
+/* Write user permission */
+#if !defined(S_IWUSR)
+# define S_IWUSR S_IWRITE
+#endif
+
+/* Execute user permission */
+#if !defined(S_IXUSR)
+# define S_IXUSR 0
+#endif
+
+/* Read group permission */
+#if !defined(S_IRGRP)
+# define S_IRGRP 0
+#endif
+
+/* Write group permission */
+#if !defined(S_IWGRP)
+# define S_IWGRP 0
+#endif
+
+/* Execute group permission */
+#if !defined(S_IXGRP)
+# define S_IXGRP 0
+#endif
+
+/* Read others permission */
+#if !defined(S_IROTH)
+# define S_IROTH 0
+#endif
+
+/* Write others permission */
+#if !defined(S_IWOTH)
+# define S_IWOTH 0
+#endif
+
+/* Execute others permission */
+#if !defined(S_IXOTH)
+# define S_IXOTH 0
+#endif
+
+/* Maximum length of file name */
+#if !defined(PATH_MAX)
+# define PATH_MAX MAX_PATH
+#endif
+#if !defined(FILENAME_MAX)
+# define FILENAME_MAX MAX_PATH
+#endif
+#if !defined(NAME_MAX)
+# define NAME_MAX FILENAME_MAX
+#endif
+
+/* File type flags for d_type */
+#define DT_UNKNOWN 0
+#define DT_REG S_IFREG
+#define DT_DIR S_IFDIR
+#define DT_FIFO S_IFIFO
+#define DT_SOCK S_IFSOCK
+#define DT_CHR S_IFCHR
+#define DT_BLK S_IFBLK
+#define DT_LNK S_IFLNK
+
+/* Macros for converting between st_mode and d_type */
+#define IFTODT(mode) ((mode) & S_IFMT)
+#define DTTOIF(type) (type)
+
+/*
+ * File type macros. Note that block devices, sockets and links cannot be
+ * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
+ * only defined for compatibility. These macros should always return false
+ * on Windows.
+ */
+#if !defined(S_ISFIFO)
+# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
+#endif
+#if !defined(S_ISDIR)
+# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
+#endif
+#if !defined(S_ISREG)
+# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
+#endif
+#if !defined(S_ISLNK)
+# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
+#endif
+#if !defined(S_ISSOCK)
+# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
+#endif
+#if !defined(S_ISCHR)
+# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
+#endif
+#if !defined(S_ISBLK)
+# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
+#endif
+
+/* Return the exact length of the file name without zero terminator */
+#define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
+
+/* Return the maximum size of a file name */
+#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1)
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Wide-character version */
+struct _wdirent {
+ /* Always zero */
+ long d_ino;
+
+ /* Position of next file in a directory stream */
+ long d_off;
+
+ /* Structure size */
+ unsigned short d_reclen;
+
+ /* Length of name without \0 */
+ size_t d_namlen;
+
+ /* File type */
+ int d_type;
+
+ /* File name */
+ wchar_t d_name[PATH_MAX+1];
+};
+typedef struct _wdirent _wdirent;
+
+struct _WDIR {
+ /* Current directory entry */
+ struct _wdirent ent;
+
+ /* Private file data */
+ WIN32_FIND_DATAW data;
+
+ /* True if data is valid */
+ int cached;
+
+ /* True if next entry is invalid */
+ int invalid;
+
+ /* Win32 search handle */
+ HANDLE handle;
+
+ /* Initial directory name */
+ wchar_t *patt;
+};
+typedef struct _WDIR _WDIR;
+
+/* Multi-byte character version */
+struct dirent {
+ /* Always zero */
+ long d_ino;
+
+ /* Position of next file in a directory stream */
+ long d_off;
+
+ /* Structure size */
+ unsigned short d_reclen;
+
+ /* Length of name without \0 */
+ size_t d_namlen;
+
+ /* File type */
+ int d_type;
+
+ /* File name */
+ char d_name[PATH_MAX+1];
+};
+typedef struct dirent dirent;
+
+struct DIR {
+ struct dirent ent;
+ struct _WDIR *wdirp;
+};
+typedef struct DIR DIR;
+
+
+/* Dirent functions */
+static DIR *opendir(const char *dirname);
+static _WDIR *_wopendir(const wchar_t *dirname);
+
+static struct dirent *readdir(DIR *dirp);
+static struct _wdirent *_wreaddir(_WDIR *dirp);
+
+static int readdir_r(
+ DIR *dirp, struct dirent *entry, struct dirent **result);
+static int _wreaddir_r(
+ _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result);
+
+static int closedir(DIR *dirp);
+static int _wclosedir(_WDIR *dirp);
+
+static void rewinddir(DIR *dirp);
+static void _wrewinddir(_WDIR *dirp);
+
+static long telldir(DIR *dirp);
+static long _wtelldir(_WDIR *dirp);
+
+static void seekdir(DIR *dirp, long loc);
+static void _wseekdir(_WDIR *dirp, long loc);
+
+static int scandir(const char *dirname, struct dirent ***namelist,
+ int (*filter)(const struct dirent*),
+ int (*compare)(const struct dirent**, const struct dirent**));
+
+static int alphasort(const struct dirent **a, const struct dirent **b);
+
+static int versionsort(const struct dirent **a, const struct dirent **b);
+
+static int strverscmp(const char *a, const char *b);
+
+/* For compatibility with Symbian */
+#define wdirent _wdirent
+#define WDIR _WDIR
+#define wopendir _wopendir
+#define wreaddir _wreaddir
+#define wclosedir _wclosedir
+#define wrewinddir _wrewinddir
+#define wtelldir _wtelldir
+#define wseekdir _wseekdir
+
+/* Compatibility with older Microsoft compilers and non-Microsoft compilers */
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+# define wcstombs_s dirent_wcstombs_s
+# define mbstowcs_s dirent_mbstowcs_s
+#endif
+
+/* Optimize dirent_set_errno() away on modern Microsoft compilers */
+#if defined(_MSC_VER) && _MSC_VER >= 1400
+# define dirent_set_errno _set_errno
+#endif
+
+
+/* Internal utility functions */
+static WIN32_FIND_DATAW *dirent_first(_WDIR *dirp);
+static WIN32_FIND_DATAW *dirent_next(_WDIR *dirp);
+static long dirent_hash(WIN32_FIND_DATAW *datap);
+
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static int dirent_mbstowcs_s(
+ size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords,
+ const char *mbstr, size_t count);
+#endif
+
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static int dirent_wcstombs_s(
+ size_t *pReturnValue, char *mbstr, size_t sizeInBytes,
+ const wchar_t *wcstr, size_t count);
+#endif
+
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static void dirent_set_errno(int error);
+#endif
+
+
+/*
+ * Open directory stream DIRNAME for read and return a pointer to the
+ * internal working area that is used to retrieve individual directory
+ * entries.
+ */
+static _WDIR *
+_wopendir(const wchar_t *dirname)
+{
+ wchar_t *p;
+
+ /* Must have directory name */
+ if (dirname == NULL || dirname[0] == '\0') {
+ dirent_set_errno(ENOENT);
+ return NULL;
+ }
+
+ /* Allocate new _WDIR structure */
+ _WDIR *dirp = (_WDIR*) malloc(sizeof(struct _WDIR));
+ if (!dirp)
+ return NULL;
+
+ /* Reset _WDIR structure */
+ dirp->handle = INVALID_HANDLE_VALUE;
+ dirp->patt = NULL;
+ dirp->cached = 0;
+ dirp->invalid = 0;
+
+ /*
+ * Compute the length of full path plus zero terminator
+ *
+ * Note that on WinRT there's no way to convert relative paths
+ * into absolute paths, so just assume it is an absolute path.
+ */
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+ /* Desktop */
+ DWORD n = GetFullPathNameW(dirname, 0, NULL, NULL);
+#else
+ /* WinRT */
+ size_t n = wcslen(dirname);
+#endif
+
+ /* Allocate room for absolute directory name and search pattern */
+ dirp->patt = (wchar_t*) malloc(sizeof(wchar_t) * n + 16);
+ if (dirp->patt == NULL)
+ goto exit_closedir;
+
+ /*
+ * Convert relative directory name to an absolute one. This
+ * allows rewinddir() to function correctly even when current
+ * working directory is changed between opendir() and rewinddir().
+ *
+ * Note that on WinRT there's no way to convert relative paths
+ * into absolute paths, so just assume it is an absolute path.
+ */
+#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+ /* Desktop */
+ n = GetFullPathNameW(dirname, n, dirp->patt, NULL);
+ if (n <= 0)
+ goto exit_closedir;
+#else
+ /* WinRT */
+ wcsncpy_s(dirp->patt, n+1, dirname, n);
+#endif
+
+ /* Append search pattern \* to the directory name */
+ p = dirp->patt + n;
+ switch (p[-1]) {
+ case '\\':
+ case '/':
+ case ':':
+ /* Directory ends in path separator, e.g. c:\temp\ */
+ /*NOP*/;
+ break;
+
+ default:
+ /* Directory name doesn't end in path separator */
+ *p++ = '\\';
+ }
+ *p++ = '*';
+ *p = '\0';
+
+ /* Open directory stream and retrieve the first entry */
+ if (!dirent_first(dirp))
+ goto exit_closedir;
+
+ /* Success */
+ return dirp;
+
+ /* Failure */
+exit_closedir:
+ _wclosedir(dirp);
+ return NULL;
+}
+
+/*
+ * Read next directory entry.
+ *
+ * Returns pointer to static directory entry which may be overwritten by
+ * subsequent calls to _wreaddir().
+ */
+static struct _wdirent *
+_wreaddir(_WDIR *dirp)
+{
+ /*
+ * Read directory entry to buffer. We can safely ignore the return
+ * value as entry will be set to NULL in case of error.
+ */
+ struct _wdirent *entry;
+ (void) _wreaddir_r(dirp, &dirp->ent, &entry);
+
+ /* Return pointer to statically allocated directory entry */
+ return entry;
+}
+
+/*
+ * Read next directory entry.
+ *
+ * Returns zero on success. If end of directory stream is reached, then sets
+ * result to NULL and returns zero.
+ */
+static int
+_wreaddir_r(
+ _WDIR *dirp, struct _wdirent *entry, struct _wdirent **result)
+{
+ /* Validate directory handle */
+ if (!dirp || dirp->handle == INVALID_HANDLE_VALUE || !dirp->patt) {
+ dirent_set_errno(EBADF);
+ *result = NULL;
+ return -1;
+ }
+
+ /* Read next directory entry */
+ WIN32_FIND_DATAW *datap = dirent_next(dirp);
+ if (!datap) {
+ /* Return NULL to indicate end of directory */
+ *result = NULL;
+ return /*OK*/0;
+ }
+
+ /*
+ * Copy file name as wide-character string. If the file name is too
+ * long to fit in to the destination buffer, then truncate file name
+ * to PATH_MAX characters and zero-terminate the buffer.
+ */
+ size_t i = 0;
+ while (i < PATH_MAX && datap->cFileName[i] != 0) {
+ entry->d_name[i] = datap->cFileName[i];
+ i++;
+ }
+ entry->d_name[i] = 0;
+
+ /* Length of file name excluding zero terminator */
+ entry->d_namlen = i;
+
+ /* Determine file type */
+ DWORD attr = datap->dwFileAttributes;
+ if ((attr & FILE_ATTRIBUTE_DEVICE) != 0)
+ entry->d_type = DT_CHR;
+ else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
+ entry->d_type = DT_DIR;
+ else
+ entry->d_type = DT_REG;
+
+ /* Read the next directory entry to cache */
+ datap = dirent_next(dirp);
+ if (datap) {
+ /* Compute 31-bit hash of the next directory entry */
+ entry->d_off = dirent_hash(datap);
+
+ /* Push the next directory entry back to cache */
+ dirp->cached = 1;
+ } else {
+ /* End of directory stream */
+ entry->d_off = (long) ((~0UL) >> 1);
+ }
+
+ /* Reset other fields */
+ entry->d_ino = 0;
+ entry->d_reclen = sizeof(struct _wdirent);
+
+ /* Set result address */
+ *result = entry;
+ return /*OK*/0;
+}
+
+/*
+ * Close directory stream opened by opendir() function. This invalidates the
+ * DIR structure as well as any directory entry read previously by
+ * _wreaddir().
+ */
+static int
+_wclosedir(_WDIR *dirp)
+{
+ if (!dirp) {
+ dirent_set_errno(EBADF);
+ return /*failure*/-1;
+ }
+
+ /*
+ * Release search handle if we have one. Being able to handle
+ * partially initialized _WDIR structure allows us to use this
+ * function to handle errors occuring within _wopendir.
+ */
+ if (dirp->handle != INVALID_HANDLE_VALUE) {
+ FindClose(dirp->handle);
+ }
+
+ /*
+ * Release search pattern. Note that we don't need to care if
+ * dirp->patt is NULL or not: function free is guaranteed to act
+ * appropriately.
+ */
+ free(dirp->patt);
+
+ /* Release directory structure */
+ free(dirp);
+ return /*success*/0;
+}
+
+/*
+ * Rewind directory stream such that _wreaddir() returns the very first
+ * file name again.
+ */
+static void _wrewinddir(_WDIR* dirp)
+{
+ /* Check directory pointer */
+ if (!dirp || dirp->handle == INVALID_HANDLE_VALUE || !dirp->patt)
+ return;
+
+ /* Release existing search handle */
+ FindClose(dirp->handle);
+
+ /* Open new search handle */
+ dirent_first(dirp);
+}
+
+/* Get first directory entry */
+static WIN32_FIND_DATAW *
+dirent_first(_WDIR *dirp)
+{
+ /* Open directory and retrieve the first entry */
+ dirp->handle = FindFirstFileExW(
+ dirp->patt, FindExInfoStandard, &dirp->data,
+ FindExSearchNameMatch, NULL, 0);
+ if (dirp->handle == INVALID_HANDLE_VALUE)
+ goto error;
+
+ /* A directory entry is now waiting in memory */
+ dirp->cached = 1;
+ return &dirp->data;
+
+error:
+ /* Failed to open directory: no directory entry in memory */
+ dirp->cached = 0;
+ dirp->invalid = 1;
+
+ /* Set error code */
+ DWORD errorcode = GetLastError();
+ switch (errorcode) {
+ case ERROR_ACCESS_DENIED:
+ /* No read access to directory */
+ dirent_set_errno(EACCES);
+ break;
+
+ case ERROR_DIRECTORY:
+ /* Directory name is invalid */
+ dirent_set_errno(ENOTDIR);
+ break;
+
+ case ERROR_PATH_NOT_FOUND:
+ default:
+ /* Cannot find the file */
+ dirent_set_errno(ENOENT);
+ }
+ return NULL;
+}
+
+/* Get next directory entry */
+static WIN32_FIND_DATAW *
+dirent_next(_WDIR *dirp)
+{
+ /* Return NULL if seek position was invalid */
+ if (dirp->invalid)
+ return NULL;
+
+ /* Is the next directory entry already in cache? */
+ if (dirp->cached) {
+ /* Yes, a valid directory entry found in memory */
+ dirp->cached = 0;
+ return &dirp->data;
+ }
+
+ /* Read the next directory entry from stream */
+ if (FindNextFileW(dirp->handle, &dirp->data) == FALSE) {
+ /* End of directory stream */
+ return NULL;
+ }
+
+ /* Success */
+ return &dirp->data;
+}
+
+/*
+ * Compute 31-bit hash of file name.
+ *
+ * See djb2 at http://www.cse.yorku.ca/~oz/hash.html
+ */
+static long
+dirent_hash(WIN32_FIND_DATAW *datap)
+{
+ unsigned long hash = 5381;
+ unsigned long c;
+ const wchar_t *p = datap->cFileName;
+ const wchar_t *e = p + MAX_PATH;
+ while (p != e && (c = *p++) != 0) {
+ hash = (hash << 5) + hash + c;
+ }
+
+ return (long) (hash & ((~0UL) >> 1));
+}
+
+/* Open directory stream using plain old C-string */
+static DIR *opendir(const char *dirname)
+{
+ /* Must have directory name */
+ if (dirname == NULL || dirname[0] == '\0') {
+ dirent_set_errno(ENOENT);
+ return NULL;
+ }
+
+ /* Allocate memory for DIR structure */
+ struct DIR *dirp = (DIR*) malloc(sizeof(struct DIR));
+ if (!dirp)
+ return NULL;
+
+ /* Convert directory name to wide-character string */
+ wchar_t wname[PATH_MAX + 1];
+ size_t n;
+ int error = mbstowcs_s(&n, wname, PATH_MAX + 1, dirname, PATH_MAX+1);
+ if (error)
+ goto exit_failure;
+
+ /* Open directory stream using wide-character name */
+ dirp->wdirp = _wopendir(wname);
+ if (!dirp->wdirp)
+ goto exit_failure;
+
+ /* Success */
+ return dirp;
+
+ /* Failure */
+exit_failure:
+ free(dirp);
+ return NULL;
+}
+
+/* Read next directory entry */
+static struct dirent *
+readdir(DIR *dirp)
+{
+ /*
+ * Read directory entry to buffer. We can safely ignore the return
+ * value as entry will be set to NULL in case of error.
+ */
+ struct dirent *entry;
+ (void) readdir_r(dirp, &dirp->ent, &entry);
+
+ /* Return pointer to statically allocated directory entry */
+ return entry;
+}
+
+/*
+ * Read next directory entry into called-allocated buffer.
+ *
+ * Returns zero on success. If the end of directory stream is reached, then
+ * sets result to NULL and returns zero.
+ */
+static int
+readdir_r(
+ DIR *dirp, struct dirent *entry, struct dirent **result)
+{
+ /* Read next directory entry */
+ WIN32_FIND_DATAW *datap = dirent_next(dirp->wdirp);
+ if (!datap) {
+ /* No more directory entries */
+ *result = NULL;
+ return /*OK*/0;
+ }
+
+ /* Attempt to convert file name to multi-byte string */
+ size_t n;
+ int error = wcstombs_s(
+ &n, entry->d_name, PATH_MAX + 1,
+ datap->cFileName, PATH_MAX + 1);
+
+ /*
+ * If the file name cannot be represented by a multi-byte string, then
+ * attempt to use old 8+3 file name. This allows the program to
+ * access files although file names may seem unfamiliar to the user.
+ *
+ * Be ware that the code below cannot come up with a short file name
+ * unless the file system provides one. At least VirtualBox shared
+ * folders fail to do this.
+ */
+ if (error && datap->cAlternateFileName[0] != '\0') {
+ error = wcstombs_s(
+ &n, entry->d_name, PATH_MAX + 1,
+ datap->cAlternateFileName, PATH_MAX + 1);
+ }
+
+ if (!error) {
+ /* Length of file name excluding zero terminator */
+ entry->d_namlen = n - 1;
+
+ /* Determine file type */
+ DWORD attr = datap->dwFileAttributes;
+ if ((attr & FILE_ATTRIBUTE_DEVICE) != 0)
+ entry->d_type = DT_CHR;
+ else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0)
+ entry->d_type = DT_DIR;
+ else
+ entry->d_type = DT_REG;
+
+ /* Get offset of next file */
+ datap = dirent_next(dirp->wdirp);
+ if (datap) {
+ /* Compute 31-bit hash of the next directory entry */
+ entry->d_off = dirent_hash(datap);
+
+ /* Push the next directory entry back to cache */
+ dirp->wdirp->cached = 1;
+ } else {
+ /* End of directory stream */
+ entry->d_off = (long) ((~0UL) >> 1);
+ }
+
+ /* Reset fields */
+ entry->d_ino = 0;
+ entry->d_reclen = sizeof(struct dirent);
+ } else {
+ /*
+ * Cannot convert file name to multi-byte string so construct
+ * an erroneous directory entry and return that. Note that
+ * we cannot return NULL as that would stop the processing
+ * of directory entries completely.
+ */
+ entry->d_name[0] = '?';
+ entry->d_name[1] = '\0';
+ entry->d_namlen = 1;
+ entry->d_type = DT_UNKNOWN;
+ entry->d_ino = 0;
+ entry->d_off = -1;
+ entry->d_reclen = 0;
+ }
+
+ /* Return pointer to directory entry */
+ *result = entry;
+ return /*OK*/0;
+}
+
+/* Close directory stream */
+static int
+closedir(DIR *dirp)
+{
+ int ok;
+
+ if (!dirp)
+ goto exit_failure;
+
+ /* Close wide-character directory stream */
+ ok = _wclosedir(dirp->wdirp);
+ dirp->wdirp = NULL;
+
+ /* Release multi-byte character version */
+ free(dirp);
+ return ok;
+
+exit_failure:
+ /* Invalid directory stream */
+ dirent_set_errno(EBADF);
+ return /*failure*/-1;
+}
+
+/* Rewind directory stream to beginning */
+static void
+rewinddir(DIR *dirp)
+{
+ if (!dirp)
+ return;
+
+ /* Rewind wide-character string directory stream */
+ _wrewinddir(dirp->wdirp);
+}
+
+/* Get position of directory stream */
+static long
+_wtelldir(_WDIR *dirp)
+{
+ if (!dirp || dirp->handle == INVALID_HANDLE_VALUE) {
+ dirent_set_errno(EBADF);
+ return /*failure*/-1;
+ }
+
+ /* Read next file entry */
+ WIN32_FIND_DATAW *datap = dirent_next(dirp);
+ if (!datap) {
+ /* End of directory stream */
+ return (long) ((~0UL) >> 1);
+ }
+
+ /* Store file entry to cache for readdir() */
+ dirp->cached = 1;
+
+ /* Return the 31-bit hash code to be used as stream position */
+ return dirent_hash(datap);
+}
+
+/* Get position of directory stream */
+static long
+telldir(DIR *dirp)
+{
+ if (!dirp) {
+ dirent_set_errno(EBADF);
+ return -1;
+ }
+
+ return _wtelldir(dirp->wdirp);
+}
+
+/* Seek directory stream to offset */
+static void
+_wseekdir(_WDIR *dirp, long loc)
+{
+ /* Directory must be open */
+ if (!dirp || dirp->handle == INVALID_HANDLE_VALUE)
+ goto exit_failure;
+
+ /* Ensure that seek position is valid */
+ if (loc < 0)
+ goto exit_failure;
+
+ /* Restart directory stream from the beginning */
+ FindClose(dirp->handle);
+ if (!dirent_first(dirp))
+ goto exit_failure;
+
+ /* Reset invalid flag so that we can read from the stream again */
+ dirp->invalid = 0;
+
+ /*
+ * Read directory entries from the beginning until the hash matches a
+ * file name. Be ware that hash code is only 31 bits longs and
+ * duplicates are possible: the hash code cannot return the position
+ * with 100.00% accuracy! Moreover, the method is slow for large
+ * directories.
+ */
+ long hash;
+ do {
+ /* Read next directory entry */
+ WIN32_FIND_DATAW *datap = dirent_next(dirp);
+ if (!datap) {
+ /*
+ * End of directory stream was reached before finding
+ * the requested location. Perhaps the file in
+ * question was deleted or moved out of the directory.
+ */
+ goto exit_failure;
+ }
+
+ /* Does the file name match the hash? */
+ hash = dirent_hash(datap);
+ } while (hash != loc);
+
+ /*
+ * File name matches the hash! Push the directory entry back to cache
+ * from where next readdir() will return it.
+ */
+ dirp->cached = 1;
+ dirp->invalid = 0;
+ return;
+
+exit_failure:
+ /* Ensure that readdir will return NULL */
+ dirp->invalid = 1;
+}
+
+/* Seek directory stream to offset */
+static void
+seekdir(DIR *dirp, long loc)
+{
+ if (!dirp)
+ return;
+
+ _wseekdir(dirp->wdirp, loc);
+}
+
+/* Scan directory for entries */
+static int
+scandir(
+ const char *dirname, struct dirent ***namelist,
+ int (*filter)(const struct dirent*),
+ int (*compare)(const struct dirent**, const struct dirent**))
+{
+ int result;
+
+ /* Open directory stream */
+ DIR *dir = opendir(dirname);
+ if (!dir) {
+ /* Cannot open directory */
+ return /*Error*/ -1;
+ }
+
+ /* Read directory entries to memory */
+ struct dirent *tmp = NULL;
+ struct dirent **files = NULL;
+ size_t size = 0;
+ size_t allocated = 0;
+ while (1) {
+ /* Allocate room for a temporary directory entry */
+ if (!tmp) {
+ tmp = (struct dirent*) malloc(sizeof(struct dirent));
+ if (!tmp)
+ goto exit_failure;
+ }
+
+ /* Read directory entry to temporary area */
+ struct dirent *entry;
+ if (readdir_r(dir, tmp, &entry) != /*OK*/0)
+ goto exit_failure;
+
+ /* Stop if we already read the last directory entry */
+ if (entry == NULL)
+ goto exit_success;
+
+ /* Determine whether to include the entry in results */
+ if (filter && !filter(tmp))
+ continue;
+
+ /* Enlarge pointer table to make room for another pointer */
+ if (size >= allocated) {
+ /* Compute number of entries in the new table */
+ size_t num_entries = size * 2 + 16;
+
+ /* Allocate new pointer table or enlarge existing */
+ void *p = realloc(files, sizeof(void*) * num_entries);
+ if (!p)
+ goto exit_failure;
+
+ /* Got the memory */
+ files = (dirent**) p;
+ allocated = num_entries;
+ }
+
+ /* Store the temporary entry to ptr table */
+ files[size++] = tmp;
+ tmp = NULL;
+ }
+
+exit_failure:
+ /* Release allocated entries */
+ for (size_t i = 0; i < size; i++) {
+ free(files[i]);
+ }
+
+ /* Release the pointer table */
+ free(files);
+ files = NULL;
+
+ /* Exit with error code */
+ result = /*error*/ -1;
+ goto exit_status;
+
+exit_success:
+ /* Sort directory entries */
+ qsort(files, size, sizeof(void*),
+ (int (*) (const void*, const void*)) compare);
+
+ /* Pass pointer table to caller */
+ if (namelist)
+ *namelist = files;
+
+ /* Return the number of directory entries read */
+ result = (int) size;
+
+exit_status:
+ /* Release temporary directory entry, if we had one */
+ free(tmp);
+
+ /* Close directory stream */
+ closedir(dir);
+ return result;
+}
+
+/* Alphabetical sorting */
+static int
+alphasort(const struct dirent **a, const struct dirent **b)
+{
+ return strcoll((*a)->d_name, (*b)->d_name);
+}
+
+/* Sort versions */
+static int
+versionsort(const struct dirent **a, const struct dirent **b)
+{
+ return strverscmp((*a)->d_name, (*b)->d_name);
+}
+
+/* Compare strings */
+static int
+strverscmp(const char *a, const char *b)
+{
+ size_t i = 0;
+ size_t j;
+
+ /* Find first difference */
+ while (a[i] == b[i]) {
+ if (a[i] == '\0') {
+ /* No difference */
+ return 0;
+ }
+ ++i;
+ }
+
+ /* Count backwards and find the leftmost digit */
+ j = i;
+ while (j > 0 && isdigit(a[j-1])) {
+ --j;
+ }
+
+ /* Determine mode of comparison */
+ if (a[j] == '0' || b[j] == '0') {
+ /* Find the next non-zero digit */
+ while (a[j] == '0' && a[j] == b[j]) {
+ j++;
+ }
+
+ /* String with more digits is smaller, e.g 002 < 01 */
+ if (isdigit(a[j])) {
+ if (!isdigit(b[j])) {
+ return -1;
+ }
+ } else if (isdigit(b[j])) {
+ return 1;
+ }
+ } else if (isdigit(a[j]) && isdigit(b[j])) {
+ /* Numeric comparison */
+ size_t k1 = j;
+ size_t k2 = j;
+
+ /* Compute number of digits in each string */
+ while (isdigit(a[k1])) {
+ k1++;
+ }
+ while (isdigit(b[k2])) {
+ k2++;
+ }
+
+ /* Number with more digits is bigger, e.g 999 < 1000 */
+ if (k1 < k2)
+ return -1;
+ else if (k1 > k2)
+ return 1;
+ }
+
+ /* Alphabetical comparison */
+ return (int) ((unsigned char) a[i]) - ((unsigned char) b[i]);
+}
+
+/* Convert multi-byte string to wide character string */
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static int
+dirent_mbstowcs_s(
+ size_t *pReturnValue, wchar_t *wcstr,
+ size_t sizeInWords, const char *mbstr, size_t count)
+{
+ /* Older Visual Studio or non-Microsoft compiler */
+ size_t n = mbstowcs(wcstr, mbstr, sizeInWords);
+ if (wcstr && n >= count)
+ return /*error*/ 1;
+
+ /* Zero-terminate output buffer */
+ if (wcstr && sizeInWords) {
+ if (n >= sizeInWords)
+ n = sizeInWords - 1;
+ wcstr[n] = 0;
+ }
+
+ /* Length of multi-byte string with zero terminator */
+ if (pReturnValue) {
+ *pReturnValue = n + 1;
+ }
+
+ /* Success */
+ return 0;
+}
+#endif
+
+/* Convert wide-character string to multi-byte string */
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static int
+dirent_wcstombs_s(
+ size_t *pReturnValue, char *mbstr,
+ size_t sizeInBytes, const wchar_t *wcstr, size_t count)
+{
+ /* Older Visual Studio or non-Microsoft compiler */
+ size_t n = wcstombs(mbstr, wcstr, sizeInBytes);
+ if (mbstr && n >= count)
+ return /*error*/1;
+
+ /* Zero-terminate output buffer */
+ if (mbstr && sizeInBytes) {
+ if (n >= sizeInBytes) {
+ n = sizeInBytes - 1;
+ }
+ mbstr[n] = '\0';
+ }
+
+ /* Length of resulting multi-bytes string WITH zero-terminator */
+ if (pReturnValue) {
+ *pReturnValue = n + 1;
+ }
+
+ /* Success */
+ return 0;
+}
+#endif
+
+/* Set errno variable */
+#if !defined(_MSC_VER) || _MSC_VER < 1400
+static void
+dirent_set_errno(int error)
+{
+ /* Non-Microsoft compiler or older Microsoft compiler */
+ errno = error;
+}
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif /*DIRENT_H*/ \ No newline at end of file
diff --git a/3rdParty/hmac_sha256/CMakeLists.txt b/3rdparty/hmac_sha256/CMakeLists.txt
index 8a50340..8a50340 100644
--- a/3rdParty/hmac_sha256/CMakeLists.txt
+++ b/3rdparty/hmac_sha256/CMakeLists.txt
diff --git a/3rdParty/hmac_sha256/LICENSE b/3rdparty/hmac_sha256/LICENSE
index fdddb29..fdddb29 100644
--- a/3rdParty/hmac_sha256/LICENSE
+++ b/3rdparty/hmac_sha256/LICENSE
diff --git a/3rdParty/hmac_sha256/README.md b/3rdparty/hmac_sha256/README.md
index a8bf2c7..a8bf2c7 100644
--- a/3rdParty/hmac_sha256/README.md
+++ b/3rdparty/hmac_sha256/README.md
diff --git a/3rdParty/hmac_sha256/hmac_sha256.c b/3rdparty/hmac_sha256/hmac_sha256.c
index d23a6e2..d23a6e2 100644
--- a/3rdParty/hmac_sha256/hmac_sha256.c
+++ b/3rdparty/hmac_sha256/hmac_sha256.c
diff --git a/3rdParty/hmac_sha256/hmac_sha256.h b/3rdparty/hmac_sha256/hmac_sha256.h
index 976b6c1..976b6c1 100644
--- a/3rdParty/hmac_sha256/hmac_sha256.h
+++ b/3rdparty/hmac_sha256/hmac_sha256.h
diff --git a/3rdParty/hmac_sha256/sha256.c b/3rdparty/hmac_sha256/sha256.c
index 95def0b..95def0b 100644
--- a/3rdParty/hmac_sha256/sha256.c
+++ b/3rdparty/hmac_sha256/sha256.c
diff --git a/3rdParty/hmac_sha256/sha256.h b/3rdparty/hmac_sha256/sha256.h
index ddedf9f..ddedf9f 100644
--- a/3rdParty/hmac_sha256/sha256.h
+++ b/3rdparty/hmac_sha256/sha256.h
diff --git a/3rdparty/windowsdaemon/windowsdaemon.cpp b/3rdparty/windowsdaemon/windowsdaemon.cpp
new file mode 100644
index 0000000..50d8c1a
--- /dev/null
+++ b/3rdparty/windowsdaemon/windowsdaemon.cpp
@@ -0,0 +1,441 @@
+//#include <windows.h>
+#include <tchar.h>
+#include <strsafe.h>
+#include <cstdio>
+
+#include "licenser.h"
+
+#define SVCNAME TEXT("licd")
+
+SERVICE_STATUS gSvcStatus;
+SERVICE_STATUS_HANDLE gSvcStatusHandle;
+HANDLE ghSvcStopEvent = NULL;
+
+VOID SvcInstall(void);
+VOID __stdcall DoDeleteSvc(void);
+VOID WINAPI SvcCtrlHandler( DWORD );
+VOID WINAPI SvcMain( DWORD, LPTSTR * );
+
+VOID ReportSvcStatus( DWORD, DWORD, DWORD );
+VOID SvcInit( DWORD, LPTSTR * );
+VOID SvcReportEvent( LPTSTR );
+
+int startProcess();
+
+
+//
+// Purpose:
+// Entry point for the process
+//
+// Parameters:
+// None
+//
+// Return value:
+// None, defaults to 0 (zero)
+//
+int __cdecl _tmain(int argc, TCHAR *argv[])
+{
+ // If command-line parameter is "--nodaemon", start as normal CLI process (not as daemon)
+ if (lstrcmpi(argv[1], TEXT("--nodaemon")) == 0) {
+ // Fire it up
+ printf("Starting licd as CLI tool\n");
+ Licenser licenser(0);
+ while (true)
+ {
+ try {
+ licenser.listen();
+ }
+ catch (...) {
+ printf("ERROR: Qt License Daemon listen() failed!!\n");
+ return -1;
+ }
+ }
+ }
+ // If command-line parameter is "--version", show the version and exit.
+ if (lstrcmpi(argv[1], TEXT("--version")) == 0) {
+ std::cout << "Qt License Daemon (licd) v" << DAEMON_VERSION << " "
+ << COPYRIGHT_TEXT << std::endl;
+ return 0;
+ }
+ // If command-line parameter is "install", install the service.
+ printf("Service main()\n");
+ if ( lstrcmpi( argv[1], TEXT("--install")) == 0 )
+ {
+ printf("Installing service\n");
+ SvcInstall();
+ return 0;
+ }
+ if ( lstrcmpi( argv[1], TEXT("--delete")) == 0 )
+ {
+ printf("Deleting service\n");
+ DoDeleteSvc();
+ return 0;
+ }
+ // Otherwise, the service is probably being started by the SCM.
+
+ SERVICE_TABLE_ENTRY DispatchTable[] =
+ {
+ { SVCNAME, (LPSERVICE_MAIN_FUNCTION) SvcMain },
+ { NULL, NULL }
+ };
+
+ // This call returns when the service has stopped.
+ // The process should simply terminate when the call returns.
+
+ if (!StartServiceCtrlDispatcher( DispatchTable ))
+ {
+ SvcReportEvent(TEXT("StartServiceCtrlDispatcher"));
+ }
+}
+
+//
+// Purpose:
+// Installs a service in the SCM database
+//
+// Parameters:
+// None
+//
+// Return value:
+// None
+//
+VOID SvcInstall()
+{
+ SC_HANDLE schSCManager;
+ SC_HANDLE schService;
+ TCHAR szUnquotedPath[MAX_PATH];
+ SERVICE_DESCRIPTION sd;
+ LPTSTR szDesc = TEXT(LICD_SERVICE_DESCRIPTION);
+ if ( !GetModuleFileName( NULL, szUnquotedPath, MAX_PATH ) )
+ {
+ printf("Cannot install service (%d)\n", GetLastError());
+ return;
+ }
+
+ // In case the path contains a space, it must be quoted so that
+ // it is correctly interpreted. For example,
+ // "d:\my share\myservice.exe" should be specified as
+ // ""d:\my share\myservice.exe"".
+ TCHAR szPath[MAX_PATH];
+ StringCbPrintf(szPath, MAX_PATH, TEXT("\"%s\""), szUnquotedPath);
+
+ // Get a handle to the SCM database.
+
+ schSCManager = OpenSCManager(
+ NULL, // local computer
+ NULL, // ServicesActive database
+ SC_MANAGER_ALL_ACCESS); // full access rights
+
+ if (NULL == schSCManager)
+ {
+ printf("OpenSCManager failed (%d)\n", GetLastError());
+ return;
+ }
+
+ // Create the service
+
+ schService = CreateService(
+ schSCManager, // SCM database
+ SVCNAME, // name of service
+ SVCNAME, // service name to display
+ SERVICE_ALL_ACCESS, // desired access
+ SERVICE_WIN32_OWN_PROCESS, // service type
+ SERVICE_AUTO_START, // start type
+ SERVICE_ERROR_NORMAL, // error control type
+ szPath, // path to service's binary
+ NULL, // no load ordering group
+ NULL, // no tag identifier
+ NULL, // no dependencies
+ NULL, // LocalSystem account
+ NULL); // no password
+
+ if (schService == NULL)
+ {
+ printf("CreateService failed (%d)\n", GetLastError());
+ CloseServiceHandle(schSCManager);
+ return;
+ }
+ else printf("Service installed successfully\n");
+
+ // Change the service description.
+ sd.lpDescription = szDesc;
+ if ( !ChangeServiceConfig2(
+ schService, // handle to service
+ SERVICE_CONFIG_DESCRIPTION, // change: description
+ &sd) ) // new description
+ {
+ printf("ChangeServiceConfig2 failed\n");
+ }
+
+ CloseServiceHandle(schService);
+ CloseServiceHandle(schSCManager);
+}
+
+//
+// Purpose:
+// Entry point for the service
+//
+// Parameters:
+// dwArgc - Number of arguments in the lpszArgv array
+// lpszArgv - Array of strings. The first string is the name of
+// the service and subsequent strings are passed by the process
+// that called the StartService function to start the service.
+//
+// Return value:
+// None.
+//
+VOID WINAPI SvcMain( DWORD dwArgc, LPTSTR *lpszArgv )
+{
+ // Register the handler function for the service
+
+ gSvcStatusHandle = RegisterServiceCtrlHandler(
+ SVCNAME,
+ SvcCtrlHandler);
+
+ if ( !gSvcStatusHandle )
+ {
+ SvcReportEvent(TEXT("RegisterServiceCtrlHandler"));
+ return;
+ }
+
+ // These SERVICE_STATUS members remain as set here
+
+ gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+ gSvcStatus.dwServiceSpecificExitCode = 0;
+
+ // Report initial status to the SCM
+
+ ReportSvcStatus( SERVICE_START_PENDING, NO_ERROR, 3000 );
+
+ // Perform service-specific initialization and work.
+
+ SvcInit( dwArgc, lpszArgv );
+}
+
+//
+// Purpose:
+// The service code
+//
+// Parameters:
+// dwArgc - Number of arguments in the lpszArgv array
+// lpszArgv - Array of strings. The first string is the name of
+// the service and subsequent strings are passed by the process
+// that called the StartService function to start the service.
+//
+// Return value:
+// None
+//
+VOID SvcInit( DWORD dwArgc, LPTSTR *lpszArgv)
+{
+ // TO_DO: Declare and set any required variables.
+ // Be sure to periodically call ReportSvcStatus() with
+ // SERVICE_START_PENDING. If initialization fails, call
+ // ReportSvcStatus with SERVICE_STOPPED.
+
+ // Create an event. The control handler function, SvcCtrlHandler,
+ // signals this event when it receives the stop control code.
+
+ ghSvcStopEvent = CreateEvent(
+ NULL, // default security attributes
+ TRUE, // manual reset event
+ FALSE, // not signaled
+ NULL); // no name
+
+ if ( ghSvcStopEvent == NULL)
+ {
+ ReportSvcStatus( SERVICE_STOPPED, GetLastError(), 0 );
+ return;
+ }
+
+ // Report running status when initialization is complete.
+
+ ReportSvcStatus( SERVICE_RUNNING, NO_ERROR, 0 );
+
+ // Fire it up
+ printf("Starting daemon\n");
+ Licenser licenser(0);
+
+ // Perform work until service stops.
+ while (WaitForSingleObject(ghSvcStopEvent, 0) != WAIT_OBJECT_0)
+ {
+ try {
+ licenser.listen();
+ }
+ catch (...) {
+ printf("ERROR: Qt License Daemon listen() failed!!\n");
+ }
+ }
+ ReportSvcStatus( SERVICE_STOP_PENDING, NO_ERROR, 0 );
+ CloseHandle(ghSvcStopEvent);
+ ReportSvcStatus( SERVICE_STOPPED, NO_ERROR, 0 );
+ return;
+}
+
+//
+// Purpose:
+// Sets the current service status and reports it to the SCM.
+//
+// Parameters:
+// dwCurrentState - The current state (see SERVICE_STATUS)
+// dwWin32ExitCode - The system error code
+// dwWaitHint - Estimated time for pending operation,
+// in milliseconds
+//
+// Return value:
+// None
+//
+VOID ReportSvcStatus( DWORD dwCurrentState,
+ DWORD dwWin32ExitCode,
+ DWORD dwWaitHint)
+{
+ static DWORD dwCheckPoint = 1;
+
+ // Fill in the SERVICE_STATUS structure.
+
+ gSvcStatus.dwCurrentState = dwCurrentState;
+ gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
+ gSvcStatus.dwWaitHint = dwWaitHint;
+
+ if (dwCurrentState == SERVICE_START_PENDING)
+ gSvcStatus.dwControlsAccepted = 0;
+ else gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+
+ if ( (dwCurrentState == SERVICE_RUNNING) ||
+ (dwCurrentState == SERVICE_STOPPED) )
+ gSvcStatus.dwCheckPoint = 0;
+ else gSvcStatus.dwCheckPoint = dwCheckPoint++;
+
+ // Report the status of the service to the SCM.
+ SetServiceStatus( gSvcStatusHandle, &gSvcStatus );
+}
+
+//
+// Purpose:
+// Called by SCM whenever a control code is sent to the service
+// using the ControlService function.
+//
+// Parameters:
+// dwCtrl - control code
+//
+// Return value:
+// None
+//
+VOID WINAPI SvcCtrlHandler( DWORD dwCtrl )
+{
+ // Handle the requested control code.
+
+ switch (dwCtrl)
+ {
+ case SERVICE_CONTROL_STOP:
+ ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
+
+ // Signal the service to stop.
+
+ SetEvent(ghSvcStopEvent);
+ ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
+
+ return;
+
+ case SERVICE_CONTROL_INTERROGATE:
+ break;
+
+ default:
+ break;
+ }
+
+}
+
+//
+// Purpose:
+// Logs messages to the event log
+//
+// Parameters:
+// szFunction - name of function that failed
+//
+// Return value:
+// None
+//
+// Remarks:
+// The service must have an entry in the Application event log.
+//
+VOID SvcReportEvent(LPTSTR szFunction)
+{
+ HANDLE hEventSource;
+ LPCTSTR lpszStrings[2];
+ TCHAR Buffer[80];
+
+ hEventSource = RegisterEventSource(NULL, SVCNAME);
+
+ if ( NULL != hEventSource )
+ {
+ StringCchPrintf(Buffer, 80, TEXT("%s failed with %d"), szFunction, GetLastError());
+
+ lpszStrings[0] = SVCNAME;
+ lpszStrings[1] = Buffer;
+
+ ReportEvent(hEventSource, // event log handle
+ EVENTLOG_ERROR_TYPE, // event type
+ 0, // event category
+ 0, // event identifier
+ NULL, // no security identifier
+ 2, // size of lpszStrings array
+ 0, // no binary data
+ lpszStrings, // array of strings
+ NULL); // no binary data
+
+ DeregisterEventSource(hEventSource);
+ }
+}
+
+//
+// Purpose:
+// Deletes a service from the SCM database
+//
+// Parameters:
+// None
+//
+// Return value:
+// None
+//
+VOID __stdcall DoDeleteSvc()
+{
+ SC_HANDLE schSCManager;
+ SC_HANDLE schService;
+ //TCHAR szSvcName[80] = SERVI;
+ // Get a handle to the SCM database.
+
+ schSCManager = OpenSCManager(
+ NULL, // local computer
+ NULL, // ServicesActive database
+ SC_MANAGER_ALL_ACCESS); // full access rights
+
+ if (NULL == schSCManager)
+ {
+ printf("OpenSCManager failed (%d)\n", GetLastError());
+ return;
+ }
+
+ // Get a handle to the service.
+
+ schService = OpenService(
+ schSCManager, // SCM database
+ SVCNAME, // name of service
+ DELETE); // need delete access
+
+ if (schService == NULL)
+ {
+ printf("OpenService failed (%d)\n", GetLastError());
+ CloseServiceHandle(schSCManager);
+ return;
+ }
+
+ // Delete the service.
+
+ if (! DeleteService(schService) )
+ {
+ printf("DeleteService failed (%d)\n", GetLastError());
+ }
+ else printf("Service deleted successfully\n");
+
+ CloseServiceHandle(schService);
+ CloseServiceHandle(schSCManager);
+}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 682f449..bb71ed5 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,65 +1,78 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+#
+# Published under GPL-3.0 with Qt-GPL-exception-1.0
+#
+
cmake_minimum_required(VERSION 3.1)
-#SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)
-#set(CMAKE_CXX_COMPILER C:/MinGW/bin/g++.exe)
+
project(licd)
cmake_policy(SET CMP0042 NEW)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
-# find_package(CURL REQUIRED)
ADD_DEFINITIONS(-DUNICODE)
ADD_DEFINITIONS(-D_UNICODE)
list(APPEND targetSrc
-${CMAKE_CURRENT_LIST_DIR}/licenser.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/licenser.cpp
${CMAKE_CURRENT_LIST_DIR}/tcpserver.cpp
${CMAKE_CURRENT_LIST_DIR}/httpclient.cpp
${CMAKE_CURRENT_LIST_DIR}/jsonhandler.cpp
- )
+ ${CMAKE_CURRENT_LIST_DIR}/utils.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/licdsetup.cpp
+)
list(APPEND includes
-${CMAKE_CURRENT_LIST_DIR}/include
- ${CMAKE_CURRENT_LIST_DIR}/3rdParty/
- #${CMAKE_CURRENT_LIST_DIR}/3rdParty/hmac_sha256
- )
-message("Compiler: ${CMAKE_CXX_COMPILER_ID}")
-message("System: ${CMAKE_SYSTEM}")
+ ${CMAKE_CURRENT_LIST_DIR}/include
+ ${CMAKE_CURRENT_LIST_DIR}/3rdparty
+)
+
+list(APPEND libs hmac_sha256)
-# For "CMAKE_INSTALL_<dir>" standard installation directories
include(GNUInstallDirs)
+
if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
+set(BUILD_SHARED_LIBS OFF)
+ set(CURL_INCLUDE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/curl/include)
+ set(CURL_LIBRARY ${CMAKE_SOURCE_DIR}/3rdparty/curl/lib/libcurl.lib)
+ set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
+ add_definitions(-DCURL_STATICLIB)
+ list(APPEND includes
+ ${CURL_INCLUDE_DIR}
+ )
list(APPEND targetSrc
- ${CMAKE_CURRENT_LIST_DIR}/win/Svc.cpp
- ${CMAKE_CURRENT_LIST_DIR}/win/SvcConfig.cpp
- ${CMAKE_CURRENT_LIST_DIR}/win/SvcControl.cpp
- ${CMAKE_CURRENT_LIST_DIR}/win/getopt.c
- #${CMAKE_CURRENT_LIST_DIR}/win_service/SrvCtrl.cpp
- #${CMAKE_CURRENT_LIST_DIR}/win_service/BaseSrv.cpp
- #${CMAKE_CURRENT_LIST_DIR}/win_service/SrvCtrl.cpp
+ ${CMAKE_CURRENT_LIST_DIR}/3rdparty/windowsdaemon/windowsdaemon.cpp
)
- list(APPEND includes
- ${CMAKE_CURRENT_LIST_DIR}/win
+ list(APPEND libs
+ ws2_32.lib crypt32.lib wldap32.lib normaliz.lib
+ ${CURL_LIBRARY}
)
- set(CMAKE_CXX_FLAGS "-static-libgcc -static-libstdc++ -static -lpthread") # POSIX stdlibs
else()
list(APPEND targetSrc
${CMAKE_CURRENT_LIST_DIR}/linux_daemon/linuxdaemon.cpp
- ${CMAKE_CURRENT_LIST_DIR}/linux_daemon/linuxdaemon.h
- )
- list(APPEND includes
- ${CMAKE_CURRENT_LIST_DIR}/linux_daemon
)
+ list(APPEND libs curl)
endif ()
-#message("Sources: ${targetSrc}")
-#message("Includes: ${includes}")
-add_subdirectory(3rdParty/hmac_sha256)
-add_subdirectory(qtlongterm)
+find_package(CURL REQUIRED)
+
+message("Compiler: ${CMAKE_CXX_COMPILER_ID}")
+message("System: ${CMAKE_SYSTEM}")
+message("Libs: ${libs}")
+
+add_subdirectory(3rdparty/hmac_sha256)
+add_subdirectory(qtlicensetool)
add_subdirectory(mocwrapper)
add_executable(licheck dummy_licheck.cpp)
-
add_executable(${PROJECT_NAME} ${targetSrc})
+if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
+ target_link_options(${PROJECT_NAME} PRIVATE "/NODEFAULTLIB:LIBCMT")
+ target_link_options(${PROJECT_NAME} PRIVATE "/NODEFAULTLIB:MSVCRTD")
+ #add_executable(svccontrol windowsdaemon/SvcControl.cpp)
+ #add_executable(svcconfig windowsdaemon/SvcConfig.cpp)
+endif ()
target_include_directories(${PROJECT_NAME} PUBLIC ${includes})
-target_link_libraries(${PROJECT_NAME} hmac_sha256 curl)
+target_link_libraries(${PROJECT_NAME} ${libs} )
diff --git a/CMakePresets.json b/CMakePresets.json
new file mode 100644
index 0000000..ba0884e
--- /dev/null
+++ b/CMakePresets.json
@@ -0,0 +1,70 @@
+{
+ "version": 3,
+ "configurePresets": [
+ {
+ "name": "windows-base",
+ "hidden": true,
+ "generator": "Ninja",
+ "binaryDir": "${sourceDir}/build",
+ "installDir": "${sourceDir}/deploy/${presetName}",
+ "cacheVariables": {
+
+ },
+ "condition": {
+ "type": "equals",
+ "lhs": "${hostSystemName}",
+ "rhs": "Windows"
+ }
+ },
+ {
+ "name": "x64-debug",
+ "displayName": "x64 Debug",
+ "inherits": "windows-base",
+ "architecture": {
+ "value": "x64",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Debug"
+ }
+ },
+ {
+ "name": "x64-release",
+ "displayName": "x64 Release",
+ "inherits": "x64-debug",
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Release"
+ }
+ },
+ {
+ "name": "x86-debug",
+ "displayName": "x86 Debug",
+ "inherits": "windows-base",
+ "architecture": {
+ "value": "x86",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Debug"
+ }
+ },
+ {
+ "name": "x86-release",
+ "displayName": "x86 Release",
+ "inherits": "x86-debug",
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Release"
+ }
+ }
+ ],
+
+ "buildPresets":
+ [
+ {
+ "name": "build",
+ "configurePreset": "x64-debug",
+ "jobs": 2
+ }
+ ]
+
+}
diff --git a/GHANGELOG b/GHANGELOG
new file mode 100644
index 0000000..b524066
--- /dev/null
+++ b/GHANGELOG
@@ -0,0 +1,13 @@
+Qt License daemon changelog
+
+Changes since 0.xxx
+
+- 'qtlongterm' CLI tool replaced qith new, more generic 'qtlicensetool'
+- Long-term functionality added in qtlicensetool through -L (or --longterm) switch
+- qtlicensetool always uses [default] section in user settings file to get its settings from
+ * Swithces used in qtlongterm command are now mostly optional, to be able to override the [default] ones
+ * See 'qtlicensetool --help' or README.md
+- Version queries now possible with qtlicensetool
+ * Version queries from License Service (daemon), License server and the tool itself
+- The binaries (licd, mocwrapper, qtlicensetool) now accept --version (or -v) switch
+- Several under-the-hood improvements for maintainability and robustness
diff --git a/INSTALL_linux.txt b/INSTALL_linux.txt
new file mode 100644
index 0000000..406b4e4
--- /dev/null
+++ b/INSTALL_linux.txt
@@ -0,0 +1,58 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+//
+
+Qt Licenser daemon for Linux
+
+- Tested in Ubuntu 16.04, Mint 20.3, Macbook Pro M1 (Mac from console only, not as a daemon)
+- This README does not include Windows version, because it's not supported yet
+
+Prerequisites:
+ cmake, curl, build-essentials
+
+To build, run the build script: (from project root)
+
+ ./build.sh
+
+
+---------- Install it as a service: ----------
+
+cd to deploy/ directory (created by build.sh):
+ cd deploy
+
+At this point, you might want to edit the licd.ini file, where most important is the License Server address to be able to connect to it. If you do this later, you need to edit /opt/licd.ini as root. See licd.ini in deploy directory.
+
+Run installation script as root:
+ sudo ./installer.sh
+
+(will now start automatically after reboot, too)
+
+To get MOC wrapper working, too, please note: Installation script does not know your Qt installation location (Something like /home/user/Qt/6.3.1/gcc_64/libexec/). That's why you need to set MOC wrapper working by doing:
+ 1. cd [your Qt framework install dir]
+ 2. mv moc orig_moc <--- Note: has to be exactly 'orig_moc'
+ 3. ln -s /opt/licd/mocwrapper moc
+ 4. Try it by building any Qt-enabled app wit any IDE or from command line
+
+In case youre using Qt5, you need to enable legacy support for its qmake licensing system by replacing licheck binary with the provided one:
+ (Still in the Qt installation location):
+ 1. cp licheck licheck.bak <--- This is just to back up the original, you can name it freely
+ 2. ln -s /opt/licd/licheck licheck
+
+
+Check if the service running:
+ sudo systemctl status licd
+
+To stop it:
+ sudo systemctl stop licd
+
+to disable it:
+ sudo systemctl disable licd
+
+To view logs:
+ journalctl -u licd -n 100
+ (Displays last 100 lines. If -n is not given, it will show all the logs)
+
+To completely uninstall, run 'uninstaller.sh' from deploy directory (as root, of course)
+ In addition, you need to remove symlinks from Qt installation dir and restore original binaries there:
+ - cd <your Qt installation dir>
+ - mv orig_moc moc
+ - mv licheck.bak licheck <-- or whatever you named your backup
diff --git a/INSTALL_win.txt b/INSTALL_win.txt
new file mode 100644
index 0000000..7ede120
--- /dev/null
+++ b/INSTALL_win.txt
@@ -0,0 +1,65 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+//
+
+Qt Licenser daemon for Windows
+
+Prerequisites:
+ cmake, Microsoft Windows SDK, MSVC <--- Download & install these first as needed
+
+============ Build and installation
+
+Firstly, take a note that configure/build relies on MSVC (not tested on mingw or others).
+If you need, edit the build_windows.bat file from the line stating
+ "cmake .. -G "Visual Studio 17 2022"
+That's for most current MSVC version, change as required
+
+Put "cmd" in the search box right next to the windows start menu, right click on "Command Promt"
+(that appears in the menu) and click "run as administrator". Command prompt should open now.
+
+In the command prompt, start the build script by typing:
+ > build_windows.bat
+
+Edit the licd.ini file under <project root>\deploy to match your system setup
+
+From this point forward, you need to be an admin. So if you didn't do so already, open the command prompt as an administrator.
+Go back to the <project root>\deploy directory:
+ > cd .. (from build dir if still there)
+ > cd deploy
+ > copy *.* "C:\Program Files\licd\"
+
+And install the service:
+ > C:\"Program Files"\licd\licd --install
+Possible error messages:
+ "OpenSCManager failed (5)" <<-- You're not an admin, re-open the Command Prompt as administrator.
+ "CreateService failed (1073)" <<-- Service is already installed/running. See below how to stop and delete
+ the old service if you want to reinstall it.
+ "CreateService failed (1072) <<-- Service is deleted but still running. Stop it from Windows Services.
+
+
+Like with Linux version, you now need to get the MOC-wrapper and Qt5 licheck binaries replaced:
+ - Find your Qt installation's binary path and cd there (still using the admin CMD prompt)
+ (For example, my path is: "C:\Qt\6.3.1\mingw_64\bin)
+ > cd <Qt instalation binary path>
+ > move moc.exe orig_moc.exe <--- Name MUST be orig_moc.exe
+ > mklink moc.exe "C:\Program\files\licd\mocwrapper.exe"
+ - And the same for licheck, if you're using Qt5:
+ > move licheck.exe licheck_bak.exe <---- Name it freely
+ > mklink licheck.exe "C:\Program\files\licd\licheck.exe"
+
+If you use a lot of command line, you may like to add "C:\Program Files\licd\" yo your PATH variable for convenience.
+
+============ Starting/stopping the service:
+
+In Windows start menu search, type:
+ "Services"
+Icon with name "Services" should appear. Open it, and a list of system services should now be seen.
+Scroll down until you see "licd". Click it to activate, and then click "Start the service" near upper left corner of the window.
+From the same place, you also can stop it whenever needed.
+
+============ Uninstall:
+
+From Administrator Command propmt, call the lidc as follows:
+ > C:\"Program Files"\licd\licd --delete
+The licd service disappears from the Windows Services and you now can do re-installation if needed.
+Please note that this does NOT delete the program itself, it's still in its designated folder.
+To completely remove it, just destroy the "c:\Program Files\licd" directory and replace the orig_moc and licheck binaries with the originals.
diff --git a/Licenses/LICENSE.txt b/Licenses/LICENSE.txt
new file mode 100644
index 0000000..b1cb1be
--- /dev/null
+++ b/Licenses/LICENSE.txt
@@ -0,0 +1,704 @@
+This is the GNU General Public License version 3, annotated with The
+Qt Company GPL Exception 1.0:
+
+-------------------------------------------------------------------------
+
+The Qt Company GPL Exception 1.0
+
+Exception 1:
+
+As a special exception you may create a larger work which contains the
+output of this application and distribute that work under terms of your
+choice, so long as the work is not otherwise derived from or based on
+this application and so long as the work does not in itself generate
+output that contains the output from this application in its original
+or modified form.
+
+Exception 2:
+
+As a special exception, you have permission to combine this application
+with Plugins licensed under the terms of your choice, to produce an
+executable, and to copy and distribute the resulting executable under
+the terms of your choice. However, the executable must be accompanied
+by a prominent notice offering all users of the executable the entire
+source code to this application, excluding the source code of the
+independent modules, but including any changes you have made to this
+application, under the terms of this license.
+
+
+-------------------------------------------------------------------------
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/Licenses/LICENSE_thirdParty.txt b/Licenses/LICENSE_thirdParty.txt
new file mode 100644
index 0000000..c7756e3
--- /dev/null
+++ b/Licenses/LICENSE_thirdParty.txt
@@ -0,0 +1,30 @@
+----------------------------------
+hmac_sha256
+
+*Minimal HMAC-SHA256 implementation in C / C++*
+----------------------------------
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <https://unlicense.org>
diff --git a/README.md b/README.md
index c00bbd7..704015f 100644
--- a/README.md
+++ b/README.md
@@ -1,102 +1,94 @@
// Copyright (C) 2022 The Qt Company Ltd.
//
-Qt Licenser daemon
-
-- Tested in Ubuntu 16.04, Mint 20.3, Macbook Pro M1 (Mac from console only, not as a daemon)
-- This README does not include Windows version, because it's not supported yet
-
-Prerequisites:
- cmake, curl, build-essentials
-
-To build, run the build script: (from project root)
-
- ./build.sh
-
-
----------- Install it as a service: ----------
-
-cd to deploy/ directory (created by build.sh):
- cd deploy
-
-At this point, you might want to edit the licd.ini file, where most important is the License Server address to be able to connect to it. If you do this later, you need to edit /opt/licd.ini as root. See licd.ini in deploy directory.
-
-Run installation script as root:
- sudo ./installer.sh
-
-(will now start automatically after reboot, too)
-
-To get MOC wrapper working, too, please note: Installation script does not know your Qt installation location (Something like /home/user/Qt/6.3.1/gcc_64/libexec/). That's why you need to set MOC wrapper working by doing:
- 1. cd [your Qt framework install dir]
- 2. mv moc orig_moc <--- Note: has to be exactly 'orig_moc'
- 3. ln -s /opt/licd/mocwrapper moc
- 4. Try it by building any Qt-enabled app wit any IDE or from command line
-
-In case youre using Qt5, you need to enable legacy support for its qmake licensing system by replacing licheck binary with the provided one:
- (Still in the Qt installation location):
- 1. cp licheck licheck.bak <--- This is just to back up the original, you can name it freely
- 2. ln -s /opt/licd/licheck licheck
-
-
-Check if the service running:
- sudo systemctl status licd
-
-To stop it:
- sudo systemctl stop licd
-
-to disable it:
- sudo systemctl disable licd
-
-To view logs:
- journalctl -u licd -n 100
- (Displays last 100 lines. If -n is not given, it will show all the logs)
-
-To run manually (easier to see what happens while testing, as logs will print out directly in the console):
- - sudo systemctl stop licd <--- Don't forget to stop all other licd instances as well
- - cd <project root>/deploy
- - OR:
- - cd /opt/licd <-- Settings will always be taken from /opt/licd/licd.ini
- - sudo ./licd <--- 'sudo' because licd needs to have write access to its directory
-
-To stop it (manually):
- killall licd <-- Not that this does not work if running as a system service
-
-To completely uninstall, run 'uninstaller.sh' from deploy directory (as root, of course)
- In addition, you need to remove symlinks from Qt installation dir and restore original binaries there:
- - cd <your Qt installation dir>
- - mv orig_moc moc
- - mv licheck.bak licheck <-- or whatever you named your backup
-
-
----------- Test it: ----------
-
-Start License server on some Windows machine
-
-- If you didn't edit settings after building: Check the ip address of Win box, then copy it to the line stating 'server_addr' in the settings file (licd.ini). This will be user as the default site license server address. After installation, it must be edited (as root) in /opt/licd/licd.ini
-
-Note that user settings file is not there yet. If you want, you can create it now by running MOC from your Qt installation dir:
- - <your Qt installation dir>/moc <--- Use the absolute path here!!!
-MOC saves the settings file in <your home dir>/.local/share/Qt/qtlicenseservice.ini and advises you to review/edit it with any text editor.
-
-After getting those settings edited, you can try to compile any Qt-enabled app, and it should go through. If you did't start MOC "manually" in the previous step thus the settings file is missing, MOC will give you the similar response now, asking you to review and edit the settings. Build again when done with it.
-
-- To test long term licenses, say:
- qtlongterm <add/remove> -u <username> -i <license id> -d <daemon address> [-l <license server address>]
- - And note thet the license server address (-l) is optional
- - For example, adding a longterm reservation:
- qtlongterm add -u sami -i 12345678 -d localhost:60000
- - To release it, use 'remove intead of 'add'
- - To get help:
- qtlongterm --help
-
-- Test MOC and plugin interfaces without actually using MOC or Qt Creator (plugin):
-
-Open telnet (you may need to install it first: sudo apt install telnet)
- telnet localhost 60000 (in linux)
-
-After connecting, issue a command like:
- license -u foobar -a QtCreator -v 6.3 -i 123456
- Where: -u = username, -a = app in use, -v app version and -i Qt license ID
- Optionally, you can also give -l switch followed by license server address, like: -l 10.0.10.234:8080
-
-Reply is then info txt about having/not having a valid license, or "Bad request" for malformed message.
+Qt Licenser daemon for Windows and Linux
+
+Daemon is a gateway between Qt License Server and Qt developer tools (i.e. Qt Creator and Qt Design Studio).
+It also keeps users developing Qt apps without Qt tools under valid license by wrapping the MOC (Meta Object Compiler)
+into new one which requests license like other tools so.
+
+Daemon talks to the server via HTTP, with data moving back and worth in JSON format usin HTTP POST method. Clients request for their licenses by connectiong to daemons's TCP/IP server, using plain text.
+
+For installation/running, see each system's respective INSTALL_xxx.txt files.
+
+---------- The user settings file ---------
+
+The settings file 'qtlicenseservice.ini' is created automatically in user's Qt home folder which usually is in:
+Linux: <your home dir>/.local/share/Qt/qtlicenseservice.ini
+Windows: <your home dir>\AppData\Roaming\Qt\qtlicenseservice.ini
+
+To create it from scratch, run either mocwrapper or qtlicensetool once (qtlicensetool needs some parameter - you can use -S). You'll be informed about the creation and location of the settings file. The defaults most probably are not correct, so edit it to meet your configuration. The most critical settings are:
+ - license_id Your license id, you definitely must edit this
+ - licd_addr Address to the machine where License Service (daemon) is running. In many cases, localhost is correct.
+ - licd_port Daemon port - default is 60000. Check from daemon settings file or ask the admin
+
+ # MOC-wrapper/moc
+From now on, moc will take the [default] section in use if there's no installation-specific section available. New section names will be determined by current Qt framework installation path. Thats why its mandatory to call moc with absolute path on the second run - easisest way to do that is to just start building some Qt app, as the build procedure always calls moc with absolute path.
+You'll be informed about the creation of the new section under which the defaults are copied at this point. In case you have multiple instances/versions of the Qt framework, you'll have invividual sections for each of them.
+
+ # qtlicensetool
+qtlicensetool ALWAYS reads its settings from the [default] section, no matter where it's being run from.
+
+
+---------- Setup and Usage ----------
+
+At first, start Qt License Server on some Windows machine
+
+- If you didn't edit daemon settings after building: Check the ip address from Win box where the License Server is running, then copy it to the line stating 'server_addr' in the settings file (licd.ini). This will be user as the default site license server address. After installation, it must be edited:
+ Linux: (as root) in /opt/licd/licd.ini
+ Widows (as admin) in C:\Program Files/licd/licd.ini
+Start the daemon, as described in respective Linux/Windows INSTALL file.
+
+- You also can 'manually' start licd in no-daemon mode (as normal CLI app):
+ - First make sure daemon is not running
+ - from the command line, cd to the directory where daemon is installed, then give a command:
+ > ./licd --nodaemon (Linux/Mac)
+ > licd.exe --nodaemon (Windows)
+ - You now can see immediately what happens in there. Stop like any other app with Ctrl-C
+ - Note that where ever you start licd, it will always read settings from installation folder.
+ # MOC-wrapper
+ If the setup is made correct (moc binary changed to the link pointing to mocwrapper), MOC license checks should happen in backround without any user actions, each time a build is being done.
+
+ You can ask mocwrapper version with:
+ > ./mocwrapper --version (mocwrapper.exe in Windows)
+
+# qtlicensetool
+ Old 'qtlongterm' has now been replaced bu a new, more generic tool to handle more Qt licensing-related checks and actions. I'ts still a CLI tool, and has a format:
+ qtlicensetool <Action> [params]
+ Where 'Action' is:
+ -h or --help : Prints out the tool's help text
+ -v or --version : Prints out qtlicensetool version
+ -S or --serverversion : Prints out License Server version
+ -D or --daemonversion : Prints out the License Service (daemon) version
+ -L or --longterm : Longterm reservation (add or remove)
+ For longterm usage ('-L' or '--longterm'), you must tell which operation to do:
+ add|remove <--- Either one needs to be there
+ Optionat parameters which override [default| section settings:
+ -d = Full license daemon address and port separated by ':'
+ -u = Your Qt license username
+ -i = Your Qt license ID number (must be an int)
+ -l = License server address and port separated by ':'
+ Example:
+ > qtlicensetool --longterm add : Make a long-term license reservation
+ > qtlicensetool -L add -i 462412 : Same as above, but using different license ID
+ > qtlicensetool --daemonversion : Prints out a daemon version number
+
+# To test MOC and plugin interfaces without actually using MOC or Qt Creator (plugin):
+ Use any TCP/IP-enabled app to connect to localhost's port 60000 (or whichever is stated in licd.ini). For example, with telnet:
+ telnet localhost 60000
+
+ After connecting, issue a command like:
+ license -u foobar -a QtCreator -v 6.3 -i 123456
+ Where: -u = username, -a = app in use, -v app version and -i Qt license ID
+ Optionally, you can also give -l switch followed by license server address, like: -l 10.0.10.234:8080
+
+ Reply is then info txt about having/not having a valid license, or "Bad request" for malformed message.
+
+---------- Version info ----------
+
+From each component included, you can ask their version using --version switch as follows:
+ [app name] --version <--- [app name].exe in Windows, of course
+ - where [app name] can be one of: 'licd', 'qtlicensetool', 'moc' (or 'mocwrapper')
+ - Note! By default, 'licd' and 'mocwrapper' are not in $PATH by default, so you must call them with their absolute path.
+ In Windows case, you can add "C:\Program Files\licd\" in environment PATH to ease up calling 'qtlongterm'
+In Linux, the binaries are in /opt/licd after installation, and "C:\Program Files\licd\" in Windows.
diff --git a/build.sh b/build_linux.sh
index 0cb43c4..c02b731 100755
--- a/build.sh
+++ b/build_linux.sh
@@ -1,8 +1,10 @@
-#!/bin/bash
-#
+#!/usr/bin/env bash
# Copyright (C) 2022 The Qt Company Ltd.
#
-#set -x
+# SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+#
+
+
name=licd
deploy_dir=deploy
INSTALL=false
@@ -49,25 +51,21 @@ mkdir -p build
if [ $? != 0 ]; then
exit_fail "Failed to create build dir"
fi
-
cd build
-# Clean
-#rm -rf *
-make clean
-
# build
cmake ..
if [ $? != 0 ]; then
exit_fail "Cmake failed"
fi
+make clean
make
if [ $? != 0 ]; then
exit_fail "Build failed"
fi
-chmod +x ${name} qtlongterm/qtlongterm mocwrapper/mocwrapper
+chmod +x ${name} licheck qtlicensetool/qtlicensetool mocwrapper/mocwrapper
cd ..
# Copy files for deployment dir (first create it)
mkdir -p ${deploy_dir}
@@ -77,7 +75,7 @@ fi
cp build/${name} ${deploy_dir}/
cp build/licheck ${deploy_dir}/
-cp build/qtlongterm/qtlongterm ${deploy_dir}/
+cp build/qtlicensetool/qtlicensetool ${deploy_dir}/
cp build/mocwrapper/mocwrapper ${deploy_dir}/
cp ${name}.ini ${deploy_dir}/
cp linux_service_scripts/${name}.service ${deploy_dir}/
diff --git a/build_windows.bat b/build_windows.bat
new file mode 100644
index 0000000..56abcc7
--- /dev/null
+++ b/build_windows.bat
@@ -0,0 +1,22 @@
+:: Copyright (C) 2022 The Qt Company Ltd.
+::
+:: SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+::
+
+@echo off
+
+mkdir build
+mkdir deploy
+
+copy licd.ini deploy\
+
+cd build
+cmake .. -G "Visual Studio 17 2022"
+cmake --build .
+
+copy Debug\licd.exe ..\deploy\
+copy Debug\licheck.exe ..\deploy\
+copy mocwrapper\Debug\mocwrapper.exe ..\deploy\
+copy qtlicensetool\Debug\qtlicensetool.exe ..\deploy\
+
+cd ..
diff --git a/dummy_licheck.cpp b/dummy_licheck.cpp
index c3ca499..e38c627 100644
--- a/dummy_licheck.cpp
+++ b/dummy_licheck.cpp
@@ -1,9 +1,10 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-// Dummy replacement for legacy licheck to have Qt5 qmake satisfied wit return value of '0'
-
-#include <cstdlib>
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+// Dummy replacement for legacy licheck to have
+// Qt5 qmake satisfied with return value of '0'
int main(int argc, char *argv[]) {
- exit(EXIT_SUCCESS);
+ return 0;
}
diff --git a/httpclient.cpp b/httpclient.cpp
index 40875fe..83a0914 100644
--- a/httpclient.cpp
+++ b/httpclient.cpp
@@ -1,97 +1,131 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#include "httpclient.h"
size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
- printf("Reading data\n");
- ((std::string *)userp)->append((char *)contents, size * nmemb);
+ std::cout << "Reading data\n";
+ ((std::string *)userp)->append(contents, size * nmemb);
return size * nmemb;
}
-HttpClient::HttpClient(std::string serverURL, std::string requestAccessPoint, std::string longtermAccessPoint) :
- m_serverUrl(serverURL),
+HttpClient::HttpClient( const std::string &serverUrl,
+ const std::string &requestAccessPoint,
+ const std::string &longtermAccessPoint,
+ const std::string &versionAccessPoint) :
+ m_serverUrl(serverUrl),
m_requestAccessPoint(requestAccessPoint),
- m_longtermAccessPoint(longtermAccessPoint)
+ m_longtermAccessPoint(longtermAccessPoint),
+ m_versionAccessPoint(versionAccessPoint)
{
+ m_userAgent += DAEMON_VERSION;
}
-int HttpClient::sendRequest(std::string &reply, const std::string &payload, const std::string &server, const std::string &authKey) {
+int HttpClient::sendRequest(std::string &reply, const std::string &payload,
+ const std::string &server, const std::string &authKey)
+{
+ HttpRequest request;
+ m_lastError = "No errors";
- CURL *curl;
- CURLcode res;
+ /* specify URL to POST */
+ request.url = server;
+ if (server.empty()) {
+ // If server URL is not given as param, we use the default
+ request.url = m_serverUrl;
+ }
+ if (!authKey.empty()) {
+ // normal request
+ request.url += m_requestAccessPoint;
+ } else {
+ if (payload.empty()) {
+ // version query
+ request.url += m_versionAccessPoint;
+ } else {
+ // long-term request
+ request.url += m_longtermAccessPoint;
+ }
+ }
+ request.authKey = authKey;
+ request.payload = payload;
- std::string readBuffer;
- curl_global_init(CURL_GLOBAL_ALL);
+ if (!request.authKey.empty()) {
+ // Set authorization only if applicable
+ std::string auth = "Authorization: " + request.authKey;
+ request.headers = curl_slist_append(request.headers, auth.c_str());
+ }
+ std::string agent = "User-Agent: " + m_userAgent;
+ request.headers = curl_slist_append(request.headers, agent.c_str());
+ request.headers = curl_slist_append(request.headers, "Accept: */*");
+ request.headers = curl_slist_append(request.headers, "Content-Type: application/json");
+ request.headers = curl_slist_append(request.headers, "charset: utf-8");
- /* init the curl session */
- curl = curl_easy_init();
+ std::cout << "HTTPClient() -- server URL " << request.url << std::endl;
- /* specify URL to POST */
- std::string Url = server;
- if (Url == "") {
- // If server Url is not given as param, we use the default
- Url = m_serverUrl;
- }
+ int retVal = 0;
- if (authKey != "n/a") {
- Url += m_requestAccessPoint;
- //printf("HTTPClient() -- server Url \"%s\"\n", Url.c_str());
- curl_easy_setopt(curl, CURLOPT_URL, Url.c_str());
+ /* init the curl session */
+ curl_global_init(CURL_GLOBAL_ALL);
+ CURL *curl = curl_easy_init();
+ try {
+ if (doRequest(curl, request) != 0) {
+ m_lastError += "Server not reachable ";
+ retVal = 1;
+ }
+ } catch(...) {
+ m_lastError = "Connection failed";
+ retVal = 1;
}
- else {
- Url += m_longtermAccessPoint;
- printf("HTTPClient() -- server Url %s\n", Url.c_str());
- curl_easy_setopt(curl, CURLOPT_URL, Url.c_str());
+ if (retVal == 0) {
+ std::cout << request.reply.length() << " bytes retrieved from license server:\n";
+ std::cout << request.reply << std::endl;
+ } else {
+ std::cout << m_lastError << std::endl;
}
+ /* cleanup curl stuff */
+ curl_easy_cleanup(curl);
+ curl_global_cleanup();
+ curl_slist_free_all(request.headers);
+ reply = request.reply;
+ return retVal;
+}
+
+int HttpClient::doRequest(CURL *curl, HttpRequest &request)
+{
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
+ std::string readBuffer;
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
- struct curl_slist *headers = NULL;
- std::string auth = "Authorization: " + authKey;
- std::string agent = "User-Agent: " + m_userAgent;
- if (authKey != "n/a") {
- // Do not set authorization if not applicable
- headers = curl_slist_append(headers, auth.c_str());
+ // Set the URL
+ curl_easy_setopt(curl, CURLOPT_URL, request.url.c_str());
+ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, request.headers);
+ if (!request.payload.empty()) {
+ curl_easy_setopt(curl, CURLOPT_POST, 1);
+ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.payload.c_str());
+ }
+ else {
+ curl_easy_setopt(curl, CURLOPT_HTTPGET, 1);
}
- headers = curl_slist_append(headers, agent.c_str());
- headers = curl_slist_append(headers, "Accept: */*");
- headers = curl_slist_append(headers, "Content-Type: application/json"); // application/x-www-form-urlencoded");
- headers = curl_slist_append(headers, "charset: utf-8");
-
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
- curl_easy_setopt(curl, CURLOPT_POST, 1);
- curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, SERVER_CONN_TIMEOUT);
/* get it! */
+ CURLcode res;
res = curl_easy_perform(curl);
/* check for errors */
if (res != CURLE_OK) {
- printf("HTTP transfer failed, URL: %s\nReason: %s\n", Url.c_str(), curl_easy_strerror(res));
- m_lastError = " Server not responding: " + Url;
- return -1;
+ std::cout << "HTTP transfer failed, URL: " << request.url << std::endl;
+ m_lastError = curl_easy_strerror(res);
+ return 1;
}
- else {
- reply = readBuffer;
- }
-
- /* cleanup curl stuff */
- curl_easy_cleanup(curl);
-
- /* we are done with libcurl, so clean it up */
- curl_global_cleanup();
-
- printf("%zu bytes retrieved from license server:\n", readBuffer.length());
- printf("%s\n", readBuffer.c_str());
-
+ request.reply = readBuffer;
return 0;
}
diff --git a/include/commonsetup.h b/include/commonsetup.h
index eaf9149..08f08e6 100644
--- a/include/commonsetup.h
+++ b/include/commonsetup.h
@@ -1,22 +1,40 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#pragma once
#include <map>
+#include "version.h"
-#define APP_VERSION_MAJOR "0"
-#define APP_VERSION_MINOR "9.7"
-#define APP_VERSION APP_VERSION_MAJOR "." APP_VERSION_MINOR
-#define USER_SETTINGS_FILE "qtlicenseservice.ini"
#define DAEMON_ADDR "localhost"
#define DAEMON_PORT 60000
+#define BLOCK_IF_NO_LICENSE true
+
+#define USER_SETTINGS_FILE "qtlicenseservice.ini"
+#define DEFAULT_USER_SETTINGS_TAG "[default]"
+
+#define SERVER_VERSION_CMD "serverversion"
+#define DAEMON_VERSION_CMD "version"
+#define RESERVATION_QUERY_CMD "reservation"
+#define LICENSE_REQUEST_CMD "license"
+#define LONGTERM_REQUEST_CMD "longterm"
+#define LONGTERM_ADD_OP "add"
+#define LONGTERM_REMOVE_OP "remove"
+
+#define MOCWRAPPER_APP_NAME "moc"
+#define ORIGINAL_MOC_PREFIX "orig_"
+
+#define QTLICENSETOOL_APP_NAME "Qt License Tool"
-#if __linux__
- // TODO write some code in the utils to get these
- #define USER_SETTINGS_DIR ".local/share/Qt/"
-#elif __APPLE__ || __MACH__
- #define USER_SETTINGS_DIR "~/TODO/something/else"
+#if __APPLE__ || __MACH__
+ #define WORKING_DIR "/opt/licd"
+#elif __linux__
+ #define WORKING_DIR "/opt/licd"
#else
- #define USER_SETTINGS_DIR "~/TODO/something/else"// Windows
+ #define WORKING_DIR "C:/Program Files/licd/"
#endif
+#define DAEMON_SETTINGS_FILE WORKING_DIR "/licd.ini"
+#define LICENSE_FILE_BASE WORKING_DIR "/lic_"
+#define SHA256_HASH_SIZE 32
diff --git a/include/httpclient.h b/include/httpclient.h
index 095dfd4..a861ae6 100644
--- a/include/httpclient.h
+++ b/include/httpclient.h
@@ -1,16 +1,29 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
-#ifndef _HTTP_CLIENT_H_
-#define _HTTP_CLIENT_H_
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+#pragma once
+#include <iostream>
#include <sstream>
#include <map>
+#include "version.h"
#define SERVER_CONN_TIMEOUT 10
-
-#if __APPLE__ || __MACH__ || __linux__
+#if _WIN32
+ //#include <windows.h>
+ #include "curl/curl.h"
+ //#pragma comment(lib, "../3rdParty/curl/lib/libcurl.lib")
+ //#pragma comment(lib, "ws2_32.lib")
+ //#pragma comment(lib, "winmm.lib")
+ //pragma comment(lib, "wldap32.lib")
+ //#include <winsock2.h>
+ //#include <ws2tcpip.h>
+ //#include <iphlpapi.h>
+ //#include <ws2def.h>
+ //#include <io.h>
+#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
@@ -18,42 +31,14 @@
#include <unistd.h>
#include <netdb.h>
#include <curl/curl.h>
-#else
- #include <windows.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <iphlpapi.h>
- //#include <ws2def.h>
- #pragma comment(lib, "Ws2_32.lib")
- #include <io.h>
- #include "../3rdParty/curl/curl.h"
- //#define close closesocket
#endif
-
-
-/******
- Enums
-*/
-enum class httpMethod {
- GET,
- POST
-};
-
-enum class contentType {
- EDI_X12,
- EDIFACT,
- JAVASCRIPT,
- OCTET_STREAM,
- OGG,
- PDF,
- XHTML_XML,
- X_SHOCKWAVE_FLASH,
- JSON,
- LD_JSON,
- XML,
- ZIP,
- X_WWW_FORM_URLENCODED
+struct HttpRequest {
+ std::string payload;
+ std::string url;
+ std::string authKey;
+ std::string reply;
+ curl_slist *headers = nullptr;
};
/*********************
@@ -63,18 +48,21 @@ enum class contentType {
class HttpClient
{
public:
- explicit HttpClient(std::string serverURL, std::string apiAccessPoint, std::string longtermAccessPoint);
+ explicit HttpClient(const std::string &serverUrl,
+ const std::string &requestAccessPoint,
+ const std::string &longtermAccessPoint,
+ const std::string &versionAccessPoint);
~HttpClient() {}
- int sendRequest(std::string &reply, const std::string &payload, const std::string &server, const std::string &authKey="n/a");
+ int sendRequest(std::string &reply, const std::string &payload,
+ const std::string &server, const std::string &authKey="");
std::string error() { return m_lastError; }
private:
std::string m_serverUrl;
std::string m_requestAccessPoint;
std::string m_longtermAccessPoint;
- std::string m_userAgent = "libcurl - agent / 1.0";
+ std::string m_versionAccessPoint;
+ std::string m_userAgent = "License daemon / ";
std::string m_lastError;
+ int doRequest(CURL *curl, HttpRequest &request);
};
-
-
-#endif // _HTTP_CLIENT_H_
diff --git a/include/jsonhandler.h b/include/jsonhandler.h
index a84854a..1f334cd 100644
--- a/include/jsonhandler.h
+++ b/include/jsonhandler.h
@@ -1,5 +1,9 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#pragma once
#include <algorithm>
#include <utility>
@@ -11,8 +15,6 @@
// Very simple JSON reader/writer, takes a JSON string as input
// Specific to Qt license daemon only, doesn't work with JSONs in general
-
-
class JsonHandler {
const std::vector<std::string> reservation {
@@ -21,7 +23,7 @@ const std::vector<std::string> reservation {
};
public:
- explicit JsonHandler (std::string jsonString);
+ explicit JsonHandler(const std::string &jsonString);
~JsonHandler() { }
std::string get(const std::string &item);
@@ -30,9 +32,9 @@ public:
std::string getStr(const std::string &item);
bool getBool(const std::string &item);
- int add(const std::string &item, const std::string &value);
- int add(const std::string &item, uint64_t value);
- int add(const std::string &item, bool value);
+ void add(const std::string &item, const std::string &value);
+ void add(const std::string &item, uint64_t value);
+ void add(const std::string &item, bool value);
std::string dump(uint8_t indent=0);
diff --git a/include/licdsetup.h b/include/licdsetup.h
new file mode 100644
index 0000000..ec2ed71
--- /dev/null
+++ b/include/licdsetup.h
@@ -0,0 +1,51 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+#include "commonsetup.h"
+#include "utils.h"
+
+#include <iostream>
+#include <string>
+#include <map>
+
+enum settings_file_result {
+ e_settings_ok = 0,
+ e_general_file_error = 1,
+ e_file_not_present = 2,
+ e_no_settings_tag = 3,
+ e_no_defaults = 4,
+ e_file_invalid_content = 5
+};
+
+enum settings_owner_type {
+ e_set_type_daemon = 0,
+ e_set_type_moc = 1,
+ e_set_type_licensetool = 2,
+ e_set_type_other = 3
+};
+
+class LicdSetup
+{
+public:
+ explicit LicdSetup(int type, const std::string &callerBinaryPath = "");
+ ~LicdSetup() {}
+ std::string get(const std::string &item);
+ void set(const std::string &item, const std::string &value);
+ int initSettings();
+
+private:
+ std::string m_filepath;
+ std::string m_tag;
+ std::map<std::string, std::string> m_settings;
+ int m_setType;
+
+ int getUserInfo();
+ int getDaemonInfo();
+ std::string parseSettingTag(const std::string &binPath);
+ int createUserSettingsFile();
+ int appendNewSection(const std::string &content);
+ std::string getTaggedSettingsSkeleton();
+ std::string getQtAppDataLocation();
+ std::string getUserFileSkeleton();
+};
diff --git a/include/licenser.h b/include/licenser.h
index b14d844..fd413fe 100644
--- a/include/licenser.h
+++ b/include/licenser.h
@@ -1,6 +1,7 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#pragma once
#include <iostream>
@@ -11,57 +12,60 @@
#include <vector>
#include <ctime>
#include <cassert>
-#include <unistd.h>
-
+#if _WIN32
+ #define WIN32_LEAN_AND_MEAN
+ // Windows
+ //#include <windows.h>
+#else
+#endif
#include "commonsetup.h"
#include "httpclient.h"
#include "tcpserver.h"
#include "utils.h"
-#include "../hmac_sha256/hmac_sha256.h"
+#include "hmac_sha256.h"
#include "jsonhandler.h"
+#include "licdsetup.h"
-#define WORKING_DIR "/opt/licd"
-#define DAEMON_SETTINGS_FILE WORKING_DIR"/licd.ini"
-#define LICENSE_FILE_BASE WORKING_DIR"/lic"
-#define SHA256_HASH_SIZE 32
-
-enum class RequestReply {
- bad_request = -1,
- license_granted = 0,
- license_rejected = 1,
- bad_connection = 2
+enum RequestReply {
+ e_bad_request = -1,
+ e_license_granted = 0,
+ e_license_rejected = 1,
+ e_bad_connection = 2
};
enum class RequestType {
no_request = 0,
- normal_License_renewal = 1,
+ normal_license_renewal = 1,
long_term_request = 2,
- init_user_settings = 3
+ server_version = 3,
+ daemon_version = 4,
+ reservation_query = 5
};
// Struct to store incoming request info for easier handling
struct RequestInfo {
RequestType type = RequestType::no_request;
- std::string operation = "";
- std::string appName = "";
- std::string appVersion = "";
- std::string userId = "";
- std::string licenseId = "";
- std::string email = "";
- std::string licenseFile = "";
- std::string userHome = "";
- std::string payload = "";
- std::string serverAddr = "";
+ std::string operation;
+ std::string appName;
+ std::string appVersion;
+ std::string userId;
+ std::string licenseId;
+ std::string email;
+ std::string licenseFile;
+ std::string userHome;
+ std::string payload;
+ std::string serverAddr;
};
-class Licenser {
+class Licenser
+{
public:
- explicit Licenser(uint16_t tcpPort=0);
- ~Licenser() {}
+ explicit Licenser(uint16_t tcpPort = 0);
+ ~Licenser();
int listen();
int sendLicensingRequest(std::string &reply, const RequestInfo &request);
int sendLongTermRequest(std::string &reply, const RequestInfo &request);
- void sendResponseToCLient(uint16_t clientId, std::string response);
+ int getListeningPort();
private:
HttpClient *m_http;
@@ -76,26 +80,50 @@ private:
bool isMocRenewalDue(const std::string &licenseFile);
void doHmacHashSha256(const std::string &payload, const std::string &secret, std::string &authKey);
int initDaemonSettings();
+ std::string checkReservations();
+ std::string askServerVersion();
+ std::string getVersion();
+ LicdSetup *settings;
- // Default settings for the daemon. Will be overridden by content of the settings file,
- // see 'qtlicenser.conf'
- std::map<std::string, std::string> settings{
- {"server_addr", "10.0.128.123:8080"},
- {"server_secret", "9llVmlSjW7RW7bcdDeiQ0JyfMRDlWcEQviC8q7BS"},
- {"reservation_access_point", "/api/v2/reservations"},
- {"long-term_access_point", "/api/v2/reservation/long-term"},
- {"moc_renewal_interval", "24"},
- {"license_file_base", LICENSE_FILE_BASE},
- {"hw_id", "c31aa37762ef3bb84e09eeea0bc9bccb6b96a81b2657b1a356ec51709975a5ea"},
- {"tcp_listening_port", "60000"}
- };
-
- std::map<RequestReply, std::string> replyString{
- {RequestReply::bad_request, "ERROR Bad request"},
- {RequestReply::license_granted, "License acquired."},
- {RequestReply::license_rejected, "No valid license acquired"},
- {RequestReply::bad_connection, "No connection to server. Try again later."}
+ std::map<RequestReply, std::string> replyString {
+ {e_bad_request, "ERROR Bad request"},
+ {e_license_granted, "License acquired."},
+ {e_license_rejected, "No valid license acquired"},
+ {e_bad_connection, "No connection to server. Try again later."}
};
};
+
+#ifndef __TIME_IMP
+ #define __TIME_IMP
+ #if _WIN32
+ // MSVC defines this in winsock2.h!?
+/*
+ typedef struct timeval {
+ long tv_sec;
+ long tv_usec;
+ } timeval;
+*/
+ inline int gettimeofday(struct timeval * tp, struct timezone * tzp)
+ {
+ // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
+ // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
+ // until 00:00:00 January 1, 1970
+ static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
+
+ SYSTEMTIME system_time;
+ FILETIME file_time;
+ uint64_t time;
+
+ GetSystemTime( &system_time );
+ SystemTimeToFileTime( &system_time, &file_time );
+ time = ((uint64_t)file_time.dwLowDateTime ) ;
+ time += ((uint64_t)file_time.dwHighDateTime) << 32;
+
+ tp->tv_sec = (long) ((time - EPOCH) / 10000000L);
+ tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
+ return 0;
+ }
+ #endif
+#endif
diff --git a/include/tcpclient.h b/include/tcpclient.h
new file mode 100644
index 0000000..383b913
--- /dev/null
+++ b/include/tcpclient.h
@@ -0,0 +1,72 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#pragma once
+
+#include <iostream>
+#include <string>
+#include <map>
+#define BUFFER_SIZE 1024
+
+#if __APPLE__ || __MACH__ || __linux__
+ #include <sys/types.h>
+ #include <sys/socket.h>
+ #include <netinet/in.h>
+ #include <arpa/inet.h>
+ #include <unistd.h>
+ #include <netdb.h>
+ typedef int type_socket;
+#else
+ #define WIN32_LEAN_AND_MEAN
+ #include <windows.h>
+ #include <winsock2.h>
+ #include <ws2tcpip.h>
+ #include <process.h>
+ // Need to link with Ws2_32.lib
+ #pragma comment (lib, "Ws2_32.lib")
+ typedef size_t ssize_t;
+ typedef SOCKET type_socket;
+#endif
+
+enum TcpReturnValues {
+ e_tcp_success = 0,
+ e_tcp_error_conn = 1,
+ e_tcp_error_send = 2,
+ e_tcp_error_recv = 3,
+ e_tcp_error_hostname = 4,
+ e_tcp_fail_socket = 5
+};
+
+class TcpClient
+{
+public:
+ TcpClient(const std::string &connAddr, uint16_t port);
+ ~TcpClient() { doCloseSocket(); }
+
+ int sendAndReceive(const std::string &message, std::string &reply);
+ std::string errorString(int errCode) {return m_tcpReturnStr[errCode];};
+
+private:
+ type_socket m_socketFD;
+ sockaddr_in m_server;
+ std::map<int, std::string> m_tcpReturnStr = {
+ {e_tcp_success, "TCP: Ok"},
+ {e_tcp_error_conn, "TCP: Error when connecting"},
+ {e_tcp_error_hostname, "TCP: Error finding the hostname"},
+ {e_tcp_error_recv, "TCP: Error receiving data"},
+ {e_tcp_error_send, "TCP: Error sending data"},
+ {e_tcp_fail_socket, "TCP: Fail setting up the socket"}
+ };
+
+ void doCloseSocket()
+ {
+#if __APPLE__ || __MACH__ || __linux__
+ close(m_socketFD);
+#else
+ closesocket(m_socketFD);
+#endif
+ }
+
+};
diff --git a/include/tcpserver.h b/include/tcpserver.h
index 10ef5d3..57f7930 100644
--- a/include/tcpserver.h
+++ b/include/tcpserver.h
@@ -1,5 +1,7 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#pragma once
@@ -20,19 +22,17 @@
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
- #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros
+ #include <sys/time.h>
#include "curl/curl.h"
+ typedef int type_socket;
#else
- #include "win/unistd.h"
+ #define WIN32_LEAN_AND_MEAN
+ #include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
- #include <iphlpapi.h>
- //#include <ws2def.h>
- #pragma comment(lib, "Ws2_32.lib")
- #include <io.h>
- #include "curl/curl.h"
- #include <windows.h>
- //#define close closesocket
+ // Need to link with Ws2_32.lib
+ #pragma comment (lib, "Ws2_32.lib")
+ typedef SOCKET type_socket;
#endif
#define BUFFER_SIZE 1024
@@ -41,17 +41,26 @@ class TcpServer
{
public:
explicit TcpServer(uint16_t serverPort);
- ~TcpServer() {}
+ ~TcpServer();
- int init(uint16_t serverPort);
std::string listenToClients(int &socket);
int sendResponse(int socketIndex, const std::string &message);
private:
- int m_masterSocket;
+ type_socket m_masterSocket;
+ type_socket m_clientSocket[MAX_CLIENTS];
int m_addrlen;
- int m_clientSocket[MAX_CLIENTS];
char m_buffer[BUFFER_SIZE]; // data buffer
fd_set m_readfds; // set of socket descriptors
struct sockaddr_in m_address;
+
+ void doCloseSocket(type_socket &socketFD)
+ {
+#if __APPLE__ || __MACH__ || __linux__
+ close(socketFD);
+#else
+ closesocket(socketFD);
+#endif
+}
+
};
diff --git a/include/utils.h b/include/utils.h
index 60bee08..c541741 100644
--- a/include/utils.h
+++ b/include/utils.h
@@ -1,6 +1,7 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#pragma once
#include <sys/stat.h>
@@ -10,253 +11,61 @@
#include <sstream>
#include <vector>
#include <algorithm>
-#if __linux__
- // TODO write some code in the utils to get these
- #include <unistd.h>
- #define USER_SETTINGS_DIR ".local/share/Qt/"
- #include <pwd.h>
- #include <grp.h>
- #define DIR_SEPARATOR '/'
-#elif __APPLE__ || __MACH__
+#if _WIN32
+ // Windows
+ #define WIN32_LEAN_AND_MEAN
+ #include <windows.h>
+ #include <stdint.h> // portable: uint64_t MSVC: __int64
+ #include <io.h>
+ #include "../3rdparty/dirent/dirent.h"
+ #define USER_SETTINGS_DIR "AppData\\Roaming\\Qt"// Windows
+ #define DIR_SEPARATOR '\\'
+ #define SYSTEM_ROOT "C:"
+#else
+ // Linux or Mac
#include <unistd.h>
- #define USER_SETTINGS_DIR "~/TODO/something/else"
+ #include <dirent.h>
#include <pwd.h>
#include <grp.h>
#define DIR_SEPARATOR '/'
-#else
- // Windows
- #define USER_SETTINGS_DIR "~/TODO/something/else"// Windows
- #include <windows.h>
- #define DIR_SEPARATOR '\\'
+ #define SYSTEM_ROOT "/"
+#endif
+#if __APPLE__ || __MACH__
+ #define USER_SETTINGS_DIR "/something/else" // not supported yet
+#elif __linux__
+ #define USER_SETTINGS_DIR ".local/share/Qt/"
#endif
-
namespace utils {
-
-static inline void trimLeft(std::string &s);
-static inline void trimRight(std::string &s);
-static std::string trimStr(const std::string &s);
-static std::vector<std::string> splitStr(const std::string &str, const char delimiter=' ');
-static std::string strToLower(const std::string &str);
-static std::string strToUpper(const std::string &str);
-static std::string getUserHomeDir();
-static int writeToFile(const std::string &filepath, const std::string &data, bool append=false);
-static int createDir(const std::string &filepath, uint16_t user=0, uint16_t group=0);
-static int readFile(std::string &str, const std::string &filepath);
-inline bool fileExists (const std::string& name);
-static std::string getFileOwnerName(const std::string &filename);
-static int getFileOwner(const std::string &filename, uint16_t &owner, uint16_t &group);
-static int strToInt(const std::string &str);
-template <typename T> T swapEndian(T val);
-static std::string getOsName();
-
/*
* String tools
*/
-
-// Trim whitespaces from start of a string
-static inline void trimLeft(std::string &s)
-{
- s.erase(s.begin(), std::find_if (s.begin(), s.end(), [](unsigned char ch)
- { return !std::isspace(ch); }));
-}
-
-// Trim whitespaces from end of a string
-static inline void trimRight(std::string &s)
-{
- s.erase(std::find_if (s.rbegin(), s.rend(), [](unsigned char ch)
- { return !std::isspace(ch); })
- .base(),
- s.end());
-}
-
-// Trim whitespaces from both ends of a string
-static std::string trimStr(const std::string &s) {
- std::string trimmed = s;
- trimLeft(trimmed);
- trimRight(trimmed);
-
- return trimmed;
-}
-
-// Split a string by a char (Defaults to a space)
-static std::vector<std::string> splitStr(const std::string &str, const char delimiter) {
- std::vector<std::string> strings;
- std::istringstream ss(str);
- std::string string;
- while (getline(ss, string, delimiter)) {
- string = trimStr(string);
- strings.push_back(string);
- }
- return strings;
-}
-
-// Convert string to lower case
-static std::string strToLower(const std::string &str) {
- std::locale loc;
- std::stringstream ss;
- for (auto c : str)
- ss << std::tolower(c, loc);
- return ss.str();
-}
-
-// Convert string to upper case
-static std::string strToUpper(const std::string &str) {
- std::locale loc;
- std::stringstream ss;
- for (auto c : str)
- ss << std::toupper(c, loc);
-
- return ss.str();
-}
-
+void trimLeft(std::string &s);
+void trimRight(std::string &s);
+std::string trimStr(const std::string &s);
+std::vector<std::string> splitStr(const std::string &str, const char delimiter=' ');
+std::string strToLower(const std::string &str);
+std::string strToUpper(const std::string &str);
+int strToInt(const std::string &str);
/*
* Filesystem tools
*/
-
-static std::string getUserHomeDir() {
- // Try to find current user's home:
- std::string homedir;
-#if __linux__ || __APPLE__ || __MACH__
- // Linux and Mac
- homedir = getenv("HOME");
- if (homedir.length() == 0) {
- homedir = getpwuid(getuid())->pw_dir;
- }
-#else
- homedir = getenv("HOMEPATH");
-#endif
- return homedir;
-}
-
-// Write data to the file
-static int writeToFile(const std::string &filepath, const std::string &data, bool append) {
- std::string path = "";
- std::ofstream file;
- // can't enable exception now because of gcc bug that raises ios_base::failure with useless message
- // file.exceptions(file.exceptions() | std::ios::failbit);
- if (append) {
- file.open(filepath, std::ios::out | std::ios::app);
- }
- else {
- file.open(filepath, std::ios::out);
- }
-
- if (file.fail()) {
- return -1;
- }
- file << data << std::endl;
- file.close();
- return 0;
-}
-
-static int createDir(const std::string &filepath, uint16_t user, uint16_t group) {
- const char delimiter = '/'; // TODO:: for Linux, windows have '\'
- std::vector<std::string> pathVector = utils::splitStr(filepath, delimiter);
- std::string path = "";
- for (std::string dir : pathVector) {
- path += delimiter; // Again, this is for Linux, windows must have "C:"
- path += dir;
- if (!utils::fileExists(path)) {
-#if __linux__ || __APPLE__ || __MACH__
- if (mkdir(path.c_str(), 0777) != 0) {
- return -1;
- }
- chown(path.c_str(), user, group);
-#else
- printf("WARNING: Unimplemented: createDir()\n");
-#endif
- }
- }
- return 0;
-}
-
-static int readFile(std::string &str, const std::string &filepath) {
- std::ifstream file;
- std::stringstream ss;
- try {
- file.open(filepath, std::ios::in);
- if (file.is_open())
- {
- std::string line;
- while (getline(file, line))
- {
- ss << line;
- }
- file.close();
- }
- else {
- return -1;
- }
- }
- catch (...) {
- return -1;
- }
- str = ss.str();
- return 0;
-}
-
-inline bool fileExists (const std::string& name) {
-#if __linux__ || __APPLE__ || __MACH__
- struct stat buffer;
- return (stat (name.c_str(), &buffer) == 0);
-#else
- printf("WARNING! Uniplemented: Win version of fileExiss()\n");
- return true;
-#endif
-}
-
-
-static std::string getFileOwnerName(const std::string &filename) {
- std::string retVal;
-#if __linux__ || __APPLE__ || __MACH__
- struct stat info;
- stat(filename.c_str(), &info); // Error check omitted
- struct passwd *pw = getpwuid(info.st_uid);
- //struct group *gr = getgrgid(info.st_gid);
- if (pw != 0) retVal = pw->pw_name; // contains the user name
- //if (gr != 0) group = gr->gr_name; // contains the group name
-
-#else
- printf("WARNING! Uniplemented: Win version of getFileOwnerName()\n");
- retVal = "NULL";
-#endif
- return retVal;
-}
-
-static int getFileOwner(const std::string &filename, uint16_t &owner, uint16_t &group) {
-#if __linux__ || __APPLE__ || __MACH__
- struct stat info;
- stat(filename.c_str(), &info); // Error check omitted
- std::string name = getFileOwnerName(filename);
- owner = info.st_uid;
- group = info.st_gid;
-#else
- printf("WARNING! Uniplemented: Win version of getFileOwner()\n");
-#endif
- //printf("Owner of %s is: %s (uid=%u, gid=%u)\n", filename.c_str(), name.c_str(), owner, group);
- return 0;
-}
-
-
+std::string getUserHomeDir();
+int writeToFile(const std::string &filepath, const std::string &data, bool append=false);
+int createDir(const std::string &filepath, uint16_t user=0, uint16_t group=0);
+int readFile(std::string &str, const std::string &filepath);
+bool fileExists(const std::string &name);
+std::string getFileOwnerName(const std::string &filename);
+int getFileOwner(const std::string &filename, uint16_t &owner, uint16_t &group);
+std::vector<std::string> getDirListing(const std::string &directory, const std::string &filter = "");
/*
-* Miscellaneous tools
+* Other
*/
-// String to int: Because stoi() causes crash upon failing
-static int strToInt(const std::string &str) {
- int retVal = 0;
- try {
- retVal = stoi(str);
- }
- catch (...) {
- printf("ERROR: Unable to convert %s to an int\n", str.c_str());
- }
- return retVal;
-}
-
+std::string getOsName();
// Swap endian of any data
-template <typename T> T swapEndian(T val) {
+template <typename T> T swapEndian(T val)
+{
T retVal;
char *pVal = (char*) &val;
char *pRetVal = (char*)&retVal;
@@ -266,34 +75,9 @@ template <typename T> T swapEndian(T val) {
}
return retVal;
}
-
-static std::string getOsName() {
- #if _WIN64 || _WIN32
- return "Windows";
- #elif __APPLE__ || __MACH__
- return "macOS";
- #elif __linux__
- return "Linux";
- #elif __FreeBSD__
- return "FreeBSD";
- #elif __unix || __unix__
- return "Unix";
- #else
- return "Unknown OS";
-#endif
-}
-
/*
-* App-specific utils here (not generic)
+* App-specific utils
*/
-static std::string getQtAppDataLocation() {
- std::string retVal = getUserHomeDir();
- retVal += DIR_SEPARATOR;
- retVal += USER_SETTINGS_DIR;
- retVal += DIR_SEPARATOR;
- return retVal;
-}
-
} // namespace utils
diff --git a/include/version.h b/include/version.h
new file mode 100644
index 0000000..954b2ad
--- /dev/null
+++ b/include/version.h
@@ -0,0 +1,22 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#pragma once
+
+#define DAEMON_VERSION_MAJOR "2"
+#define DAEMON_VERSION_MINOR "0.1"
+#define DAEMON_VERSION DAEMON_VERSION_MAJOR "." DAEMON_VERSION_MINOR
+#define LICD_SERVICE_DESCRIPTION "Qt Licensing service"
+#define COPYRIGHT_TEXT "Copyright (C) 2022 The Qt Company Ltd"
+
+// Let the client versions be the same at this point:
+#define QTLICENSETOOL_VERSION_MAJOR DAEMON_VERSION_MAJOR
+#define QTLICENSETOOL_VERSION_MINOR DAEMON_VERSION_MINOR
+#define QTLICENSETOOL_VERSION QTLICENSETOOL_VERSION_MAJOR "." QTLICENSETOOL_VERSION_MINOR
+
+#define MOCWRAPPER_VERSION_MAJOR DAEMON_VERSION_MAJOR
+#define MOCWRAPPER_VERSION_MINOR DAEMON_VERSION_MINOR
+#define MOCWRAPPER_VERSION MOCWRAPPER_VERSION_MAJOR "." MOCWRAPPER_VERSION_MINOR
+
diff --git a/jsonhandler.cpp b/jsonhandler.cpp
index a5e2182..52185de 100644
--- a/jsonhandler.cpp
+++ b/jsonhandler.cpp
@@ -1,23 +1,26 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#include "jsonhandler.h"
-JsonHandler::JsonHandler (std::string jsonString) {
+JsonHandler::JsonHandler(const std::string &jsonString)
+{
if (preParse(jsonString) != 0) {
- printf("Error reading JSON:\n %s", jsonString.c_str());
+ std::cout << "Error reading JSON:\n" << jsonString << std::endl;
}
}
-
-std::string JsonHandler::get(const std::string &item) {
+std::string JsonHandler::get(const std::string &item)
+{
return getStr(item);
}
-
-int JsonHandler::getInt(const std::string &item) {
+int JsonHandler::getInt(const std::string &item)
+{
if (!m_items.count(item)) {
- printf("ERROR no item %s (integer) found in JSON", item.c_str());
+ std::cout << "ERROR no item '" << item << "' (integer) found in JSON\n";
return INT16_MIN;
}
// Is it an integer?
@@ -29,36 +32,41 @@ int JsonHandler::getInt(const std::string &item) {
}
}
-std::string JsonHandler::getStr(const std::string &item) {
- return (std::string)m_items[item];
+
+std::string JsonHandler::getStr(const std::string &item)
+{
if (!m_items.count(item)) {
- printf("ERROR no item %s (string) found in JSON\n", item.c_str());
+ std::cout << "ERROR no item '" << item << "' (string) found in JSON\n";
return("Error in license service");
}
+ return (std::string)m_items[item];
}
-bool JsonHandler::getBool(const std::string &item) {
+
+bool JsonHandler::getBool(const std::string &item)
+{
if (!m_items.count(item)) {
- printf("ERROR no item %s (boolean) found in JSON", item.c_str());
+ std::cout << "ERROR no item '" << item << "' (boolean) found in JSON\n";
}
return (m_items[item] == "true")? true : false;
}
-int JsonHandler::add(const std::string &item, const std::string &value) {
+void JsonHandler::add(const std::string &item, const std::string &value)
+{
m_items[item] = value;
- return 0;
}
-int JsonHandler::add(const std::string &item, uint64_t value) {
+void JsonHandler::add(const std::string &item, uint64_t value)
+{
m_items[item] = std::to_string(value);
- return 0;
}
-int JsonHandler::add(const std::string &item, bool value) {
- m_items[item] = (value)?"true":"false";
- return 0;
+void JsonHandler::add(const std::string &item, bool value)
+{
+ m_items[item] = (value) ? "true" : "false";
}
-std::string JsonHandler::dump(uint8_t indent) {
+std::string JsonHandler::dump(uint8_t indent)
+{
// Stringify a JSON
// NOTE!! Specific to license daemon, NOT GENERIC
std::string ind(indent, ' ');
@@ -69,13 +77,12 @@ std::string JsonHandler::dump(uint8_t indent) {
if (indent > 0) {
res << ind << "\"reservation\": {" << std::endl;
top << std::endl;
+ } else {
+ res << "\"reservation\":{";
}
- else res << "\"reservation\":{";
uint8_t count = 0;
for (auto const &item : m_items) {
- //std::cout << "Current: " << item.first << ": " << item.second << std::endl;
- //if (item.first == "reservation") continue;
count ++;
if (std::find(reservation.begin(), reservation.end(),
item.first) != reservation.end()) {
@@ -83,14 +90,15 @@ std::string JsonHandler::dump(uint8_t indent) {
if (indent > 0) res << " ";
res << "\"" << item.second << "\"";
if (count == itemCount) {
- if (indent > 0) res << std::endl << ind << "}";
- else res << "}" << std::endl;
+ if (indent > 0) {
+ res << std::endl << ind << "}";
+ } else {
+ res << "}" << std::endl;
+ }
continue;
- }
- else res << ",";
+ } else res << ",";
if (indent > 0) res << std::endl;
- }
- else {
+ } else {
if (indent > 0) res << std::setfill(' ') << std::setw(indent);
top << ind << "\"" << item.first << "\":";
if (indent > 0) top << " ";
@@ -104,7 +112,8 @@ std::string JsonHandler::dump(uint8_t indent) {
return top.str();
}
-int JsonHandler::preParse(const std::string &jsonString) {
+int JsonHandler::preParse(const std::string &jsonString)
+{
std::string str = jsonString;
/* First throw away everything we dont need
*/
@@ -125,7 +134,6 @@ int JsonHandler::preParse(const std::string &jsonString) {
item = utils::trimStr(item);
std::string value = utils::trimStr(pair.substr(pair.find(':') + 1, pair.length() - 1));
m_items[item] = value;
- //printf("Item: %s = %s\n", item.c_str(), value.c_str());
}
return 0;
diff --git a/licd.ini b/licd.ini
index bbc714b..e619c4b 100644
--- a/licd.ini
+++ b/licd.ini
@@ -28,6 +28,11 @@ reservation_access_point=/api/v2/reservations
# Type: string
long-term_access_point=/api/v2/reservations/long-term
###################
+# version_query_access_point
+# License server REST access point for version query requests
+# Type: string
+version_query_access_point=/api/v2/ping
+###################
# moc_request_interval
# Duration (in hours) after which MOC license requests will be renewed (request forwarded to the server).
# In the meantime, timestamp stored in the license file will be used
@@ -37,7 +42,7 @@ moc_renewal_interval=24
# license_file
# filename for storing license server reply JSON. Note! Username and license ID will be added to this
# Type: string
-license_file_base=lic
+license_file_base=lic_
# license_file_extension
# filename extension for storing license server reply JSON
# Type: string
@@ -53,6 +58,5 @@ hw_id=c31aa37762ef3bb84e09eeea0bc9bccb6b96a81b2657b1a356ec51709975a5ea
# user_settings_tag
# Tag under which user settings should reside
# Type: string
-user_settings_tag=[QtSiteLicense]
[/QtLicenseDaemon]
diff --git a/licdsetup.cpp b/licdsetup.cpp
new file mode 100644
index 0000000..2594485
--- /dev/null
+++ b/licdsetup.cpp
@@ -0,0 +1,305 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#include "licdsetup.h"
+
+LicdSetup::LicdSetup(int type, const std::string &callerBinaryPath) :
+ m_setType(type)
+{
+ if (m_setType == e_set_type_daemon) {
+ m_filepath = DAEMON_SETTINGS_FILE;
+ initSettings();
+ } else if (m_setType == e_set_type_moc) {
+ m_filepath = getQtAppDataLocation() + USER_SETTINGS_FILE;
+ m_tag = parseSettingTag(callerBinaryPath);
+ } else {
+ m_filepath = getQtAppDataLocation() + USER_SETTINGS_FILE;
+ m_tag = DEFAULT_USER_SETTINGS_TAG;
+ }
+}
+
+
+std::string LicdSetup::get(const std::string &item)
+{
+ try {
+ auto x = m_settings.at(item);
+ }
+ catch (...) {
+ std::cout << "Warning: No settings item '" << item << "' found\n";
+ return "";
+ }
+ return m_settings[item];
+}
+
+void LicdSetup::set(const std::string &item, const std::string &value)
+{
+ //std::cout << "Setting '" << item << "' to '" << value << "'\n";
+ m_settings[item] = value;
+}
+
+int LicdSetup::initSettings()
+{
+ int result = 0;
+ if (m_setType == e_set_type_daemon) {
+ // read daemon info
+ result = getDaemonInfo();
+ } else {
+ // Read user info
+ result = getUserInfo();
+ if (result == e_file_not_present) {
+ // No settings file found: Create it
+ if (createUserSettingsFile() != 0) {
+ std::cout << "WARNING! Not able to create settings file\n";
+ }
+ return e_file_not_present;
+ } else if (result == e_no_settings_tag && m_setType != e_set_type_licensetool) {
+ std::string content = getTaggedSettingsSkeleton();
+ if (appendNewSection(content) != 0) {
+ std::cout << "WARNING! Not able to write into settings file\n";
+ }
+ }
+ }
+ if (result == e_general_file_error) {
+ std::cout << "Error reading file:\n";
+ return e_general_file_error;
+ } else if (result == e_file_invalid_content) {
+ std::cout << "Error somewhere in settings:\n";
+ for (auto& item: m_settings) {
+ std::cout << item.first << ": " << item.second << '\n';
+ }
+ return e_file_invalid_content;
+ }
+ return e_settings_ok;
+}
+
+
+int LicdSetup::getUserInfo()
+{
+ if (!utils::fileExists(m_filepath)) {
+ return e_file_not_present;
+ }
+ std::ifstream file;
+ bool defaultFound = false;
+ bool inDefault = false;
+ bool inTag = false;
+ bool tagFound = false;
+ try
+ {
+ file.open(m_filepath, std::ios::in);
+ if (file.is_open())
+ {
+ std::string line;
+ while (getline(file, line))
+ {
+ line = utils::trimStr(line);
+ // Continue until correct tag is found:
+ if (line.length() < 1) continue; // omit empty lines
+ if (line[0] == '#') continue; // omit comment line
+ if (line[0] == '[' && line[line.length()-1] == ']') {
+ inTag = false;
+ inDefault = false;
+ if (!tagFound && !inTag) {
+ if (line.compare(m_tag) == 0) {
+ tagFound = true;
+ inTag = true;
+ inDefault = false;
+ }
+ }
+ if (!defaultFound && !inDefault && !tagFound) {
+ if (line == DEFAULT_USER_SETTINGS_TAG) {
+ // Pick default settings only if correct tag is not found yet
+ defaultFound = true;
+ inDefault = true;
+ inTag = false;
+ }
+ }
+ continue;
+ }
+ if (inTag || inDefault) {
+ std::string item;
+ std::string value;
+ std::vector<std::string> data = utils::splitStr(line, '=');
+ if (data.size() > 0) {
+ item = data[0];
+ if (data.size() > 1) {
+ value = data[1];
+ } else {
+ value = "";
+ }
+ m_settings[item] = value;
+ }
+ }
+ }
+ file.close();
+ } else {
+ std::cout << "\nERROR not able to open the settings file, check " << m_filepath << std::endl;
+ file.close();
+ return e_general_file_error;
+ }
+ }
+ catch (...)
+ {
+ std::cout << "\nERROR reading the settings file, check " << m_filepath << std::endl;
+ file.close();
+ return e_general_file_error;
+ }
+ if (!tagFound) {
+ if (!defaultFound) {
+ return e_file_invalid_content;
+ }
+ return e_no_settings_tag;
+ }
+ // Everything is in place?
+ if (m_settings["user_id"].length() == 0 || m_settings["license_id"].length() == 0) {
+ return e_file_invalid_content;
+ }
+ std::string addr = m_settings["licd_addr"];
+ uint16_t port = utils::strToInt(m_settings["licd_port"]);
+ if (port == 0) {
+ return e_file_invalid_content;
+ }
+ return e_settings_ok;
+}
+
+int LicdSetup::getDaemonInfo()
+{
+ m_settings["host_os"] = utils::getOsName();
+ std::cout << "Host: " << m_settings["host_os"] << std::endl;
+ std::ifstream file;
+ try
+ {
+ std::cout << "Opening file " << DAEMON_SETTINGS_FILE << std::endl;
+ file.open(DAEMON_SETTINGS_FILE, std::ios::in);
+ if (file.is_open())
+ {
+ std::string line;
+ while (getline(file, line))
+ {
+ line = utils::trimStr(line);
+ if (line.length() > 0) {
+ if (line[0] == '#' || line[0] == '[') continue; // omit these lines
+ std::string item;
+ std::string value;
+ std::vector<std::string> data = utils::splitStr(line, '=');
+ if (data.size() > 0) {
+ item = data[0];
+ if (data.size() > 1) {
+ value = data[1];
+ } else {
+ value = "";
+ }
+ m_settings[item] = value;
+ std::cout << "Setting '" << item << "' to '" << value <<"'\n";
+ }
+ }
+ }
+ } else {
+ std::cout << "ERROR opening the settings file" << std::endl;
+ file.close();
+ return e_general_file_error;
+ }
+ }
+ catch (...)
+ {
+ std::cout << "ERROR opening/reading the settings file" << std::endl;
+ file.close();
+ return e_general_file_error;
+ }
+ file.close();
+ return e_settings_ok;
+}
+
+std::string LicdSetup::parseSettingTag(const std::string &callerBinaryPath)
+{
+ // Qt uses absolute paths, like: (linux example):
+ // "/home/<user>/Qt/6.3.1/gcc_64/./libexec/moc"
+ size_t loc = callerBinaryPath.rfind(DIR_SEPARATOR);
+ loc = callerBinaryPath.rfind(DIR_SEPARATOR, loc-1);
+ std::string tag = "[" + callerBinaryPath.substr(0, loc);
+ while (tag[tag.length()-1] == DIR_SEPARATOR || tag[tag.length()-1] == '.' ) {
+ tag.erase(tag.length() -1);
+ }
+ tag += "]";
+ std::replace(tag.begin(), tag.end(), DIR_SEPARATOR, '_');
+ return tag;
+}
+
+int LicdSetup::createUserSettingsFile()
+{
+ if (!utils::fileExists(m_filepath)) {
+ std::cout << "Settings file does not exist." << std::endl;
+ if (utils::writeToFile(m_filepath, getUserFileSkeleton(), false) != 0) {
+ std::cout << "Failed to create file " << m_filepath << std::endl;
+ return -1;
+ }
+ std::cout << "New settings file created in " << m_filepath.c_str()
+ << "\nCheck and edit the " << DEFAULT_USER_SETTINGS_TAG << " section\n";
+ }
+ return 0;
+}
+
+int LicdSetup::appendNewSection(const std::string &contentStr)
+{
+ // Append new section in the file
+ if (utils::writeToFile(m_filepath, contentStr, true) != 0) {
+ return -1;
+ }
+ std::cout << "Note! Default settings copied under section:\n" << m_tag << std::endl;
+ return 0;
+}
+
+std::string LicdSetup::getUserFileSkeleton()
+{
+ std::stringstream ss;
+ ss << "#" << std::endl;
+ ss << "# User settings for Qt licensing tools" << std::endl;
+ ss << "# Please fill up, and note that at least user_id" << std::endl;
+ ss << "# and license id MUST be set here correctly" << std::endl;
+ ss << "#\n" << "# Required fields:" << std::endl;
+ ss << "# user_id: Your Qt license username" << std::endl;
+ ss << "# license_id: Your Qt license ID" << std::endl;
+ ss << "# licd_addr: URL of the qt license daemon." << std::endl;
+ ss << "# licd_port: TCP/IP port of the qt license daemon" << std::endl;
+ ss << "#\n" << "# Optional fields:" << std::endl;
+ ss << "# user_email: For cloud usage" << std::endl;
+ ss << "# license_server_addr: If your setup differs from system default license server" << std::endl;
+ ss << "# license_server_port: If your setup differs from system default license server" << std::endl;
+ ss << "\n\n# Default settings section (do not remove):" << std::endl;
+ ss << DEFAULT_USER_SETTINGS_TAG << std::endl;
+ ss << "user_id=foobar" << std::endl;
+ ss << "user_email=foobar@foo.bar" << std::endl;
+ ss << "license_id=12345678" << std::endl;
+ ss << "licd_addr=" << DAEMON_ADDR << std::endl;
+ ss << "licd_port=" << DAEMON_PORT << std::endl;
+ ss << "license_server_addr=" << std::endl;
+ ss << "license_server_port=" << std::endl;
+ ss << std::endl;
+ return ss.str();
+}
+
+std::string LicdSetup::getTaggedSettingsSkeleton()
+{
+ std::stringstream ss;
+ ss << std::endl << m_tag << std::endl;
+ ss << "user_id=" << m_settings["user_id"] << std::endl;
+ ss << "user_email=" << m_settings["user_email"] << std::endl;
+ ss << "license_id=" << m_settings["license_id"] << std::endl;
+ ss << "licd_addr=" << m_settings["licd_addr"] << std::endl;
+ ss << "licd_port=" << m_settings["licd_port"] << std::endl;
+ ss << "license_server_addr=" << m_settings["license_server_addr"] << std::endl;
+ ss << "license_server_port=" << m_settings["license_server_port"] << std::endl;
+ ss << std::endl;
+
+ return ss.str();
+}
+
+std::string LicdSetup::getQtAppDataLocation()
+{
+ std::string retVal = utils::getUserHomeDir();
+ retVal += DIR_SEPARATOR;
+ retVal += USER_SETTINGS_DIR;
+ retVal += DIR_SEPARATOR;
+ return retVal;
+}
diff --git a/licenser.cpp b/licenser.cpp
index 864cca5..202effb 100644
--- a/licenser.cpp
+++ b/licenser.cpp
@@ -1,137 +1,159 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#include "licenser.h"
Licenser::Licenser(uint16_t tcpPort)
{
- // Init daemon basic settings
- initDaemonSettings();
+ // Init daemon settings
+ settings = new LicdSetup(e_set_type_daemon);
+
if (tcpPort == 0) {
- tcpPort = stoi(settings["tcp_listening_port"]);
+ tcpPort = utils::strToInt(settings->get("tcp_listening_port"));
}
- m_mocInterval = stoi(settings["moc_renewal_interval"]) * 3600; // 3600 = secs in hour
+ m_mocInterval = utils::strToInt(settings->get("moc_renewal_interval")) * 3600; // 3600 = secs in hour
// Start the HTTP client
- m_http = new HttpClient(settings["server_addr"],
- settings["reservation_access_point"], settings["long-term_access_point"]);
+ m_http = new HttpClient(settings->get("server_addr"),
+ settings->get("reservation_access_point"),
+ settings->get("long-term_access_point"),
+ settings->get("version_query_access_point"));
// Start the TCP/IP m_server
m_server = new TcpServer(tcpPort);
+
+
}
-// Main loop, rolling forever
-int Licenser::listen() {
- while (TRUE) {
- 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 received nothing but empty line, just send an empty line back, only to
- // release client from listening mode, then start over again
- m_server->sendResponse(socket, "\n");
- continue;
- }
- printf("Got an request: '%s'\n", input.c_str());
- RequestInfo request;
- std::string reply = "";
- if (parseIncoming(input, request) == 0) {
- std::string payload = "";
- if (request.type == RequestType::normal_License_renewal) {
- printf("Standard license renewal request\n");
- // See if it's MOC who's calling us (special case)
- if (request.appName == "MOC") {
- // More than 24hrs from last successful request?
- if (!isMocRenewalDue(request.licenseFile)) {
- // No - Just send ok message and no further actions needed
- reply = replyString[RequestReply::license_granted];
- m_server->sendResponse(socket, reply);
- continue;
- }
- }
- if (buildRequestJson(request) == 0) {
- if (sendLicensingRequest(reply, request) != 0) {
- // Bad server connection: Check the existing license file for expiry date
- if (!checkLicenseExpiryDate(request.licenseFile)) {
- // If expiry date is up or no license file found,
- // Send "Bad connection"
- reply = replyString[RequestReply::bad_connection];
- reply += m_http->error();
- }
- else {
- reply = replyString[RequestReply::license_granted];
- }
- }
- else {
- parseAndSaveJsonReply(reply, request);
- }
- }
- else {
- reply = replyString[RequestReply::bad_request];
+Licenser::~Licenser()
+{
+ 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()) {
+ return 0; //continue;
+ }
+ std::cout << "Got an request: " << input << std::endl;
+ RequestInfo request;
+ std::string reply = "";
+ if (parseIncoming(input, request) == 0) {
+ std::string payload = "";
+ if (request.type == RequestType::normal_license_renewal) {
+ std::cout << "Standard license renewal request\n";
+ // See if it's MOC who's calling us (special case)
+ if (request.appName == MOCWRAPPER_APP_NAME) {
+ // More than 24hrs from last successful request?
+ if (!isMocRenewalDue(request.licenseFile)) {
+ // No - Just send ok message and no further actions needed
+ reply = replyString[e_license_granted];
+ m_server->sendResponse(socket, reply);
+ return 0; //continue;
}
}
- else if (request.type == RequestType::long_term_request) {
- printf("Long-term license request\n");
- if (buildRequestJson(request) == 0) {
- if (sendLongTermRequest(reply, request) != 0) {
- reply = replyString[RequestReply::bad_connection];
+ if (buildRequestJson(request) == 0) {
+ if (sendLicensingRequest(reply, request) != 0) {
+ // Bad server connection: Check the existing license file for expiry date
+ if (!checkLicenseExpiryDate(request.licenseFile)) {
+ // If expiry date is up or no license file found,
+ // Send "Bad connection"
+ reply = replyString[e_bad_connection];
reply += m_http->error();
+ } else {
+ reply = replyString[e_license_granted];
}
- else {
- parseAndSaveJsonReply(reply, request);
- }
+ } else {
+ parseAndSaveJsonReply(reply, request);
}
+ } else {
+ reply = replyString[e_bad_request];
}
- }
- else {
- reply = replyString[RequestReply::bad_request];
- if (request.type == RequestType::long_term_request) {
- reply += ": ";
- reply += m_infoString;
+ } else if (request.type == RequestType::long_term_request) {
+ std::cout << "Long-term license request\n";
+ if (buildRequestJson(request) == 0) {
+ if (sendLongTermRequest(reply, request) != 0) {
+ reply = replyString[e_bad_connection];
+ reply += m_http->error();
+ } else {
+ parseAndSaveJsonReply(reply, request);
+ }
}
+ } else if (request.type == RequestType::reservation_query) {
+ reply = checkReservations();
+ } else if (request.type == RequestType::server_version) {
+ reply = askServerVersion();
}
- if (m_infoString.length() > 0) {
- reply += m_infoString;
+ else if (request.type == RequestType::daemon_version) {
+ reply = getVersion();
}
- reply +="\n";
- m_server->sendResponse(socket, reply);
+ } else {
+ reply = replyString[e_bad_request] + '\n';
}
+ reply += m_infoString;
+ reply +="\n";
+ m_server->sendResponse(socket, reply);
+ std::cout << "Replied to socket " << socket << ": " << reply << std::endl;
+ return 0;
}
-int Licenser::parseIncoming(const std::string &incoming, RequestInfo &request) {
+std::string Licenser::getVersion()
+{
+ std::string version = "Qt License Daemon (licd) v";
+ version += DAEMON_VERSION;
+ return version;
+}
+int Licenser::parseIncoming(const std::string &incoming, RequestInfo &request)
+{
// Cycle through input and all given parameters to find essential info for request JSON
// Start from item 1, since item 0 is the command itself
std::vector<std::string> req = utils::splitStr(incoming, '-');
// First find out the command (and operation for longterm case)
std::string cmd = utils::trimStr(req[0]);
- if (cmd == "license") {
- request.type = RequestType::normal_License_renewal;
- }
- else if (cmd.substr(0, 8) == "longterm") {
+ if (cmd == LICENSE_REQUEST_CMD) {
+ request.type = RequestType::normal_license_renewal;
+ } else if (cmd.substr(0, 8) == LONGTERM_REQUEST_CMD) {
request.type = RequestType::long_term_request;
std::string op = utils::trimStr(cmd.substr(8, cmd.length() -1));
- if (op != "add" && op != "remove") {
+ if (op != LONGTERM_ADD_OP && op != LONGTERM_REMOVE_OP) {
m_infoString = "Invalid longterm operation: " + op;
- printf("%s", m_infoString.c_str());
- return -1;
+ std::cout << m_infoString;
+ return e_bad_request;
}
request.operation = op;
- }
- else {
- printf("Invalid command: %s", cmd.c_str());
- return -1;
+ } else if (cmd == SERVER_VERSION_CMD) {
+ request.type = RequestType::server_version;
+ }else if (cmd == DAEMON_VERSION_CMD) {
+ request.type = RequestType::daemon_version;
+ return 0;
+ } else if (cmd == RESERVATION_QUERY_CMD) {
+ request.type = RequestType::reservation_query;
+ return 0;
+ } else {
+ std::cout << "Invalid command: " << cmd << std::endl;
+ return e_bad_request;
}
- // Then cycle through parameters
+ // Then cycle through parameters. Start from [1] because [0] is the command
for (int i = 1; i < req.size(); i++) {
- char arg = req[i][0];
- std::string val = utils::trimStr(req[i].substr(1, req[i].size() - 1));
+ std::string item = req[i];
+ char arg = (char)item[0];
+ std::string val = utils::trimStr(item.substr(1, item.length() - 1));
if (val.length() == 0) {
m_infoString = "No value for argument: -";
m_infoString.push_back(arg);
- printf("%s\n",m_infoString.c_str());
- return -1;
+ std::cout << m_infoString << std::endl;
+ return e_bad_request;
}
if (arg == 'a') request.appName = val;
@@ -142,66 +164,68 @@ int Licenser::parseIncoming(const std::string &incoming, RequestInfo &request) {
else {
m_infoString = "Invalid argument: -";
m_infoString.push_back(arg);
- return -1;
+ return e_bad_request;
}
}
- // Sanity checks. May not be needed after all, if the clients ara made correctly.
+ // Sanity checks. May not be needed after all, if the clients are made correctly.
+ if (request.type == RequestType::server_version) {
+ return 0; // version query has no mandatory parameters, no checks
+ }
bool fail = false;
if (request.userId.empty()) {
- printf("Missing argument: Username (-u)\n");
+ std::cout << "Missing argument: Username (-u)\n";
fail = true;
}
if (request.licenseId.empty()) {
- printf("Missing argument: License ID (-i)\n");
+ std::cout << "Missing argument: License ID (-i)\n";
fail = true;
}
- if (request.type == RequestType::normal_License_renewal) {
+ if (request.type == RequestType::normal_license_renewal) {
if (request.appName.empty()) {
- printf("Missing argument: Application name (-a)\n");
+ std::cout << "Missing argument: Application name (-a)\n";
fail = true;
}
if (request.appVersion.empty()) {
- printf("Missing argument: Application version (-v)\n");
+ std::cout << "Missing argument: Application version (-v)\n";
fail = true;
}
- }
- else if (request.type == RequestType::long_term_request) {
+ } else if (request.type == RequestType::long_term_request) {
if (request.operation.empty()) {
m_infoString = "Missing argument: Longterm operation (add/remove)\n";
- printf("%s", m_infoString.c_str()); // For logging
+ std::cout << m_infoString << std::endl; // For logging
fail = true;
}
}
-
if (fail) {
- return -1;
+ return e_bad_request;
}
// Add user info to the license filename
- std::string file = settings["license_file_base"] + "_";
+ std::string file = settings->get("license_file_base");
file += request.userId;
file += "_";
file += request.licenseId;
- file += settings["license_file_extension"];
+ file += settings->get("license_file_extension");
request.licenseFile = file;
+
return 0;
}
-int Licenser::buildRequestJson(RequestInfo &request) {
+int Licenser::buildRequestJson(RequestInfo &request)
+{
std::stringstream pay;
pay << "{";
pay<< "\"license_number\":" << "\"" << request.licenseId << "\",";
pay << "\"user_id\":" << "\"" << request.userId << "\",";
- if (request.type == RequestType::normal_License_renewal) {
- pay << "\"hw_id\":" << "\"" << settings["hw_id"] << "\",";
+ if (request.type == RequestType::normal_license_renewal) {
+ pay << "\"hw_id\":" << "\"" << settings->get("hw_id") << "\",";
pay << "\"src\":" << "\"" << request.appName << "\",";
- pay << "\"host_os\":" << "\"" << settings["host_os"] << "\",";
+ pay << "\"host_os\":" << "\"" << settings->get("host_os") << "\",";
pay << "\"src_version\":" << "\"" << request.appVersion << "\",";
pay << "\"email\":" << "\"" << request.email << "\"";
- }
- else if (request.type == RequestType::long_term_request) {
+ } else if (request.type == RequestType::long_term_request) {
pay << "\"operation\":" << "\"" << request.operation << "\"";
}
pay << "}";
@@ -209,7 +233,8 @@ int Licenser::buildRequestJson(RequestInfo &request) {
return 0;
}
-int Licenser::parseAndSaveJsonReply(std::string &reply, const RequestInfo &request) {
+int Licenser::parseAndSaveJsonReply(std::string &reply, const RequestInfo &request)
+{
JsonHandler json(reply);
std::stringstream ss;
if (request.type == RequestType::long_term_request) {
@@ -219,17 +244,15 @@ int Licenser::parseAndSaveJsonReply(std::string &reply, const RequestInfo &reque
return 1;
}
// Nothing to add to the server message
- }
- else {
+ } else {
if (json.get("status") == "true") {
- ss << replyString[RequestReply::license_granted];
+ ss << replyString[e_license_granted];
ss << " expiry_date=" << json.get("expiry_date");
ss << " license_id=" << json.get("license_number");
ss << " reservation_id=" << json.get("reservation_id");
reply = ss.str();
- }
- else {
- reply = replyString[RequestReply::license_rejected];
+ } else {
+ reply = replyString[e_license_rejected];
// Do not save the response json, just return
return 1;
}
@@ -244,23 +267,24 @@ int Licenser::parseAndSaveJsonReply(std::string &reply, const RequestInfo &reque
json.add("last_timestamp", timeNow);
int result = utils::writeToFile(request.licenseFile, json.dump(4));
if (result != 0) {
- printf("ERROR saving license file: %s\n", strerror(result));
+ std::cout << "ERROR saving license file: " << strerror(result) << std::endl;
}
return 0;
}
-bool Licenser::checkLicenseExpiryDate(const std::string &licenseFile) {
- printf("Offline - checking validity from license file %s\n", licenseFile.c_str());
+bool Licenser::checkLicenseExpiryDate(const std::string &licenseFile)
+{
+ std::cout << "Offline - checking validity from license file " << licenseFile << std::endl;
// Open the license file
std::string data;
if (utils::readFile(data, licenseFile) != 0) {
- printf("No license file - rejecting license %s\n", licenseFile.c_str());
+ std::cout << "No license file - rejecting license " <<licenseFile << std::endl;
return false;
}
JsonHandler license(data);
// Check license status
if (license.get("status") != "true") {
- printf("License status = false: Rejecting license\n");
+ std::cout << "License status = false: Rejecting license\n";
return false;
}
@@ -278,20 +302,21 @@ bool Licenser::checkLicenseExpiryDate(const std::string &licenseFile) {
// See if the time has expired
if (current.str() > expiryDate) {
// License expired
- printf("License already expired at %s, rejecting\n", expiryDate.c_str());
+ std::cout << "License already expired at " << expiryDate << ", rejecting\n";
return false;
}
- printf("License granted, expires at: %s\n", expiryDate.c_str());
+ std::cout << "License granted, expires at " << expiryDate << std::endl;
return true;
}
-bool Licenser::isMocRenewalDue(const std::string &licenseFile) {
- printf("MOC calling, checking if renewal is needed\n");
+bool Licenser::isMocRenewalDue(const std::string &licenseFile)
+{
+ std::cout << "MOC calling, checking if renewal is needed\n";
// Open the license file
std::string data;
if (utils::readFile(data, licenseFile) != 0) {
// If there is no license file yet, have to request anyway
- printf("No license file present (%s)- requesting license\n", licenseFile.c_str());
+ std::cout << "No license file present (" << licenseFile << ") - requesting license\n";
return true;
}
JsonHandler license(data);
@@ -305,18 +330,19 @@ bool Licenser::isMocRenewalDue(const std::string &licenseFile) {
uint64_t timeNow = tp.tv_sec;
if (timeNow > utils::strToInt(license.get("last_timestamp")) + m_mocInterval) {
// Renewal is due
- printf("Requesting license renewal\n");
+ std::cout << "Requesting license renewal\n";
return true;
}
- printf("Renewal time not due, granting license\n");
+ std::cout << "Renewal time not due, granting license\n";
return false;
}
-int Licenser::sendLicensingRequest(std::string &reply, const RequestInfo &request) {
+int Licenser::sendLicensingRequest(std::string &reply, const RequestInfo &request)
+{
// Generate auth hash
std::string authKey;
- doHmacHashSha256(request.payload, settings["server_secret"], authKey); // 19755982232ff7b6f6d0f3c57ffc1c0e4f03060e7175d478f7b146fb1e000507";
+ doHmacHashSha256(request.payload, settings->get("server_secret"), authKey); // 19755982232ff7b6f6d0f3c57ffc1c0e4f03060e7175d478f7b146fb1e000507";
// Send the request
if (m_http->sendRequest(reply, request.payload, request.serverAddr, authKey) != 0) {
@@ -325,15 +351,16 @@ int Licenser::sendLicensingRequest(std::string &reply, const RequestInfo &reques
return 0;
}
-int Licenser::sendLongTermRequest (std::string &reply, const RequestInfo &request) {
-
+int Licenser::sendLongTermRequest(std::string &reply, const RequestInfo &request)
+{
if (m_http->sendRequest(reply, request.payload, request.serverAddr) != 0) {
return -1;
}
return 0;
}
-void Licenser::doHmacHashSha256(const std::string &payload, const std::string &secret, std::string &authKey) {
+void Licenser::doHmacHashSha256(const std::string &payload, const std::string &secret, std::string &authKey)
+{
std::stringstream ss_result;
ss_result << "apikey ";
@@ -352,56 +379,43 @@ void Licenser::doHmacHashSha256(const std::string &payload, const std::string &
authKey = ss_result.str();
// Print out the result
- printf("Message: %s\n", payload.c_str());
- printf("Key: %s\n", secret.c_str());
- printf("HMAC: %s\n", authKey.c_str());
+ std::cout << "Message: " << payload << std::endl;
+ std::cout << "Key: " << secret << std::endl;
+ std::cout << "HMAC: " << authKey << std::endl;
}
-
-int Licenser::initDaemonSettings()
+std::string Licenser::checkReservations()
{
- settings["host_os"] = utils::getOsName();
- printf("Host: %s\n", settings["host_os"].c_str());
- std::ifstream file;
- try
- {
- file.open(DAEMON_SETTINGS_FILE, std::ios::in);
- if (file.is_open())
- {
- std::string line;
- while (getline(file, line))
- {
- line = utils::trimStr(line);
- if (line.length() > 0) {
- if (line[0] == '#') continue; // omit comment lines
- std::string item;
- std::string value;
- std::vector<std::string> data = utils::splitStr(line, '=');
- if (data.size() > 0) {
- item = data[0];
- if (data.size() > 1) {
- value = data[1];
- }
- else value = "";
- if (settings.find(item) != settings.end()) {
- settings[item] = value;
- printf("Setting '%s' to '%s'\n", item.c_str(), value.c_str());
- }
- }
- }
- }
- file.close();
- }
- else
- {
- printf("\nWARNING: Error opening the settings file, using default settings.\nTo suppress this warning, check '%s'\n", DAEMON_SETTINGS_FILE);
+ // Open all license files
+ std::string dir = WORKING_DIR;
+ std::string filter = settings->get("license_file_base");
+ std::vector<std::string> files = utils::getDirListing(dir, filter);
+ std::stringstream reply;
+ reply << "Current reservations: \n";
+ for (auto file : files) {
+ 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;
}
- catch (...)
- {
- printf("ERROR opening/reading the settings file\n");
- return -1;
- }
+ return reply.str();
+}
- return 0;
+std::string Licenser::askServerVersion()
+{
+ std::string reply;
+ if (m_http->sendRequest(reply, "", "") != 0) {
+ reply = replyString[e_bad_connection];
+ } else if (reply.find("Error") == std::string::npos) {
+ JsonHandler json(reply);
+ reply = "Qt License Server v";
+ reply += json.get("version");
+ }
+ return reply;
}
diff --git a/linux_daemon/linuxdaemon.cpp b/linux_daemon/linuxdaemon.cpp
index c055e96..3f9e565 100644
--- a/linux_daemon/linuxdaemon.cpp
+++ b/linux_daemon/linuxdaemon.cpp
@@ -1,7 +1,30 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+#include <sys/stat.h>
+#include <iostream>
+#include <unistd.h>
+#include "licenser.h"
+#include "version.h"
-#include "linuxdaemon.h"
+int startProcess(uint16_t tcpPort) {
+ // Fire it up
+ Licenser license(tcpPort);
+ std::cout << "listening..\n";
+ uint16_t count = 0;
+ while (1) {
+ count++;
+ try {
+ license.listen();
+ }
+ catch (...) {
+ std::cout << "ERROR: Qt License Daemon failed!!\n";
+ return -1;
+ }
+ }
+
+}
int main(int argc, char *argv[])
{
@@ -11,7 +34,19 @@ int main(int argc, char *argv[])
std::string message = "";
bool all_ok = true;
for (int i = 1; i < argc; i++) {
- if (strcmp( argv[i], "--port" ) == 0) {
+ // If command-line parameter is "--nodaemon", start right away
+ // as normal CLI process (not as daemon)
+ if (strcmp(argv[1], "--nodaemon") == 0) {
+ int res = startProcess(0);
+ return res;
+ }
+ // If command-line parameter is "--version", show the version and exit.
+ if (strcmp(argv[1], "--version") == 0) {
+ std::cout << "Qt License Daemon (licd) v" << DAEMON_VERSION << " "
+ << COPYRIGHT_TEXT << std::endl;
+ return 0;
+ }
+ if (strcmp(argv[i], "--port") == 0) {
if (i + 1 == argc) {
all_ok = false;
printf("No port number given");
@@ -42,7 +77,7 @@ int main(int argc, char *argv[])
printf("Supported options are:\n");
printf(" --port <port number> : Specify TCP/IP server port. If omitted, default is used.\n");
printf(" --help : This help\n\n");
- exit(EXIT_FAILURE);
+ return -1;
}
printf("Starting daemon\n");
@@ -51,11 +86,11 @@ int main(int argc, char *argv[])
pid_t pid, sid;
pid = fork();
if (pid > 0) {
- exit(EXIT_SUCCESS);
+ return 0;
}
else if (pid < 0) {
printf("Daemon process fork failed!\n");
- exit(EXIT_FAILURE);
+ return 1;
}
umask(0);
sid = setsid();
@@ -63,18 +98,8 @@ int main(int argc, char *argv[])
if (sid < 0)
{
printf("Invalid session id for a child process\n");
- exit(EXIT_FAILURE);
+ return 1;
}
-
- // Fire it up
- Licenser *license = new Licenser(tcpPort);
-
- license->listen();
- /* TODO change above something like:
- license->listen();
- where listen() will be kind of event loop
- */
-
- printf("Successfully started Qt License Daemon\n");
- delete license;
+ startProcess(tcpPort);
+ std::cout << "Started\n";
}
diff --git a/linux_daemon/linuxdaemon.h b/linux_daemon/linuxdaemon.h
deleted file mode 100644
index b9d1d8c..0000000
--- a/linux_daemon/linuxdaemon.h
+++ /dev/null
@@ -1,12 +0,0 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
-#pragma once
-
-#include <sys/stat.h>
-#include <iostream>
-#include <unistd.h>
-#include "licenser.h"
-
-
-int main(int argc, char *argv[]);
diff --git a/linux_service_scripts/installer.sh b/linux_service_scripts/installer.sh
index 8a7bef6..f0ba87f 100755
--- a/linux_service_scripts/installer.sh
+++ b/linux_service_scripts/installer.sh
@@ -1,12 +1,11 @@
-#!/bin/bash
-#
+#!/usr/bin/env bash
# Copyright (C) 2022 The Qt Company Ltd.
#
+# SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
name=licd
installdir=/opt/${name}
-
function exit_fail {
echo "ERROR! $1: Aborting installation"
exit 1
diff --git a/linux_service_scripts/uninstaller.sh b/linux_service_scripts/uninstaller.sh
index 7ff8cb8..a1f19e4 100755
--- a/linux_service_scripts/uninstaller.sh
+++ b/linux_service_scripts/uninstaller.sh
@@ -1,7 +1,7 @@
-#!/bin/bash
-#
+#!/usr/bin/env bash
# Copyright (C) 2022 The Qt Company Ltd.
#
+# SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
name=licd
diff --git a/mocwrapper/CMakeLists.txt b/mocwrapper/CMakeLists.txt
index 7494da4..5ce10e8 100644
--- a/mocwrapper/CMakeLists.txt
+++ b/mocwrapper/CMakeLists.txt
@@ -1,20 +1,25 @@
# Copyright (C) 2022 The Qt Company Ltd.
#
-
+# SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+#
cmake_minimum_required(VERSION 3.5)
+project(mocwrapper LANGUAGES C CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-cmake_policy(SET CMP0042 NEW)
+#cmake_policy(SET CMP0042 NEW)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
-# For "CMAKE_INSTALL_<dir>" standard installation directories
-include(GNUInstallDirs)
-
-project(mocwrapper LANGUAGES C CXX)
-
-include_directories ( ./ ../include/ )
-
-add_executable(mocwrapper mocwrapper.cpp)
+include_directories (
+ ./
+ ../include/
+ ../3rdparty/
+)
+
+add_executable(mocwrapper
+ mocwrapper.cpp
+ ../tcpclient.cpp
+ ../utils.cpp
+ ../licdsetup.cpp
+)
diff --git a/mocwrapper/mocwrapper.cpp b/mocwrapper/mocwrapper.cpp
index e7f7a6e..ec80769 100644
--- a/mocwrapper/mocwrapper.cpp
+++ b/mocwrapper/mocwrapper.cpp
@@ -1,43 +1,23 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#include "mocwrapper.h"
-int main (int argc, char *argv[]) {
-
- // Read user info
- std::string settingsFilePath = utils::getQtAppDataLocation();
- std::string settingsTag = parseSettingTag(argv[0]);
- std::cout << "\nChecking Qt license. ";
- int res = getUserInfo(settingsTag);
- if (res == e_general_file_error) {
- exit(EXIT_FAILURE);
- }
- else if (res == e_file_invalid_content) {
- std::cout << "ERROR somewhere in settings:" << std::endl;
- std::cout << " user_id = " << user["user_id"] << std::endl;
- std::cout << " license_id = " << user["license_id"] << std::endl;
- std::cout << " licd_addr = " << user["licd_addr"] << std::endl;
- std::cout << " licd_port = " << user["licd_port"] << std::endl;
- exit(EXIT_FAILURE);
- }
- else if (res == e_file_not_present) {
- // No settings file found: Create it
- if (createUserSettingsFile() != 0) {
- std::cout << "WARNING! Not able to create settings file\n";
- }
- }
- else if (res == e_no_settings_tag) {
- if (updateUserSettingsFile(settingsTag) != 0) {
- std::cout << "WARNING! Not able to write into settings file\n";
+int main(int argc, char *argv[])
+{
+ // First check if version is asked
+ if (argc > 1) {
+ if (std::string(argv[1]) == "--version") {
+ std::cout << "MOC-wrapper v" << MOCWRAPPER_VERSION << " "
+ << COPYRIGHT_TEXT << std::endl;
+ return 0;
}
}
- // Got the settings: Now to get into action (send the request)
- std::string addr = user["licd_addr"];
- uint16_t port = utils::strToInt(user["licd_port"]);
- if (requestLicense(addr, port) != 0) {
- std::cout << "WARNING! No valid license to run " << APP_NAME;
+ if (requestLicense(argv[0]) != 0) {
+ std::cout << "WARNING! No valid license to run " << MOCWRAPPER_APP_NAME;
if (BLOCK_IF_NO_LICENSE) {
std::cout << ": Aborting\n";
exit(EXIT_FAILURE);
@@ -45,17 +25,16 @@ int main (int argc, char *argv[]) {
std::cout << std::endl;
}
// Continue by running MOC...
- std::cout << "Starting " << APP_NAME << std::endl;
if (forward_call(argc, argv) != 0) {
- std::cout << "Failed to start " << APP_NAME;
+ std::cout << "Failed to start " << MOCWRAPPER_APP_NAME << std::endl;
}
}
int forward_call(int argc, char *argv[])
{
- std::string origCmd = utils::strToLower(APP_NAME);
+ std::string origCmd = utils::strToLower(MOCWRAPPER_APP_NAME);
std::string executable = ORIGINAL_MOC_PREFIX + origCmd;
- std::string cmd = std::string(argv[0]) +'\0';
+ std::string cmd = std::string(argv[0]) + '\0';
cmd.replace(cmd.find(origCmd), origCmd.length(), executable);
std::string args = "";
for (int i = 1; i < argc; i++) {
@@ -63,257 +42,45 @@ int forward_call(int argc, char *argv[])
args += argv[i];
args += '\0';
}
- //std::cout << argv[0] << args << std::endl;
cmd += args;
- //int retval = system(cmd.c_str());
+#ifdef _WIN32
+ int retval = (int)_execve(cmd.c_str(), argv, NULL);
+#else
int retval = execve(cmd.c_str(), argv, NULL);
+#endif
if (retval != 0)
- fprintf(stderr, "Calling '%s' failed, errno = %d\n", executable.c_str(), errno);
+ fprintf(stderr, "Calling '%s' failed, errno = %d\nCommand: \n%s\n",
+ MOCWRAPPER_APP_NAME, errno, cmd.c_str());
return retval;
}
-int requestLicense(const std::string &daemonAddr, uint16_t daemonPort) {
- std::stringstream ss;
- ss << "license -u " << user["user_id"] << " -i " << user["license_id"]
- << " -a " << APP_NAME << " -v " << APP_VERSION;
- if (user["license_server_addr"].length() > 0) {
- ss << " -l " << user["license_server_addr"] << ":" << user["license_server_port"];
- }
- std::string msg = ss.str();
-
- struct sockaddr_in server;
-#if __APPLE__ || __MACH__ || __linux__
- const int inetSuccess = inet_aton(daemonAddr.c_str(), &server.sin_addr);
-#else
- const int inetSuccess = inet_pton(AF_INET, daemonAddr.c_str(), &server.sin_addr.s_addr);
-#endif
- if (!inetSuccess) {
- // Try to resolve hostname
- struct hostent *host;
- struct in_addr **addrList;
- if ( (host = gethostbyname( daemonAddr.c_str() ) ) == nullptr){
- std::cout << "Failed to resolve hostname\n";
- return -1;
- }
- addrList = (struct in_addr **) host->h_addr_list;
- server.sin_addr = *addrList[0];
- }
- server.sin_family = AF_INET;
- server.sin_port = htons(daemonPort);
- int sockFD;
- sockFD = (socket(AF_INET , SOCK_STREAM , 0));
- if (sockFD < 0) {
- throw std::runtime_error(strerror(errno));
- }
- // Connect to daemon
- int connectR = connect(sockFD, (struct sockaddr *)&server, sizeof(server));
- if (connectR == -1) {
- close(sockFD);
- std::cout << "Error while connecting socket:\n";
- return -1;
- }
- const size_t bytesSent = send(sockFD, msg.c_str(), msg.length(), 0);
-
- if (bytesSent < 0 ) { // send failed
- std::cout << "ERROR in sending to daemon: " << strerror(errno) << std::endl;
+int requestLicense(const std::string &mocBinPath)
+{
+ LicdSetup user(e_set_type_moc, mocBinPath);
+ if (user.initSettings() == e_file_not_present) {
return -1;
}
-
- std::string reply(BUFFER_SIZE, ' ');
-
- size_t bytes_recv = recv(sockFD, &reply.front(), reply.size(), 0);
- if (bytes_recv == -1) {
- std::cout << "Error while receiving bytes\n";
- return -1;
+ // Read user info
+ std::string addr = user.get("licd_addr");
+ uint16_t port = utils::strToInt(user.get("licd_port"));
+ std::stringstream ss;
+ ss << "license -u " << user.get("user_id") << " -i " << user.get("license_id")
+ << " -a " << MOCWRAPPER_APP_NAME << " -v " << MOCWRAPPER_VERSION;
+ if (user.get("license_server_addr").length() > 0) {
+ ss << " -l " << user.get("license_server_addr") << ":" << user.get("license_server_port");
+ }
+ TcpClient tcp(addr, port);
+ std::string reply;
+ int result = tcp.sendAndReceive(ss.str(), reply);
+ if (result != e_tcp_success) {
+ std::cout << "Failure: " << tcp.errorString(result) << std::endl;
+ return -1; // TCP/IP error
}
-
reply = utils::trimStr(reply);
std::cout << reply << std::endl;
if (reply.substr(0,2) == "No" || reply.substr(0,5) == "ERROR") {
- return -1;
- }
- close(sockFD);
- return 0;
-}
-
-int getUserInfo(const std::string &userSettingsTag) {
- std::string userSettingsFile = utils::getQtAppDataLocation() + USER_SETTINGS_FILE;
- if (!utils::fileExists(userSettingsFile)) {
- std::cout << "No user settings file " << userSettingsFile << " found\n";
- return e_file_not_present;
+ return -1; // No license
}
- std::ifstream file;
- bool defaultFound = false;
- bool inDefault = false;
- bool inTag = false;
- bool tagFound = false;
- try
- {
- file.open(userSettingsFile, std::ios::in);
- if (file.is_open())
- {
- std::string line;
- while (getline(file, line))
- {
- line = utils::trimStr(line);
- // Continue until correct tag is found:
- if (line.length() < 1) continue; // omit empty lines
- if (line[0] == '#') continue; // omit comment line
- if (line[0] == '[' && line[line.length()-1] == ']') {
- inTag = false;
- inDefault = false;
- if (!tagFound && !inTag) {
- if (line.compare(userSettingsTag) == 0) {
- tagFound = true;
- inTag = true;
- inDefault = false;
- }
- }
- if (!defaultFound && !inDefault && !tagFound) {
- if (line == "[default]") {
- // Pick default settings only if correct tag is not found yet
- defaultFound = true;
- inDefault = true;
- inTag = false;
- }
- }
- continue;
- }
- if (inTag || inDefault) {
- std::string item;
- std::string value;
- std::vector<std::string> data = utils::splitStr(line, '=');
- if (data.size() > 0) {
- item = data[0];
- if (data.size() > 1) {
- value = data[1];
- }
- else value = "";
- if (user.find(item) != user.end()) {
- user[item] = value;
- //printf("Setting '%s' to '%s'\n", item.c_str(), value.c_str());
- }
- }
- }
- }
- file.close();
- }
- else
- {
- std::cout << "\nERROR not able to open the settings file, check " << userSettingsFile << std::endl;
- return e_general_file_error;
- }
- }
- catch (...)
- {
- std::cout << "\nERROR reading the settings file, check " << userSettingsFile << std::endl;
- return e_general_file_error;
- }
- if (!tagFound) {
- if (!defaultFound) {
- return e_file_invalid_content;
- }
- std::cout << "Tag: [default]\n";
- return e_no_settings_tag;
- }
- else {
- std::cout << "Tag: " << userSettingsTag << std::endl;
- }
- // Everything is in place?
- if (user["user_id"].length() == 0 || user["license_id"].length() == 0) {
- return e_file_invalid_content;
- }
- std::string addr = user["licd_addr"];
- uint16_t port = utils::strToInt(user["licd_port"]);
- if (port == 0) {
- return e_file_invalid_content;
- }
-
- return 0;
-}
-
-std::string parseSettingTag(const std::string &mocBinPath) {
- // Qt uses absolute paths, like: (linux example):
- // "/home/<user>/Qt/6.3.1/gcc_64/./libexec/moc"
- size_t loc = mocBinPath.rfind(DIR_SEPARATOR);
- loc = mocBinPath.rfind(DIR_SEPARATOR, loc-1);
- std::string tag = "[" + mocBinPath.substr(0, loc);
- while (tag[tag.length()-1] == DIR_SEPARATOR || tag[tag.length()-1] == '.' ) {
- tag.erase(tag.length() -1);
- }
- tag += "]";
- std::replace(tag.begin(), tag.end(), DIR_SEPARATOR, '_');
- return tag;
-}
-
-
-
-int createUserSettingsFile() {
- std::string file = utils::getQtAppDataLocation() + USER_SETTINGS_FILE;
- std::cout << "Checking Qt app settings in: " << file << std::endl;
- if (!utils::fileExists(file)) {
- std::cout << "File does not exist, creating it..." << std::endl;
- if (utils::writeToFile(file, getUserFileSkeleton(), false) != 0) {
- std::cout << "Failed to create file " << file << std::endl;
- return -1;
- }
- std::cout << "Settings file created.\n";
- }
- return 0;
-}
-
-int updateUserSettingsFile(const std::string &settingsTag) {
- std::string file = utils::getQtAppDataLocation() + USER_SETTINGS_FILE;
- // Append new section in the file
- if (utils::writeToFile(file, getTaggedSettingsSkeleton(settingsTag), true) != 0) {
- std::cout << "ERROR! Failed to write in file " << file << std::endl;
- return -1;
- }
- std::cout << "#### Default settings copied under tag: " << settingsTag << std::endl;
- std::cout << "#### Please make sure they're correct in file:\n#### " << file << std::endl;
return 0;
}
-
-static std::string getUserFileSkeleton() {
- std::stringstream ss;
- ss << "#" << std::endl;
- ss << "# User settings for Qt licensing tools" << std::endl;
- ss << "# Please fill up, and note that at least user_id" << std::endl;
- ss << "# and license id MUST be set here correctly" << std::endl;
- ss << "#\n" << "# Required fields:" << std::endl;
- ss << "# user_id: Your Qt license username" << std::endl;
- ss << "# license_id: Your Qt license ID" << std::endl;
- ss << "# licd_addr: URL of the qt license daemon." << std::endl;
- ss << "# licd_port: TCP/IP port of the qt license daemon" << std::endl;
- ss << "#\n" << "# Optional fields:" << std::endl;
- ss << "# user_email: For cloud usage" << std::endl;
- ss << "# license_server_addr: If your setup differs from system default license server" << std::endl;
- ss << "# license_server_port: If your setup differs from system default license server" << std::endl;
- ss << "\n\n# Default settings section (do not remove):" << std::endl;
- ss << "[default]" << std::endl;
- ss << "user_id=foobar" << std::endl;
- ss << "user_email=foobar@foo.bar" << std::endl;
- ss << "license_id=10876096" << std::endl;
- ss << "licd_addr=" << DAEMON_ADDR << std::endl;
- ss << "licd_port=" << DAEMON_PORT << std::endl;
- ss << "# license_server_addr=" << std::endl;
- ss << "# license_server_port=" << std::endl;
- ss << std::endl;
- return ss.str();
-}
-
-static std::string getTaggedSettingsSkeleton(const std::string &tag) {
- std::stringstream ss;
- ss << std::endl << tag << std::endl;
- ss << "user_id=" << user["user_id"] << std::endl;
- ss << "user_email=" << user["user_email"] << std::endl;
- ss << "license_id=" << user["license_id"] << std::endl;
- ss << "licd_addr=" << user["licd_addr"] << std::endl;
- ss << "licd_port=" << user["licd_port"] << std::endl;
- ss << "# license_server_addr=" << user["license_server_addr"] << std::endl;
- ss << "# license_server_port=" << user["license_server_port"] << std::endl;
- ss << std::endl;
-
- return ss.str();
-}
diff --git a/mocwrapper/mocwrapper.h b/mocwrapper/mocwrapper.h
index 9877e58..8b7e363 100644
--- a/mocwrapper/mocwrapper.h
+++ b/mocwrapper/mocwrapper.h
@@ -1,5 +1,7 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#pragma once
@@ -10,57 +12,24 @@
#include <fstream>
#include <map>
#include <cstdlib>
-#if __APPLE__ || __MACH__ || __linux__
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- #include <netdb.h>
-#else
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <iphlpapi.h>
- #include <ws2def.h>
- #pragma comment(lib, "Ws2_32.lib")
- #include <io.h>
- #include <windows.h>
- //#define close closesocket
+#ifdef _WIN32
+ #define WIN32_LEAN_AND_MEAN
+ #include <process.h>
#endif
+#include "tcpclient.h"
#include "utils.h"
#include "commonsetup.h"
+#include "licdsetup.h"
-#define APP_NAME "MOC"
-#define BLOCK_IF_NO_LICENSE true
-#define ORIGINAL_MOC_PREFIX "orig_"
-#define BUFFER_SIZE 1024
-enum settings_file_result {
- e_settings_ok = 0,
- e_general_file_error = 1,
- e_file_not_present = 2,
- e_no_settings_tag = 3,
- e_no_defaults = 4,
- e_file_invalid_content = 5
-};
+#define BUFFER_SIZE 1024
int getUserInfo(const std::string &filepath);
-int requestLicense(const std::string &daemonAddr, uint16_t daemonPort);
+int requestLicense(const std::string &mocBinPath);
int forward_call(int argc, char *argv[]);
std::string parseSettingTag(const std::string &mocBinPath);
int createUserSettingsFile();
int updateUserSettingsFile(const std::string &settingsTag);
static std::string getUserFileSkeleton();
static std::string getTaggedSettingsSkeleton(const std::string &tag);
-
-// Skeleton with defaults for user settings. These MUST be filled in to the user settings file
-std::map<std::string, std::string> user = {
- {"user_id", "foobar"},
- {"user_email", "foo@bar.com"},
- {"license_id", "12345678"},
- {"licd_addr", std::string(DAEMON_ADDR)},
- {"licd_port", std::to_string(DAEMON_PORT)},
- {"license_server_addr", ""},
- {"license_server_port", ""}
-};
diff --git a/qtlicensetool/CMakeLists.txt b/qtlicensetool/CMakeLists.txt
new file mode 100644
index 0000000..8e9fefd
--- /dev/null
+++ b/qtlicensetool/CMakeLists.txt
@@ -0,0 +1,30 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+#
+# SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+#
+cmake_minimum_required(VERSION 3.5)
+project(qtlicensetool LANGUAGES CXX)
+
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+set(CMAKE_CXX_STANDARD 14)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+include_directories (
+ ./
+ ${CMAKE_CURRENT_LIST_DIR}/../include/
+ ${CMAKE_CURRENT_LIST_DIR}/../3drparty/
+)
+
+#if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
+# include_directories (
+# ${CMAKE_CURRENT_LIST_DIR}/../3rdparty/
+# )
+#endif()
+
+add_executable(qtlicensetool
+ qtlicensetool.cpp
+ ../tcpclient.cpp
+ ../utils.cpp
+ ../licdsetup.cpp
+)
diff --git a/qtlicensetool/qtlicensetool.cpp b/qtlicensetool/qtlicensetool.cpp
new file mode 100644
index 0000000..66f07bd
--- /dev/null
+++ b/qtlicensetool/qtlicensetool.cpp
@@ -0,0 +1,206 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#include "qtlicensetool.h"
+
+int main(int argc, char *argv[])
+{
+ // Fetch the settings from .ini file
+ LicdSetup setup(e_set_type_licensetool, "");
+ if (setup.initSettings() == e_file_not_present) {
+ errorAndExit("Not able to find the settings");
+ }
+ if (argc < 2) {
+ errorAndExit("No arguments given");
+ }
+ std::string action = argv[1];
+ // Get rid of commands which don't require further actions
+ if (action == "--version" || action == "-v") {
+ showVersion();
+ return 0;
+ } else if (action == "--help" || action == "-h") {
+ helpAndExit();
+ }
+
+ // Then those requiring connection
+ if (action == "--longterm" || action == "-L") {
+ // Override setup with cmd-line args:
+ overrideSetup(&setup, argc, argv);
+ doLongtermRequest(&setup);
+ } else if (action == "--serverversion" || action == "-S") {
+ askStatus(SERVER_VERSION_CMD, &setup);
+ } else if (action == "--daemonversion" || action == "-D") {
+ askStatus(DAEMON_VERSION_CMD, &setup);
+ } else if (action == "--reservation" || action == "-r") {
+ askStatus(RESERVATION_QUERY_CMD, &setup);
+ } else {
+ errorAndExit("Invalid parameters");
+ }
+}
+
+void showVersion()
+{
+ std::cout << "qtlicensetool v" << QTLICENSETOOL_VERSION
+ << " - CLI tool for Qt Licensing\n";
+ return;
+}
+
+int askStatus(const std::string &statusRequest, LicdSetup *setup)
+{
+ std::string daemonAddr = setup->get("licd_addr");
+ int daemonPort = utils::strToInt(setup->get("licd_port"));
+ if (daemonPort < 0) {
+ errorAndExit("Invalid daemon port - check settings/arguments");
+ }
+
+ // Connect and send/receive the request
+ TcpClient tcp(daemonAddr, daemonPort);
+ std::string reply;
+ int result = tcp.sendAndReceive(statusRequest, reply);
+ if (result != e_tcp_success) {
+ std::cout << tcp.errorString(result) << std::endl;
+ return e_tcp_error_conn;
+ }
+ std::cout << reply << std::endl;
+ return 0;
+}
+
+void overrideSetup(LicdSetup *setup, int argc, char *argv[])
+{
+ // Pick up the cmd-line switches: Start looping args from index 1,
+ // as first one is the command itself
+ bool longterm = false;
+ for (int i = 1; i < argc; i++) {
+ std::string sw = utils::trimStr(argv[i]);
+ std::string val = "";
+ if (sw == "-L" || sw == "--longterm") {
+ longterm = true;
+ continue;
+ }
+ if (longterm) {
+ // Longterm operation (add|remove) has to come right after the -L switch, not later
+ if (sw == LONGTERM_ADD_OP || sw == LONGTERM_REMOVE_OP) {
+ setup->set("operation", sw);
+ longterm = false;
+ continue;
+ }
+ else {
+ errorAndExit("Invalid longterm operation");
+ }
+ }
+
+ // Check if given switch has a value
+ if (sw[0] == '-' && argc > i+1) {
+ val = utils::trimStr(argv[i+1]);
+ if (val[0] == '-') { // do not accept another switch as a value
+ val = "";
+ } else {
+ i++;
+ }
+ }
+ if (val.empty()) {
+ std::string error = "No value for argument " + sw;
+ errorAndExit(error);
+ }
+ // Pick up values
+ if (sw == "-i") {
+ setup->set("license_id", val);
+ } else if (sw == "-u") {
+ setup->set("user_id", val);
+ } else if (sw == "-d") {
+ size_t colPos = val.find(':');
+ if (colPos == std::string::npos) {
+ errorAndExit("Invalid service address: Must be in form <url>:<port>");
+ }
+ setup->set("licd_addr", val.substr(0, colPos));
+ setup->set("licd_port", val.substr(colPos+1));
+ } else if (sw == "-l") {
+ size_t colPos = val.find(':');
+ if (colPos == std::string::npos) {
+ errorAndExit("Invalid license server address: Must be in form <url>:<port>");
+ }
+ setup->set("license_server_addr", val.substr(0, colPos));
+ setup->set("license_server_port", val.substr(colPos + 1));
+
+ } else {
+ std::string error = "Invalid argument:" + sw;
+ errorAndExit(error);
+ }
+ }
+}
+
+int doLongtermRequest(LicdSetup *setup)
+{
+ std::string operation = setup->get("operation"); // utils::trimStr(argv[2]);
+ if (operation != LONGTERM_ADD_OP && operation != LONGTERM_REMOVE_OP) {
+ std::string error = "Invalid operation \"" + operation;
+ error += "\"";
+ errorAndExit(error);
+ }
+ uint16_t daemonPort = utils::strToInt(setup->get("licd_port"));
+ if (daemonPort < 0) {
+ errorAndExit("Invalid daemon port - check settings/arguments");
+ }
+
+ // Ready to build the request
+ std::stringstream request;
+ request << LONGTERM_REQUEST_CMD << " " << setup->get("operation")
+ << " -u " << setup->get("user_id")
+ << " -i " << setup->get("license_id");
+ if (!setup->get("license_server_addr").empty()) {
+ // Add optional license server URL if specified
+ request << " -l " << setup->get("license_server_addr")
+ << ":" << setup->get("license_server_port");
+ }
+
+ // Connect and send/receive the request
+ TcpClient tcp(setup->get("licd_addr"), daemonPort);
+ std::string reply;
+ int result = tcp.sendAndReceive(request.str(), reply);
+ if (result != e_tcp_success) {
+ std::cout << tcp.errorString(result) << std::endl;
+ exit(EXIT_FAILURE);
+ }
+ if (reply.find("No") != std::string::npos
+ || reply.find("ERROR") != std::string::npos
+ || reply.find("expired") != std::string::npos) {
+ errorAndExit(reply);
+ }
+ std::cout << reply << std::endl;
+ exit(EXIT_SUCCESS);
+}
+
+void errorAndExit(const std::string &reason)
+{
+ if (!reason.empty()) {
+ std::cout << "ERROR! " << reason << std::endl;
+ }
+ exit(EXIT_FAILURE);
+}
+
+void helpAndExit()
+{
+ std::stringstream ss;
+ std::cout << "Usage:\n"
+ << " qtlicensetool <Action> [params]\n"
+ << " Where 'Action' is:\n"
+ << " -h or --help : Prints out the tool's help text\n"
+ << " -v or --version : Prints out qtlicensetool version\n"
+ << " -S or --serverversion : Prints out License Server version\n"
+ << " -D or --daemonversion : Prints out the License Service (daemon) version\n"
+ << " -L or --longterm : Longterm reservation (add or remove)\n"
+ << " For longterm usage ('-L' or '--longterm'), you must tell which operation to do:\n"
+ << " add|remove <--- Either one needs to be there\n"
+ << " Optionat parameters which override [default| section settings:\n"
+ << " -d = Full license daemon address and port separated by ':'\n"
+ << " -u = Your Qt license username\n"
+ << " -i = Your Qt license ID number (must be an int)\n"
+ << " -l = License server address and port separated by ':'\n"
+ << " Example:\n"
+ << " > qtlicensetool --longterm add : Make a long-term license reservation\n"
+ << " > qtlicensetool -L add -i 462412 : Same as above, but using different license ID\n"
+ << " > qtlicensetool --daemonversion : Prints out a daemon version number\n";
+ exit(EXIT_SUCCESS);
+}
diff --git a/qtlicensetool/qtlicensetool.h b/qtlicensetool/qtlicensetool.h
new file mode 100644
index 0000000..c92c33c
--- /dev/null
+++ b/qtlicensetool/qtlicensetool.h
@@ -0,0 +1,53 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#pragma once
+
+#include <cstring>
+#include <iostream>
+#include <string>
+#include <sstream>
+#include <fstream>
+#include <map>
+#if __APPLE__ || __MACH__ || __linux__
+ #include <sys/types.h>
+ #include <netdb.h>
+ #include <sys/socket.h>
+ #include <netinet/in.h>
+ #include <arpa/inet.h>
+ #include <unistd.h>
+#else
+ #define WIN32_LEAN_AND_MEAN
+ #include <windows.h>
+ #include <winsock2.h>
+ #include <ws2tcpip.h>
+ // Need to link with Ws2_32.lib
+ #pragma comment (lib, "Ws2_32.lib")
+
+ typedef size_t ssize_t;
+#endif
+
+enum qt_tool_action_type {
+ e_action_tool_version = 1,
+ e_action_server_version = 2,
+ e_action_longterm = 3,
+ e_action_license_query = 4
+};
+
+#include "tcpclient.h"
+#include "utils.h"
+#include "commonsetup.h"
+#include "licdsetup.h"
+
+#define APP_NAME "Qt long-term license CLI"
+#define BUFFER_SIZE 1024
+
+int main(int argc, char *argv[]);
+void showVersion();
+int askStatus(const std::string &statusRequest, LicdSetup *setup);
+int doLongtermRequest(LicdSetup *setup);
+void overrideSetup(LicdSetup *setup, int argc, char *argv[]);
+void errorAndExit(const std::string &reason = "");
+void helpAndExit();
diff --git a/qtlongterm/CMakeLists.txt b/qtlongterm/CMakeLists.txt
deleted file mode 100644
index 9092729..0000000
--- a/qtlongterm/CMakeLists.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright (C) 2022 The Qt Company Ltd.
-#
-
-cmake_minimum_required(VERSION 3.1)
-
-project(qtlongterm LANGUAGES CXX)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-cmake_policy(SET CMP0042 NEW)
-
-set(CMAKE_CXX_STANDARD 14)
-set(CMAKE_CXX_STANDARD_REQUIRED ON)
-
-include_directories(./ ../include)
-
-add_executable(qtlongterm qtlongterm.cpp)
diff --git a/qtlongterm/qtlongterm.cpp b/qtlongterm/qtlongterm.cpp
deleted file mode 100644
index 8bd6a73..0000000
--- a/qtlongterm/qtlongterm.cpp
+++ /dev/null
@@ -1,183 +0,0 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
-#include "qtlongterm.h"
-
-int main(int argc, char *argv[]) {
- if (argc < 2) helpAndExit("Too few arguments");
-
- std::string userId = "";
- std::string licenseId = "";
- std::string daemonAddr = "";
- uint16_t daemonPort = 0;
- std::string serverURL = "";
- std::string operation = utils::trimStr((std::string)argv[1]);
- if (operation == "--help" || operation == "-h") {
- printf("%s\n", helpText().c_str());
- exit(EXIT_SUCCESS);
- }
- if (operation != "add" && operation != "remove") {
- std::string error = "Invalid operation \"" + operation;
- error += "\"";
- helpAndExit(error);
- }
- // TODO check if user wants to use [default] settings
-
- // Pick up the switches
- uint8_t swCount = 0;
- // Start looping for switches from index 2, first two are command itself and the operation
- for (int i = 2; i < argc; i++) {
- std::string sw = utils::trimStr((std::string)argv[i]);
- std::string val = "";
- // Check if given switch has a value
- if (sw[0] == '-' && argc > i+1) {
- val = utils::trimStr((std::string)argv[i+1]);
- if (val[0] == '-')
- val = "";
- else
- i++;
- }
- if (val.empty()) {
- std::string error = "No value for argument " + sw;
- helpAndExit(error);
- }
-
- // Pick up values
- if (sw == "-i") {
- licenseId = val;
- swCount++;
- }
- else if (sw == "-u") {
- userId = val;
- swCount++;
- }
- else if (sw == "-d") {
- size_t colPos = val.find(':');
- if (colPos == std::string::npos) {
- printf("Invalid service address: Must be in form <url>:<port>\n");
- exit(EXIT_FAILURE);
- }
- daemonAddr = val.substr(0, colPos);
- daemonPort = utils::strToInt(val.substr(colPos+1));
- if (daemonPort < 1) {
- printf("Invalid service port: Must be an integer\n");
- exit(EXIT_FAILURE);
- }
- swCount++;
- }
- else if (sw == "-l") {
- serverURL = val;
- size_t colPos = val.find(':');
- if (colPos == std::string::npos) {
- printf("Invalid license server address: Must be in form <url>:<port>\n");
- exit(EXIT_FAILURE);
- }
- uint16_t port = utils::strToInt(val.substr(colPos+1));
- if (daemonPort < 1) {
- printf("Invalid license server port: Must be an integer\n");
- exit(EXIT_FAILURE);
- }
- swCount++;
- }
- else {
- std::string error = "Invalid argument:" + sw;
- helpAndExit(error);
- }
- // printf("%s : %s\n", sw.c_str(), val.c_str());
- }
-
- // Now we check if all needed arguments are there
- if (swCount < 3) {
- helpAndExit("Too few arguments");
- }
- std::stringstream request;
- request << "longterm " << operation << " -u " << userId << " -i " << licenseId;
- if (serverURL.length() > 0) {
- // Add optional license server URL if specified
- request << " -l " << serverURL;
- }
- std::string msg = request.str();
-
- // Prepare for connection
- struct sockaddr_in server;
-#if __APPLE__ || __MACH__ || __linux__
- const int inetSuccess = inet_aton(daemonAddr.c_str(), &server.sin_addr);
-#else
- const int inetSuccess = inet_pton(AF_INET, daemonAddr.c_str(), &server.sin_addr.s_addr);
-#endif
- if (!inetSuccess) {
- // Try to resolve hostname
- struct hostent *host;
- struct in_addr **addrList;
- if ( (host = gethostbyname( daemonAddr.c_str() ) ) == nullptr){
- printf("Failed to resolve hostname: %s\n", daemonAddr.c_str());
- exit(EXIT_FAILURE);;
- }
- addrList = (struct in_addr **) host->h_addr_list;
- server.sin_addr = *addrList[0];
- }
- server.sin_family = AF_INET;
- server.sin_port = htons(daemonPort);
- int sockFD;
- sockFD = (socket(AF_INET , SOCK_STREAM , 0));
- if (sockFD < 0) {
- throw std::runtime_error(strerror(errno));
- }
-
- // Connect to daemon
- int connectR = connect(sockFD, (struct sockaddr *)&server, sizeof(server));
- if (connectR == -1) {
- close(sockFD);
- printf("Error while connecting socket: %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- // Send request
- const size_t bytesSent = send(sockFD, msg.c_str(), msg.length(), 0);
-
- if (bytesSent < 0 ) { // send failed
- printf("ERROR in sending to daemon: %s\n", strerror(errno));
- exit(EXIT_FAILURE);
- }
-
-
- // Listen for daemon reply
- std::string reply(BUFFER_SIZE, ' ');
- ssize_t bytes_recv = recv(sockFD, &reply.front(), reply.size(), 0);
- if (bytes_recv == -1) {
- printf("Error while receiving bytes\n");
- exit(EXIT_FAILURE);
- }
- close(sockFD);
-
- reply = utils::trimStr(reply);
- // Show the reply and we're done
- printf("%s\n", reply.c_str());
- if (reply.find("No") != std::string::npos ||
- reply.find("ERROR") != std::string::npos) {
- exit(EXIT_FAILURE);
- }
- exit(EXIT_SUCCESS);
-}
-
-void helpAndExit(const std::string &reason) {
- printf("\nERROR: %s\n\n", reason.c_str());
- printf("%s\n", helpText().c_str());
- exit(EXIT_FAILURE);
-}
-
-std::string helpText() {
- std::stringstream ss;
- ss << "Usage:\n";
- ss << " qtlongterm add|remove -a daemon_url:port -u username -i license_id [-l <server_url>:<server_port>]\n";
- ss << " Or:\n qtlongterm --help to get this help (-h also works)\n";
- ss << "Where:\n";
- ss << " -d = Full license daemon address with port separated by ':'.\n";
- ss << " -u = Your Qt license username\n";
- ss << " -i = Your Qt license ID number (must be an int)\n";
- ss << " -l = (Optional, not required) License server address and port \n";
- ss << "Use \"add\" to request a long-term license reservation and \"remove\" to remove it\n";
- ss << "\nExample:\n";
- ss << " qtlongterm add -d localhost:60000 -u foobar -i 12345670\n";
- return ss.str();
-}
diff --git a/qtlongterm/qtlongterm.h b/qtlongterm/qtlongterm.h
deleted file mode 100644
index bb99a73..0000000
--- a/qtlongterm/qtlongterm.h
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
-#pragma once
-
-#include <cstring>
-#include <iostream>
-#include <string>
-#include <sstream>
-#include <fstream>
-#include <map>
-#if __APPLE__ || __MACH__ || __linux__
- #include <sys/types.h>
- #include <netdb.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <unistd.h>
-#else
- #include <windows.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #define close closesocket
-#endif
-
-#include "utils.h"
-//#include "commonsetup.h"
-
-#define APP_NAME "Qt long-term license CLI"
-#define BUFFER_SIZE 1024
-
-void helpAndExit(const std::string &reason);
-std::string helpText();
diff --git a/tcpclient.cpp b/tcpclient.cpp
new file mode 100644
index 0000000..1922b76
--- /dev/null
+++ b/tcpclient.cpp
@@ -0,0 +1,76 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#include "tcpclient.h"
+
+TcpClient::TcpClient(const std::string &connAddr, uint16_t port)
+{
+#ifdef _WIN32
+ // Initialize Winsock
+ WSADATA wsaData;
+ int iResult = 0;
+ iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
+ if (iResult != NO_ERROR) {
+ wprintf(L"Error at WSAStartup()\n");
+ exit(EXIT_FAILURE);
+ }
+ const int inetSuccess = inet_pton(AF_INET, connAddr.c_str(), &m_server.sin_addr.s_addr);
+#else
+ const int inetSuccess = inet_aton(connAddr.c_str(), &m_server.sin_addr);
+#endif
+ if (!inetSuccess) {
+ // Try to resolve hostname
+ struct hostent *host;
+ struct in_addr **addrList;
+ if ( (host = gethostbyname(connAddr.c_str()) ) == nullptr){
+ std::cout << "Failed to resolve hostname\n";
+ exit(EXIT_FAILURE);
+ }
+ addrList = (struct in_addr **) host->h_addr_list;
+ m_server.sin_addr = *addrList[0];
+ }
+ m_server.sin_port = htons(port);
+}
+
+int TcpClient::sendAndReceive(const std::string &message, std::string &reply)
+{
+ m_server.sin_family = AF_INET;
+ m_socketFD = (socket(AF_INET , SOCK_STREAM, 0));
+ if (m_socketFD < 0) {
+ doCloseSocket();
+ return e_tcp_fail_socket;
+ }
+
+ // Connect to daemon
+ int connectR = connect(m_socketFD, (struct sockaddr *)&m_server, sizeof(m_server));
+ if (connectR == -1) {
+ doCloseSocket();
+ return e_tcp_error_conn;
+ }
+ const size_t bytesSent = send(m_socketFD, message.c_str(), (int)message.length(), 0);
+
+ if (bytesSent < 0 ) { // send failed
+ doCloseSocket();
+ return e_tcp_error_send;
+ }
+
+ std::string resp(BUFFER_SIZE, ' ');
+ size_t bytes_recv;
+ try {
+ bytes_recv = recv(m_socketFD, &resp.front(), (int)resp.size(), 0);
+ }
+ catch (...) {
+ std::cout << "Error receiving" << std::endl;
+ doCloseSocket();
+ return e_tcp_error_recv;
+ }
+ if (bytes_recv == -1) {
+ doCloseSocket();
+ return e_tcp_error_recv;
+ }
+ doCloseSocket();
+ reply = resp.substr(0, bytes_recv); // Had to cut it like this for windows
+ return e_tcp_success;
+}
diff --git a/tcpserver.cpp b/tcpserver.cpp
index a7b9ff1..5ee4e89 100644
--- a/tcpserver.cpp
+++ b/tcpserver.cpp
@@ -1,172 +1,182 @@
-// Copyright (C) 2022 The Qt Company Ltd.
-//
-
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
#include "tcpserver.h"
TcpServer::TcpServer(uint16_t serverPort)
{
- init(serverPort);
-}
-
-int TcpServer::init(uint16_t serverPort) {
int opt = TRUE;
- // initialize all m_clientSocket[] to 0 so not checked
- for (uint8_t i = 0; i < MAX_CLIENTS; i++)
- {
+ // Initialize all m_clientSocket[] to 0 so not checked
+ for (uint8_t i = 0; i < MAX_CLIENTS; i++) {
m_clientSocket[i] = 0;
}
- // create a master socket
- if ((m_masterSocket = socket(AF_INET, SOCK_STREAM, 0)) == 0)
- {
+#ifdef _WIN32
+ // Initialize Winsock
+ WSADATA wsaData;
+ int iResult = 0;
+ iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
+ if (iResult != NO_ERROR) {
+ wprintf(L"Error at WSAStartup()\n");
+ exit(EXIT_FAILURE);
+ }
+#endif
+ // Create a master socket
+ if ((m_masterSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
- // set master socket to allow multiple connections ,
- // this is just a good habit, it will work without this
+ // Set master socket to allow multiple connections
+
if (setsockopt(m_masterSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
- sizeof(opt)) < 0)
- {
- perror("setsockopt");
+ sizeof(opt)) < 0) {
+ perror("setsockopt failed");
exit(EXIT_FAILURE);
}
+ timeval tv {2, 0}; //t.tv_sec = 2; t.tv_usec = 0;
+ int ret = setsockopt(m_masterSocket, SOL_SOCKET, SO_RCVTIMEO,
+ (char*)&tv, sizeof(timeval));
+ if (ret < 0) {
+ printf("Socket timeout error code: %d\n", ret);
+ perror("Socket timeout failed");
+ }
- // type of socket created
+ // Type of socket created
m_address.sin_family = AF_INET;
m_address.sin_addr.s_addr = INADDR_ANY;
m_address.sin_port = htons(serverPort);
- // bind the socket to localhost port 8888
- if (bind(m_masterSocket, (struct sockaddr *)&m_address, sizeof(m_address)) < 0)
- {
+ // Bind the socket to localhost port 8888
+ if (bind(m_masterSocket, (struct sockaddr *)&m_address, sizeof(m_address)) < 0) {
+ doCloseSocket(m_masterSocket);
perror("bind failed");
exit(EXIT_FAILURE);
}
- printf("Listening to port %d \n", serverPort);
-
- // try to specify maximum of 3 pending connections for the master socket
- if (listen(m_masterSocket, 3) < 0)
- {
+ std::cout << "Listening to port " << serverPort << std::endl;
+ unsigned long mode = 1;
+ //ioctlsocket(m_masterSocket, FIONBIO, &mode);
+ // Try to specify maximum of 3 pending connections for the master socket
+ if (listen(m_masterSocket, 3) < 0) {
+ doCloseSocket(m_masterSocket);
perror("listen");
exit(EXIT_FAILURE);
}
-
- // accept the incoming connection
m_addrlen = sizeof(m_address);
- puts("Waiting for connections ...");
- return 0;
+ // Accept the incoming connection
+ std::cout << "Waiting for connections ...\n";
+}
+
+TcpServer::~TcpServer()
+{
+ doCloseSocket(m_masterSocket);
+ for (uint8_t i = 0; i < MAX_CLIENTS; i++) {
+ doCloseSocket(m_clientSocket[i]);
+ }
+
}
-std::string TcpServer::listenToClients(int &socket) {
- int new_socket, activity, i, valread, sd, max_sd;
+std::string TcpServer::listenToClients(int &socket)
+{
std::string data;
bool gotData = false;
- do {
- // clear the socket set
+ //do {
+ // Clear the socket set
FD_ZERO(&m_readfds);
- // add master socket to set
+ type_socket max_sd = m_masterSocket;
+
+ // Add master socket to set
FD_SET(m_masterSocket, &m_readfds);
- max_sd = m_masterSocket;
- // add child sockets to set
- for (i = 0; i < MAX_CLIENTS; i++)
- {
- // socket descriptor
- sd = m_clientSocket[i];
+ // Add child sockets to set
+ for (int i = 0; i < MAX_CLIENTS; i++) {
+ // Socket descriptor
+ type_socket sd = m_clientSocket[i];
- // if valid socket descriptor then add to read list
+ // If valid socket descriptor then add to read list
if (sd > 0)
FD_SET(sd, &m_readfds);
- // highest file descriptor number, need it for the select function
+ // Highest file descriptor number, need it for the select function
if (sd > max_sd)
max_sd = sd;
}
+ // timeout
+ timeval tv{2, 0}; //t.tv_sec = 2; t.tv_usec = 0;
+ // Wait for an activity on one of the sockets.
+ int activity = select((int)max_sd + 1, &m_readfds, NULL, NULL, &tv);
- // wait for an activity on one of the sockets , timeout is NULL ,
- // so wait indefinitely
- activity = select(max_sd + 1, &m_readfds, NULL, NULL, NULL);
-
- if ((activity < 0) && (errno != EINTR))
- {
- printf("select error");
+ if ((activity < 0) && (errno != EINTR)) {
+ std::cout << "select error \n";
}
-
- // If something happened on the master socket ,
- // then its an incoming connection
- if (FD_ISSET(m_masterSocket, &m_readfds))
- {
+ // If something happened on the master socket, then its an incoming connection
+ if (FD_ISSET(m_masterSocket, &m_readfds)) {
+ type_socket new_socket;
if ((new_socket = accept(m_masterSocket,
- (struct sockaddr *)&m_address, (socklen_t *)&m_addrlen)) < 0)
- {
+ (struct sockaddr *)&m_address, (socklen_t *)&m_addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
-
- // inform user of socket number - used in send and receive commands
- printf("New connection , socket fd is %d , ip is : %s , port : %d\n",
- new_socket , inet_ntoa(m_address.sin_addr) , ntohs(m_address.sin_port));
-
- // add new socket to array of sockets
- for (i = 0; i < MAX_CLIENTS; i++)
- {
- // if position is empty
- if (m_clientSocket[i] == 0)
- {
+ // Add new socket to array of sockets
+ for (int i = 0; i < MAX_CLIENTS; i++) {
+ // If position is free
+ if (m_clientSocket[i] == 0) {
m_clientSocket[i] = new_socket;
- printf("Adding to list of sockets as %d\n", i);
-
+ std::cout << "New connection - adding to list of sockets with id " << i << std::endl;
break;
}
}
}
+ // Else its some IO operation on some other socket
+ for (int i = 0; i < MAX_CLIENTS; i++) {
+ type_socket sd = m_clientSocket[i];
- // else its some IO operation on some other socket
- for (i = 0; i < MAX_CLIENTS; i++)
- {
- sd = m_clientSocket[i];
-
- if (FD_ISSET(sd, &m_readfds))
- {
+ if (FD_ISSET(sd, &m_readfds)) {
// Check if it was for closing , and also read the
// incoming message
- if ((valread = read(sd, m_buffer, 1024)) == 0)
- {
- // Somebody disconnected , get his details and print
+#ifdef _WIN32
+ int valread = recv(sd, m_buffer, sizeof(m_buffer), 0);
+#else
+ int valread = read(sd, m_buffer, sizeof(m_buffer));
+#endif
+ if (valread == 0) {
+ // Somebody disconnected, get his details and print
getpeername(sd, (struct sockaddr *)&m_address,
(socklen_t *)&m_addrlen);
- printf("Host disconnected , ip %s , socket id %d\n",
- inet_ntoa(m_address.sin_addr), sd);
+ std::cout << "Client disconnected, socket id " << sd << std::endl;
// Close the socket and mark as 0 in list for reuse
- close(sd);
+ doCloseSocket(sd);
m_clientSocket[i] = 0;
- }
- else
- {
- // set the string terminating NULL byte on the end
- // of the data read
- m_buffer[valread] = '\0';
+ } else {
+ // Set the string terminating NULL byte
+ // on the end of the data read
gotData = true;
+ m_buffer[valread] = '\0';
socket = i;
- data += (std::string)m_buffer;
- //send(sd, data.c_str(), strlen(m_buffer), 0);
+ data = m_buffer;
}
}
}
- } while (!gotData);
+ //} while (!gotData);
+
return data;
}
-
-int TcpServer::sendResponse(int socketIndex, const std::string &message) {
- int sd = m_clientSocket[socketIndex];
- send(sd, message.c_str(), message.length(), 0);
+int TcpServer::sendResponse(int socketIndex, const std::string &message)
+{
+ type_socket sd = m_clientSocket[socketIndex];
+ if (send(sd, message.c_str(), (int)message.length(), 0) != message.length()) {
+ printf("[TcpServer] Send failed\n");
+ return 1;
+ }
+ doCloseSocket(sd);
+ m_clientSocket[socketIndex] = 0;
return 0;
}
diff --git a/utils.cpp b/utils.cpp
new file mode 100644
index 0000000..7bfd481
--- /dev/null
+++ b/utils.cpp
@@ -0,0 +1,258 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#include "utils.h"
+#include "commonsetup.h"
+
+namespace utils
+{
+
+// Trim whitespaces from start of a string
+void trimLeft(std::string &s)
+{
+ s.erase(s.begin(), std::find_if (s.begin(), s.end(), [](unsigned char ch)
+ { return !std::isspace(ch); }));
+}
+
+// Trim whitespaces from end of a string
+void trimRight(std::string &s)
+{
+ s.erase(std::find_if (s.rbegin(), s.rend(), [](unsigned char ch)
+ { return !std::isspace(ch); })
+ .base(),
+ s.end());
+}
+
+// Trim whitespaces from both ends of a string
+std::string trimStr(const std::string &s)
+{
+ std::string trimmed = s;
+ trimLeft(trimmed);
+ trimRight(trimmed);
+
+ return trimmed;
+}
+
+// Split a string by a char (Defaults to a space)
+std::vector<std::string> splitStr(const std::string &str, const char delimiter)
+{
+ std::vector<std::string> strings;
+ std::istringstream ss(str);
+ std::string tmpStr;
+ while (getline(ss, tmpStr, delimiter)) {
+ tmpStr = trimStr(tmpStr);
+ strings.push_back(tmpStr);
+ }
+ return strings;
+}
+
+// Convert string to lower case
+std::string strToLower(const std::string &str)
+{
+ std::string ret = str;
+ std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
+ return ret;
+}
+
+// Convert string to upper case
+std::string strToUpper(const std::string &str)
+{
+ std::string ret = str;
+ std::transform(ret.begin(), ret.end(), ret.begin(), ::toupper);
+ return ret;
+}
+
+// String to int: Because stoi() raises an exception upon failing
+int strToInt(const std::string &str)
+{
+ int retVal = 0;
+ try {
+ retVal = stoi(str);
+ }
+ catch (...) {
+ printf("ERROR: Unable to convert '%s' to an int\n", str.c_str());
+ }
+ return retVal;
+}
+
+std::string getUserHomeDir()
+{
+ // Try to find current user's home
+ std::string homedir;
+#if __linux__ || __APPLE__ || __MACH__
+ // Linux and Mac
+ if (getenv("HOME") != nullptr)
+ homedir = getenv("HOME");
+ if (homedir.length() == 0) {
+ homedir = getpwuid(getuid())->pw_dir;
+ }
+#else
+ homedir = getenv("HOMEPATH");
+ homedir = SYSTEM_ROOT + homedir;
+#endif
+ if (&homedir == nullptr) {
+ printf("ERROR Not able to determine user's home directory\n");
+ homedir = "";
+ }
+ return homedir;
+}
+
+// Write data to the file
+int writeToFile(const std::string &filepath, const std::string &data, bool append)
+{
+ std::string path;
+ std::ofstream file;
+ // can't enable exception now because of gcc bug that raises ios_base::failure with useless message
+ if (append) {
+ file.open(filepath, std::ios::out | std::ios::app);
+ } else {
+ file.open(filepath, std::ios::out);
+ }
+ if (file.fail()) {
+ return -1;
+ }
+ try {
+ file << data << std::endl;
+ } catch (...) {
+ file.close();
+ std::cout << "Failed to write data in file " << filepath << std::endl;
+ return -1;
+ }
+ file.close();
+ return 0;
+}
+
+int createDir(const std::string &filepath, uint16_t user, uint16_t group)
+{
+ std::vector<std::string> pathVector = utils::splitStr(filepath, DIR_SEPARATOR);
+ std::string path;
+ for (std::string dir : pathVector) {
+ path += SYSTEM_ROOT;
+ path += dir;
+ if (!utils::fileExists(path)) {
+#if __linux__ || __APPLE__ || __MACH__
+ if (mkdir(path.c_str(), 0777) != 0) {
+ return -1;
+ }
+ chown(path.c_str(), user, group);
+#else
+
+ printf("WARNING: Unimplemented: createDir() for Windows\n");
+#endif
+ }
+ }
+ return 0;
+}
+
+int readFile(std::string &str, const std::string &filepath)
+{
+ std::ifstream file;
+ std::stringstream ss;
+
+ file.open(filepath, std::ios::in);
+ if (file.is_open()) {
+ std::string line;
+ while (getline(file, line)) {
+ ss << line;
+ }
+ file.close();
+ } else {
+ return -1;
+ }
+ str = ss.str();
+ return 0;
+}
+
+bool fileExists(const std::string &name)
+{
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat buffer;
+ return (stat (name.c_str(), &buffer) == 0);
+#else
+ if (_access(name.c_str(), 0) == -1) {
+ std::cout << "File " << name << " doesn't exist\n";
+ return false; // not accessible
+ }
+ return true;
+#endif
+}
+
+std::string getFileOwnerName(const std::string &filename)
+{
+ std::string retVal;
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat info;
+ stat(filename.c_str(), &info); // Error check omitted
+ struct passwd *pw = getpwuid(info.st_uid);
+ if (pw != 0) retVal = pw->pw_name; // contains the user name
+
+#else
+ printf("WARNING! Uniplemented: Win version of getFileOwnerName()\n");
+ retVal = "NULL";
+#endif
+ return retVal;
+}
+
+int getFileOwner(const std::string &filename, uint16_t &owner, uint16_t &group)
+{
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat info;
+ stat(filename.c_str(), &info); // Error check omitted
+ std::string name = getFileOwnerName(filename);
+ owner = info.st_uid;
+ group = info.st_gid;
+#else
+ printf("WARNING! Uniplemented: Win version of getFileOwner()\n");
+#endif
+ return 0;
+}
+
+std::vector<std::string> getDirListing(const std::string &directory, const std::string &filter)
+{
+ /* Open directory stream */
+ DIR *dir = opendir(directory.c_str());
+ if (!dir) {
+ /* Could not open directory */
+ std::cout << "Cannot open directory" << directory << std::endl;;
+ }
+ /* Gather files and directories within the directory */
+ std::vector<std::string> files;
+ struct dirent *ent;
+ while ((ent = readdir(dir)) != NULL) {
+ if (ent->d_type == DT_REG) {
+ std::string name = ent->d_name;
+ if (name.substr(0, filter.length()) == filter || filter.empty()) {
+ files.push_back(name);
+ }
+ }
+ }
+ closedir(dir);
+ return files;
+}
+
+
+std::string getOsName()
+{
+#if _WIN32
+ return "Windows";
+#elif __APPLE__ || __MACH__
+ return "macOS";
+#elif __linux__
+ return "Linux";
+#elif __FreeBSD__
+ return "FreeBSD";
+#elif __unix || __unix__
+ return "Unix";
+#else
+ return "Unknown OS";
+#endif
+}
+
+/*
+* App-specific utils here (not generic)
+*/
+
+
+} // namespace utils