| 1 | // Copyright (c) 2014-2022, The Monero Project |
| 2 | // |
| 3 | // All rights reserved. |
| 4 | // |
| 5 | // Redistribution and use in source and binary forms, with or without modification, are |
| 6 | // permitted provided that the following conditions are met: |
| 7 | // |
| 8 | // 1. Redistributions of source code must retain the above copyright notice, this list of |
| 9 | // conditions and the following disclaimer. |
| 10 | // |
| 11 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list |
| 12 | // of conditions and the following disclaimer in the documentation and/or other |
| 13 | // materials provided with the distribution. |
| 14 | // |
| 15 | // 3. Neither the name of the copyright holder nor the names of its contributors may be |
| 16 | // used to endorse or promote products derived from this software without specific |
| 17 | // prior written permission. |
| 18 | // |
| 19 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
| 20 | // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF |
| 21 | // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL |
| 22 | // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
| 24 | // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 25 | // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, |
| 26 | // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF |
| 27 | // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | // |
| 29 | // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers |
| 30 | |
| 31 | #include <unistd.h> |
| 32 | #include <cstdio> |
| 33 | #include <wchar.h> |
| 34 | |
| 35 | #ifdef __GLIBC__ |
| 36 | #include <gnu/libc-version.h> |
| 37 | #endif |
| 38 | |
| 39 | #ifdef __GLIBC__ |
| 40 | #include <sys/types.h> |
| 41 | #include <sys/stat.h> |
| 42 | #include <sys/resource.h> |
| 43 | #include <unistd.h> |
| 44 | #include <dirent.h> |
| 45 | #include <string.h> |
| 46 | #include <ctype.h> |
| 47 | #include <string> |
| 48 | #endif |
| 49 | |
| 50 | //tools::is_hdd |
| 51 | #ifdef __GLIBC__ |
| 52 | #include <sstream> |
| 53 | #include <sys/sysmacros.h> |
| 54 | #include <fstream> |
| 55 | #endif |
| 56 | |
| 57 | #include "unbound.h" |
| 58 | |
| 59 | #include "include_base_utils.h" |
| 60 | #include "file_io_utils.h" |
| 61 | #include "wipeable_string.h" |
| 62 | #include "time_helper.h" |
| 63 | using namespace epee; |
| 64 | |
| 65 | #include "crypto/crypto.h" |
| 66 | #include "util.h" |
| 67 | #include "stack_trace.h" |
| 68 | #include "memwipe.h" |
| 69 | #include "net/http_client.h" // epee::net_utils::... |
| 70 | #include "readline_buffer.h" |
| 71 | |
| 72 | #ifdef WIN32 |
| 73 | #ifndef STRSAFE_NO_DEPRECATE |
| 74 | #define STRSAFE_NO_DEPRECATE |
| 75 | #endif |
| 76 | #include <windows.h> |
| 77 | #include <shlobj.h> |
| 78 | #include <strsafe.h> |
| 79 | #else |
| 80 | #include <sys/file.h> |
| 81 | #include <sys/utsname.h> |
| 82 | #include <sys/stat.h> |
| 83 | #endif |
| 84 | #include <boost/filesystem.hpp> |
| 85 | #include <boost/algorithm/string.hpp> |
| 86 | #include <boost/asio.hpp> |
| 87 | #include <boost/format.hpp> |
| 88 | #include <openssl/evp.h> |
| 89 | |
| 90 | #undef MONERO_DEFAULT_LOG_CATEGORY |
| 91 | #define MONERO_DEFAULT_LOG_CATEGORY "util" |
| 92 | |
| 93 | namespace |
| 94 | { |
| 95 | |
| 96 | #ifndef _WIN32 |
| 97 | static int flock_exnb(int fd) |
| 98 | { |
| 99 | struct flock fl; |
| 100 | int ret; |
| 101 | |
| 102 | memset(&fl, 0, sizeof(fl)); |
| 103 | fl.l_type = F_WRLCK; |
| 104 | fl.l_whence = SEEK_SET; |
| 105 | fl.l_start = 0; |
| 106 | fl.l_len = 0; |
| 107 | ret = fcntl(fd, F_SETLK, &fl); |
| 108 | if (ret < 0) |
| 109 | MERROR("Error locking fd " << fd << ": " << errno << " (" << strerror(errno) << ")"); |
| 110 | return ret; |
| 111 | } |
| 112 | #endif |
| 113 | |
| 114 | } |
| 115 | |
| 116 | namespace tools |
| 117 | { |
| 118 | |
| 119 | void copy_file(const std::string& from, const std::string& to) |
| 120 | { |
| 121 | using boost::filesystem::path; |
| 122 | #if BOOST_VERSION < 107400 |
| 123 | // Remove this preprocessor if/else when we are bumping the boost version. |
| 124 | boost::filesystem::copy_file( |
| 125 | path(from), |
| 126 | path(to), |
| 127 | boost::filesystem::copy_option::overwrite_if_exists); |
| 128 | #else |
| 129 | boost::filesystem::copy_file( |
| 130 | path(from), |
| 131 | path(to), |
| 132 | boost::filesystem::copy_options::overwrite_existing); |
| 133 | #endif |
| 134 | } |
| 135 | |
| 136 | std::function<void(int)> signal_handler::m_handler; |
| 137 | |
| 138 | private_file::private_file() noexcept : m_handle(), m_filename() {} |
| 139 | |
| 140 | private_file::private_file(std::FILE* handle, std::string&& filename) noexcept |
| 141 | : m_handle(handle), m_filename(std::move(filename)) {} |
| 142 | |
| 143 | private_file private_file::create(std::string name, uint32_t extra_flags) |
| 144 | { |
| 145 | #ifdef WIN32 |
| 146 | struct close_handle |
| 147 | { |
| 148 | void operator()(HANDLE handle) const noexcept |
| 149 | { |
| 150 | CloseHandle(handle); |
| 151 | } |
| 152 | }; |
| 153 | |
| 154 | std::unique_ptr<void, close_handle> process = nullptr; |
| 155 | { |
| 156 | HANDLE temp{}; |
| 157 | const bool fail = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, std::addressof(temp)) == 0; |
| 158 | process.reset(temp); |
| 159 | if (fail) |
| 160 | return {}; |
| 161 | } |
| 162 | |
| 163 | DWORD sid_size = 0; |
| 164 | GetTokenInformation(process.get(), TokenOwner, nullptr, 0, std::addressof(sid_size)); |
| 165 | if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) |
| 166 | return {}; |
| 167 | |
| 168 | std::unique_ptr<char[]> sid{new char[sid_size]}; |
| 169 | if (!GetTokenInformation(process.get(), TokenOwner, sid.get(), sid_size, std::addressof(sid_size))) |
| 170 | return {}; |
| 171 | |
| 172 | const PSID psid = reinterpret_cast<const PTOKEN_OWNER>(sid.get())->Owner; |
| 173 | const DWORD daclSize = |
| 174 | sizeof(ACL) + sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(psid) - sizeof(DWORD); |
| 175 | |
| 176 | const std::unique_ptr<char[]> dacl{new char[daclSize]}; |
| 177 | if (!InitializeAcl(reinterpret_cast<PACL>(dacl.get()), daclSize, ACL_REVISION)) |
| 178 | return {}; |
| 179 | |
| 180 | if (!AddAccessAllowedAce(reinterpret_cast<PACL>(dacl.get()), ACL_REVISION, (READ_CONTROL | FILE_GENERIC_READ | DELETE), psid)) |
| 181 | return {}; |
| 182 | |
| 183 | SECURITY_DESCRIPTOR descriptor{}; |
| 184 | if (!InitializeSecurityDescriptor(std::addressof(descriptor), SECURITY_DESCRIPTOR_REVISION)) |
| 185 | return {}; |
| 186 | |
| 187 | if (!SetSecurityDescriptorDacl(std::addressof(descriptor), true, reinterpret_cast<PACL>(dacl.get()), false)) |
| 188 | return {}; |
| 189 | |
| 190 | SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), std::addressof(descriptor), false}; |
| 191 | std::unique_ptr<void, close_handle> file{ |
| 192 | CreateFile( |
| 193 | name.c_str(), |
| 194 | GENERIC_WRITE, FILE_SHARE_READ, |
| 195 | std::addressof(attributes), |
| 196 | CREATE_NEW, (FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE | extra_flags), |
| 197 | nullptr |
| 198 | ) |
| 199 | }; |
| 200 | if (file) |
| 201 | { |
| 202 | const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(file.get()), 0); |
| 203 | if (0 <= fd) |
| 204 | { |
| 205 | file.release(); |
| 206 | std::FILE* real_file = _fdopen(fd, "w"); |
| 207 | if (!real_file) |
| 208 | { |
| 209 | _close(fd); |
| 210 | } |
| 211 | return {real_file, std::move(name)}; |
| 212 | } |
| 213 | } |
| 214 | #else |
| 215 | const int fdr = open(name.c_str(), (O_RDONLY | O_CREAT | extra_flags), S_IRUSR); |
| 216 | if (0 <= fdr) |
| 217 | { |
| 218 | struct stat rstats = {}; |
| 219 | if (fstat(fdr, std::addressof(rstats)) != 0) |
| 220 | { |
| 221 | close(fdr); |
| 222 | return {}; |
| 223 | } |
| 224 | fchmod(fdr, (S_IRUSR | S_IWUSR)); |
| 225 | const int fdw = open(name.c_str(), O_RDWR); |
| 226 | fchmod(fdr, rstats.st_mode); |
| 227 | close(fdr); |
| 228 | |
| 229 | if (0 <= fdw) |
| 230 | { |
| 231 | struct stat wstats = {}; |
| 232 | if (fstat(fdw, std::addressof(wstats)) == 0 && |
| 233 | rstats.st_dev == wstats.st_dev && rstats.st_ino == wstats.st_ino && |
| 234 | flock_exnb(fdw) == 0 && ftruncate(fdw, 0) == 0) |
| 235 | { |
| 236 | std::FILE* file = fdopen(fdw, "w"); |
| 237 | if (file) return {file, std::move(name)}; |
| 238 | } |
| 239 | close(fdw); |
| 240 | } |
| 241 | } |
| 242 | #endif |
| 243 | return {}; |
| 244 | } |
| 245 | |
| 246 | private_file private_file::drop_and_recreate(std::string filename) |
| 247 | { |
| 248 | if (epee::file_io_utils::is_file_exist(filename)) { |
| 249 | boost::system::error_code ec{}; |
| 250 | boost::filesystem::remove(filename, ec); |
| 251 | if (ec) { |
| 252 | MERROR("Failed to remove " << filename << ": " << ec.message()); |
| 253 | return {}; |
| 254 | } |
| 255 | } |
| 256 | #ifdef WIN32 |
| 257 | return create(filename); |
| 258 | #else |
| 259 | return create(filename, O_EXCL); |
| 260 | #endif |
| 261 | } |
| 262 | |
| 263 | private_file::~private_file() noexcept |
| 264 | { |
| 265 | try |
| 266 | { |
| 267 | boost::system::error_code ec{}; |
| 268 | boost::filesystem::remove(filename(), ec); |
| 269 | } |
| 270 | catch (...) {} |
| 271 | } |
| 272 | |
| 273 | file_locker::file_locker(const std::string &filename) |
| 274 | { |
| 275 | #ifdef WIN32 |
| 276 | m_fd = INVALID_HANDLE_VALUE; |
| 277 | std::wstring filename_wide; |
| 278 | try |
| 279 | { |
| 280 | filename_wide = string_tools::utf8_to_utf16(filename); |
| 281 | } |
| 282 | catch (const std::exception &e) |
| 283 | { |
| 284 | MERROR("Failed to convert path \"" << filename << "\" to UTF-16: " << e.what()); |
| 285 | return; |
| 286 | } |
| 287 | m_fd = CreateFileW(filename_wide.c_str(), GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); |
| 288 | if (m_fd != INVALID_HANDLE_VALUE) |
| 289 | { |
| 290 | OVERLAPPED ov; |
| 291 | memset(&ov, 0, sizeof(ov)); |
| 292 | if (!LockFileEx(m_fd, LOCKFILE_FAIL_IMMEDIATELY | LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &ov)) |
| 293 | { |
| 294 | MERROR("Failed to lock " << filename << ": " << std::error_code(GetLastError(), std::system_category())); |
| 295 | CloseHandle(m_fd); |
| 296 | m_fd = INVALID_HANDLE_VALUE; |
| 297 | } |
| 298 | } |
| 299 | else |
| 300 | { |
| 301 | MERROR("Failed to open " << filename << ": " << std::error_code(GetLastError(), std::system_category())); |
| 302 | } |
| 303 | #else |
| 304 | m_fd = open(filename.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0666); |
| 305 | if (m_fd != -1) |
| 306 | { |
| 307 | if (flock_exnb(m_fd) == -1) |
| 308 | { |
| 309 | MERROR("Failed to lock " << filename << ": " << std::strerror(errno)); |
| 310 | close(m_fd); |
| 311 | m_fd = -1; |
| 312 | } |
| 313 | } |
| 314 | else |
| 315 | { |
| 316 | MERROR("Failed to open " << filename << ": " << std::strerror(errno)); |
| 317 | } |
| 318 | #endif |
| 319 | } |
| 320 | file_locker::~file_locker() |
| 321 | { |
| 322 | if (locked()) |
| 323 | { |
| 324 | #ifdef WIN32 |
| 325 | CloseHandle(m_fd); |
| 326 | #else |
| 327 | close(m_fd); |
| 328 | #endif |
| 329 | } |
| 330 | } |
| 331 | bool file_locker::locked() const |
| 332 | { |
| 333 | #ifdef WIN32 |
| 334 | return m_fd != INVALID_HANDLE_VALUE; |
| 335 | #else |
| 336 | return m_fd != -1; |
| 337 | #endif |
| 338 | } |
| 339 | |
| 340 | #ifdef WIN32 |
| 341 | std::string get_windows_version_display_string() |
| 342 | { |
| 343 | typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO); |
| 344 | typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); |
| 345 | #define BUFSIZE 10000 |
| 346 | |
| 347 | char pszOS[BUFSIZE] = {0}; |
| 348 | OSVERSIONINFOEX osvi; |
| 349 | SYSTEM_INFO si; |
| 350 | PGNSI pGNSI; |
| 351 | PGPI pGPI; |
| 352 | BOOL bOsVersionInfoEx; |
| 353 | DWORD dwType; |
| 354 | |
| 355 | ZeroMemory(&si, sizeof(SYSTEM_INFO)); |
| 356 | ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX)); |
| 357 | |
| 358 | osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); |
| 359 | bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*) &osvi); |
| 360 | |
| 361 | if(!bOsVersionInfoEx) return pszOS; |
| 362 | |
| 363 | // Call GetNativeSystemInfo if supported or GetSystemInfo otherwise. |
| 364 | |
| 365 | pGNSI = (PGNSI) GetProcAddress( |
| 366 | GetModuleHandle(TEXT("kernel32.dll")), |
| 367 | "GetNativeSystemInfo"); |
| 368 | if(NULL != pGNSI) |
| 369 | pGNSI(&si); |
| 370 | else GetSystemInfo(&si); |
| 371 | |
| 372 | if ( VER_PLATFORM_WIN32_NT==osvi.dwPlatformId && |
| 373 | osvi.dwMajorVersion > 4 ) |
| 374 | { |
| 375 | StringCchCopy(pszOS, BUFSIZE, TEXT("Microsoft ")); |
| 376 | |
| 377 | // Test for the specific product. |
| 378 | if ( osvi.dwMajorVersion == 10 ) |
| 379 | { |
| 380 | if ( osvi.dwMinorVersion == 0 ) |
| 381 | { |
| 382 | if( osvi.wProductType == VER_NT_WORKSTATION ) |
| 383 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows 10 ")); |
| 384 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2016 " )); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | if ( osvi.dwMajorVersion == 6 ) |
| 389 | { |
| 390 | if ( osvi.dwMinorVersion == 0 ) |
| 391 | { |
| 392 | if( osvi.wProductType == VER_NT_WORKSTATION ) |
| 393 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows Vista ")); |
| 394 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 " )); |
| 395 | } |
| 396 | |
| 397 | if ( osvi.dwMinorVersion == 1 ) |
| 398 | { |
| 399 | if( osvi.wProductType == VER_NT_WORKSTATION ) |
| 400 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows 7 ")); |
| 401 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 R2 " )); |
| 402 | } |
| 403 | |
| 404 | if ( osvi.dwMinorVersion == 2 ) |
| 405 | { |
| 406 | if( osvi.wProductType == VER_NT_WORKSTATION ) |
| 407 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows 8 ")); |
| 408 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2012 " )); |
| 409 | } |
| 410 | |
| 411 | if ( osvi.dwMinorVersion == 3 ) |
| 412 | { |
| 413 | if( osvi.wProductType == VER_NT_WORKSTATION ) |
| 414 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows 8.1 ")); |
| 415 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2012 R2 " )); |
| 416 | } |
| 417 | |
| 418 | pGPI = (PGPI) GetProcAddress( |
| 419 | GetModuleHandle(TEXT("kernel32.dll")), |
| 420 | "GetProductInfo"); |
| 421 | |
| 422 | pGPI( osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType); |
| 423 | |
| 424 | switch( dwType ) |
| 425 | { |
| 426 | case PRODUCT_ULTIMATE: |
| 427 | StringCchCat(pszOS, BUFSIZE, TEXT("Ultimate Edition" )); |
| 428 | break; |
| 429 | case PRODUCT_PROFESSIONAL: |
| 430 | StringCchCat(pszOS, BUFSIZE, TEXT("Professional" )); |
| 431 | break; |
| 432 | case PRODUCT_HOME_PREMIUM: |
| 433 | StringCchCat(pszOS, BUFSIZE, TEXT("Home Premium Edition" )); |
| 434 | break; |
| 435 | case PRODUCT_HOME_BASIC: |
| 436 | StringCchCat(pszOS, BUFSIZE, TEXT("Home Basic Edition" )); |
| 437 | break; |
| 438 | case PRODUCT_ENTERPRISE: |
| 439 | StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" )); |
| 440 | break; |
| 441 | case PRODUCT_BUSINESS: |
| 442 | StringCchCat(pszOS, BUFSIZE, TEXT("Business Edition" )); |
| 443 | break; |
| 444 | case PRODUCT_STARTER: |
| 445 | StringCchCat(pszOS, BUFSIZE, TEXT("Starter Edition" )); |
| 446 | break; |
| 447 | case PRODUCT_CLUSTER_SERVER: |
| 448 | StringCchCat(pszOS, BUFSIZE, TEXT("Cluster Server Edition" )); |
| 449 | break; |
| 450 | case PRODUCT_DATACENTER_SERVER: |
| 451 | StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition" )); |
| 452 | break; |
| 453 | case PRODUCT_DATACENTER_SERVER_CORE: |
| 454 | StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition (core installation)" )); |
| 455 | break; |
| 456 | case PRODUCT_ENTERPRISE_SERVER: |
| 457 | StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition" )); |
| 458 | break; |
| 459 | case PRODUCT_ENTERPRISE_SERVER_CORE: |
| 460 | StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition (core installation)" )); |
| 461 | break; |
| 462 | case PRODUCT_ENTERPRISE_SERVER_IA64: |
| 463 | StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems" )); |
| 464 | break; |
| 465 | case PRODUCT_SMALLBUSINESS_SERVER: |
| 466 | StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server" )); |
| 467 | break; |
| 468 | case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM: |
| 469 | StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server Premium Edition" )); |
| 470 | break; |
| 471 | case PRODUCT_STANDARD_SERVER: |
| 472 | StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition" )); |
| 473 | break; |
| 474 | case PRODUCT_STANDARD_SERVER_CORE: |
| 475 | StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition (core installation)" )); |
| 476 | break; |
| 477 | case PRODUCT_WEB_SERVER: |
| 478 | StringCchCat(pszOS, BUFSIZE, TEXT("Web Server Edition" )); |
| 479 | break; |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 ) |
| 484 | { |
| 485 | if( GetSystemMetrics(SM_SERVERR2) ) |
| 486 | StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Server 2003 R2, ")); |
| 487 | else if ( osvi.wSuiteMask & VER_SUITE_STORAGE_SERVER ) |
| 488 | StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Storage Server 2003")); |
| 489 | else if ( osvi.wSuiteMask & VER_SUITE_WH_SERVER ) |
| 490 | StringCchCat(pszOS, BUFSIZE, TEXT( "Windows Home Server")); |
| 491 | else if( osvi.wProductType == VER_NT_WORKSTATION && |
| 492 | si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) |
| 493 | { |
| 494 | StringCchCat(pszOS, BUFSIZE, TEXT( "Windows XP Professional x64 Edition")); |
| 495 | } |
| 496 | else StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2003, ")); |
| 497 | |
| 498 | // Test for the server type. |
| 499 | if ( osvi.wProductType != VER_NT_WORKSTATION ) |
| 500 | { |
| 501 | if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_IA64 ) |
| 502 | { |
| 503 | if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) |
| 504 | StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Edition for Itanium-based Systems" )); |
| 505 | else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) |
| 506 | StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise Edition for Itanium-based Systems" )); |
| 507 | } |
| 508 | |
| 509 | else if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 ) |
| 510 | { |
| 511 | if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) |
| 512 | StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter x64 Edition" )); |
| 513 | else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) |
| 514 | StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise x64 Edition" )); |
| 515 | else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard x64 Edition" )); |
| 516 | } |
| 517 | |
| 518 | else |
| 519 | { |
| 520 | if ( osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER ) |
| 521 | StringCchCat(pszOS, BUFSIZE, TEXT( "Compute Cluster Edition" )); |
| 522 | else if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) |
| 523 | StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Edition" )); |
| 524 | else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) |
| 525 | StringCchCat(pszOS, BUFSIZE, TEXT( "Enterprise Edition" )); |
| 526 | else if ( osvi.wSuiteMask & VER_SUITE_BLADE ) |
| 527 | StringCchCat(pszOS, BUFSIZE, TEXT( "Web Edition" )); |
| 528 | else StringCchCat(pszOS, BUFSIZE, TEXT( "Standard Edition" )); |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 ) |
| 534 | { |
| 535 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows XP ")); |
| 536 | if( osvi.wSuiteMask & VER_SUITE_PERSONAL ) |
| 537 | StringCchCat(pszOS, BUFSIZE, TEXT( "Home Edition" )); |
| 538 | else StringCchCat(pszOS, BUFSIZE, TEXT( "Professional" )); |
| 539 | } |
| 540 | |
| 541 | if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 ) |
| 542 | { |
| 543 | StringCchCat(pszOS, BUFSIZE, TEXT("Windows 2000 ")); |
| 544 | |
| 545 | if ( osvi.wProductType == VER_NT_WORKSTATION ) |
| 546 | { |
| 547 | StringCchCat(pszOS, BUFSIZE, TEXT( "Professional" )); |
| 548 | } |
| 549 | else |
| 550 | { |
| 551 | if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) |
| 552 | StringCchCat(pszOS, BUFSIZE, TEXT( "Datacenter Server" )); |
| 553 | else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) |
| 554 | StringCchCat(pszOS, BUFSIZE, TEXT( "Advanced Server" )); |
| 555 | else StringCchCat(pszOS, BUFSIZE, TEXT( "Server" )); |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | // Include service pack (if any) and build number. |
| 560 | |
| 561 | if( strlen(osvi.szCSDVersion) > 0 ) |
| 562 | { |
| 563 | StringCchCat(pszOS, BUFSIZE, TEXT(" ") ); |
| 564 | StringCchCat(pszOS, BUFSIZE, osvi.szCSDVersion); |
| 565 | } |
| 566 | |
| 567 | TCHAR buf[80]; |
| 568 | |
| 569 | StringCchPrintf( buf, 80, TEXT(" (build %d)"), osvi.dwBuildNumber); |
| 570 | StringCchCat(pszOS, BUFSIZE, buf); |
| 571 | |
| 572 | if ( osvi.dwMajorVersion >= 6 ) |
| 573 | { |
| 574 | if ( si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64 ) |
| 575 | StringCchCat(pszOS, BUFSIZE, TEXT( ", 64-bit" )); |
| 576 | else if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL ) |
| 577 | StringCchCat(pszOS, BUFSIZE, TEXT(", 32-bit")); |
| 578 | } |
| 579 | |
| 580 | return pszOS; |
| 581 | } |
| 582 | else |
| 583 | { |
| 584 | printf( "This sample does not support this version of Windows.\n"); |
| 585 | return pszOS; |
| 586 | } |
| 587 | } |
| 588 | #else |
| 589 | std::string get_nix_version_display_string() |
| 590 | { |
| 591 | struct utsname un; |
| 592 | |
| 593 | if(uname(&un) < 0) |
| 594 | return std::string("*nix: failed to get os version"); |
| 595 | return std::string() + un.sysname + " " + un.version + " " + un.release; |
| 596 | } |
| 597 | #endif |
| 598 | |
| 599 | |
| 600 | |
| 601 | std::string get_os_version_string() |
| 602 | { |
| 603 | #ifdef WIN32 |
| 604 | return get_windows_version_display_string(); |
| 605 | #else |
| 606 | return get_nix_version_display_string(); |
| 607 | #endif |
| 608 | } |
| 609 | |
| 610 | |
| 611 | |
| 612 | #ifdef WIN32 |
| 613 | std::string get_special_folder_path(int nfolder, bool iscreate) |
| 614 | { |
| 615 | WCHAR psz_path[MAX_PATH] = L""; |
| 616 | |
| 617 | if (SHGetSpecialFolderPathW(NULL, psz_path, nfolder, iscreate)) |
| 618 | { |
| 619 | try |
| 620 | { |
| 621 | return string_tools::utf16_to_utf8(psz_path); |
| 622 | } |
| 623 | catch (const std::exception &e) |
| 624 | { |
| 625 | MERROR("utf16_to_utf8 failed: " << e.what()); |
| 626 | return ""; |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | LOG_ERROR("SHGetSpecialFolderPathW() failed, could not obtain requested path."); |
| 631 | return ""; |
| 632 | } |
| 633 | #endif |
| 634 | |
| 635 | std::string get_default_data_dir() |
| 636 | { |
| 637 | /* Please for the love of god refactor the ifdefs out of this */ |
| 638 | |
| 639 | // namespace fs = boost::filesystem; |
| 640 | // Windows < Vista: C:\Documents and Settings\Username\Application Data\CRYPTONOTE_NAME |
| 641 | // Windows >= Vista: C:\Users\Username\AppData\Roaming\CRYPTONOTE_NAME |
| 642 | // Unix & Mac: ~/.CRYPTONOTE_NAME |
| 643 | std::string config_folder; |
| 644 | |
| 645 | #ifdef WIN32 |
| 646 | config_folder = get_special_folder_path(CSIDL_COMMON_APPDATA, true) + "\\" + CRYPTONOTE_NAME; |
| 647 | #else |
| 648 | std::string pathRet; |
| 649 | char* pszHome = getenv("HOME"); |
| 650 | if (pszHome == NULL || strlen(pszHome) == 0) |
| 651 | pathRet = "/"; |
| 652 | else |
| 653 | pathRet = pszHome; |
| 654 | config_folder = (pathRet + "/." + CRYPTONOTE_NAME); |
| 655 | #endif |
| 656 | |
| 657 | return config_folder; |
| 658 | } |
| 659 | |
| 660 | bool create_directories_if_necessary(const std::string& path) |
| 661 | { |
| 662 | namespace fs = boost::filesystem; |
| 663 | boost::system::error_code ec; |
| 664 | fs::path fs_path(path); |
| 665 | if (fs::is_directory(fs_path, ec)) |
| 666 | { |
| 667 | return true; |
| 668 | } |
| 669 | |
| 670 | bool res = fs::create_directories(fs_path, ec); |
| 671 | if (res) |
| 672 | { |
| 673 | LOG_PRINT_L2("Created directory: " << path); |
| 674 | } |
| 675 | else |
| 676 | { |
| 677 | LOG_PRINT_L2("Can't create directory: " << path << ", err: "<< ec.message()); |
| 678 | } |
| 679 | |
| 680 | return res; |
| 681 | } |
| 682 | |
| 683 | std::error_code replace_file(const std::string& old_name, const std::string& new_name) |
| 684 | { |
| 685 | int code; |
| 686 | #if defined(WIN32) |
| 687 | // Maximizing chances for success |
| 688 | std::wstring wide_replacement_name; |
| 689 | try { wide_replacement_name = string_tools::utf8_to_utf16(old_name); } |
| 690 | catch (...) { return std::error_code(GetLastError(), std::system_category()); } |
| 691 | std::wstring wide_replaced_name; |
| 692 | try { wide_replaced_name = string_tools::utf8_to_utf16(new_name); } |
| 693 | catch (...) { return std::error_code(GetLastError(), std::system_category()); } |
| 694 | |
| 695 | DWORD attributes = ::GetFileAttributesW(wide_replaced_name.c_str()); |
| 696 | if (INVALID_FILE_ATTRIBUTES != attributes) |
| 697 | { |
| 698 | ::SetFileAttributesW(wide_replaced_name.c_str(), attributes & (~FILE_ATTRIBUTE_READONLY)); |
| 699 | } |
| 700 | |
| 701 | bool ok = 0 != ::MoveFileExW(wide_replacement_name.c_str(), wide_replaced_name.c_str(), MOVEFILE_REPLACE_EXISTING); |
| 702 | code = ok ? 0 : static_cast<int>(::GetLastError()); |
| 703 | #else |
| 704 | bool ok = 0 == std::rename(old_name.c_str(), new_name.c_str()); |
| 705 | code = ok ? 0 : errno; |
| 706 | #endif |
| 707 | return std::error_code(code, std::system_category()); |
| 708 | } |
| 709 | |
| 710 | static bool unbound_built_with_threads() |
| 711 | { |
| 712 | ub_ctx *ctx = ub_ctx_create(); |
| 713 | if (!ctx) return false; // cheat a bit, should not happen unless OOM |
| 714 | char *monero = strdup("monero"), *unbound = strdup("unbound"); |
| 715 | ub_ctx_zone_add(ctx, monero, unbound); // this calls ub_ctx_finalize first, then errors out with UB_SYNTAX |
| 716 | free(unbound); |
| 717 | free(monero); |
| 718 | // if no threads, bails out early with UB_NOERROR, otherwise fails with UB_AFTERFINAL id already finalized |
| 719 | bool with_threads = ub_ctx_async(ctx, 1) != 0; // UB_AFTERFINAL is not defined in public headers, check any error |
| 720 | ub_ctx_delete(ctx); |
| 721 | MINFO("libunbound was built " << (with_threads ? "with" : "without") << " threads"); |
| 722 | return with_threads; |
| 723 | } |
| 724 | |
| 725 | bool sanitize_locale() |
| 726 | { |
| 727 | // boost::filesystem throws for "invalid" locales, such as en_US.UTF-8, or kjsdkfs, |
| 728 | // so reset it here before any calls to it |
| 729 | try |
| 730 | { |
| 731 | boost::filesystem::path p {std::string("test")}; |
| 732 | p /= std::string("test"); |
| 733 | } |
| 734 | catch (...) |
| 735 | { |
| 736 | #if defined(__MINGW32__) || defined(__MINGW__) |
| 737 | putenv("LC_ALL=C"); |
| 738 | putenv("LANG=C"); |
| 739 | #else |
| 740 | setenv("LC_ALL", "C", 1); |
| 741 | setenv("LANG", "C", 1); |
| 742 | #endif |
| 743 | return true; |
| 744 | } |
| 745 | return false; |
| 746 | } |
| 747 | |
| 748 | #ifdef STACK_TRACE |
| 749 | #ifdef _WIN32 |
| 750 | // https://stackoverflow.com/questions/1992816/how-to-handle-seg-faults-under-windows |
| 751 | static LONG WINAPI windows_crash_handler(PEXCEPTION_POINTERS pExceptionInfo) |
| 752 | { |
| 753 | tools::log_stack_trace("crashing"); |
| 754 | exit(1); |
| 755 | return EXCEPTION_CONTINUE_SEARCH; |
| 756 | } |
| 757 | static void setup_crash_dump() |
| 758 | { |
| 759 | SetUnhandledExceptionFilter(windows_crash_handler); |
| 760 | } |
| 761 | #else |
| 762 | static void posix_crash_handler(int signal) |
| 763 | { |
| 764 | tools::log_stack_trace(("crashing with fatal signal " + std::to_string(signal)).c_str()); |
| 765 | #ifdef NDEBUG |
| 766 | _exit(1); |
| 767 | #else |
| 768 | abort(); |
| 769 | #endif |
| 770 | } |
| 771 | static void setup_crash_dump() |
| 772 | { |
| 773 | signal(SIGSEGV, posix_crash_handler); |
| 774 | signal(SIGBUS, posix_crash_handler); |
| 775 | signal(SIGILL, posix_crash_handler); |
| 776 | signal(SIGFPE, posix_crash_handler); |
| 777 | } |
| 778 | #endif |
| 779 | #else |
| 780 | static void setup_crash_dump() {} |
| 781 | #endif |
| 782 | |
| 783 | bool disable_core_dumps() |
| 784 | { |
| 785 | #ifdef __GLIBC__ |
| 786 | // disable core dumps in release mode |
| 787 | struct rlimit rlimit; |
| 788 | rlimit.rlim_cur = rlimit.rlim_max = 0; |
| 789 | if (setrlimit(RLIMIT_CORE, &rlimit)) |
| 790 | { |
| 791 | MWARNING("Failed to disable core dumps"); |
| 792 | return false; |
| 793 | } |
| 794 | #endif |
| 795 | return true; |
| 796 | } |
| 797 | |
| 798 | ssize_t get_lockable_memory() |
| 799 | { |
| 800 | #ifdef __GLIBC__ |
| 801 | struct rlimit rlim; |
| 802 | if (getrlimit(RLIMIT_MEMLOCK, &rlim) < 0) |
| 803 | { |
| 804 | MERROR("Failed to determine the lockable memory limit"); |
| 805 | return -1; |
| 806 | } |
| 807 | return rlim.rlim_cur; |
| 808 | #else |
| 809 | return -1; |
| 810 | #endif |
| 811 | } |
| 812 | |
| 813 | bool on_startup() |
| 814 | { |
| 815 | mlog_configure("", true); |
| 816 | |
| 817 | setup_crash_dump(); |
| 818 | |
| 819 | sanitize_locale(); |
| 820 | |
| 821 | #ifdef __GLIBC__ |
| 822 | const char *ver = gnu_get_libc_version(); |
| 823 | if (!strcmp(ver, "2.25")) |
| 824 | MCLOG_RED(el::Level::Warning, "global", "Running with glibc " << ver << ", hangs may occur - change glibc version if possible"); |
| 825 | #endif |
| 826 | |
| 827 | #if OPENSSL_VERSION_NUMBER < 0x10100000 || defined(LIBRESSL_VERSION_TEXT) |
| 828 | SSL_library_init(); |
| 829 | #else |
| 830 | OPENSSL_init_ssl(0, NULL); |
| 831 | #endif |
| 832 | |
| 833 | if (!unbound_built_with_threads()) |
| 834 | MCLOG_RED(el::Level::Warning, "global", "libunbound was not built with threads enabled - crashes may occur"); |
| 835 | |
| 836 | return true; |
| 837 | } |
| 838 | void set_strict_default_file_permissions(bool strict) |
| 839 | { |
| 840 | #if defined(__MINGW32__) || defined(__MINGW__) |
| 841 | // no clue about the odd one out |
| 842 | #else |
| 843 | mode_t mode = strict ? 077 : 0; |
| 844 | umask(mode); |
| 845 | #endif |
| 846 | } |
| 847 | |
| 848 | boost::optional<bool> is_hdd(const char *file_path) |
| 849 | { |
| 850 | #ifdef __GLIBC__ |
| 851 | struct stat st; |
| 852 | std::string prefix; |
| 853 | if(stat(file_path, &st) == 0) |
| 854 | { |
| 855 | std::ostringstream s; |
| 856 | s << "/sys/dev/block/" << major(st.st_dev) << ":" << minor(st.st_dev); |
| 857 | prefix = s.str(); |
| 858 | } |
| 859 | else |
| 860 | { |
| 861 | return boost::none; |
| 862 | } |
| 863 | std::string attr_path = prefix + "/queue/rotational"; |
| 864 | std::ifstream f(attr_path, std::ios_base::in); |
| 865 | if(not f.is_open()) |
| 866 | { |
| 867 | attr_path = prefix + "/../queue/rotational"; |
| 868 | f.open(attr_path, std::ios_base::in); |
| 869 | if(not f.is_open()) |
| 870 | { |
| 871 | return boost::none; |
| 872 | } |
| 873 | } |
| 874 | unsigned short val = 0xdead; |
| 875 | f >> val; |
| 876 | if(not f.fail()) |
| 877 | { |
| 878 | return (val == 1); |
| 879 | } |
| 880 | return boost::none; |
| 881 | #else |
| 882 | return boost::none; |
| 883 | #endif |
| 884 | } |
| 885 | |
| 886 | namespace |
| 887 | { |
| 888 | boost::mutex max_concurrency_lock; |
| 889 | unsigned max_concurrency = boost::thread::hardware_concurrency(); |
| 890 | } |
| 891 | |
| 892 | void set_max_concurrency(unsigned n) |
| 893 | { |
| 894 | if (n < 1) |
| 895 | n = boost::thread::hardware_concurrency(); |
| 896 | unsigned hwc = boost::thread::hardware_concurrency(); |
| 897 | if (n > hwc) |
| 898 | n = hwc; |
| 899 | boost::lock_guard<boost::mutex> lock(max_concurrency_lock); |
| 900 | max_concurrency = n; |
| 901 | } |
| 902 | |
| 903 | unsigned get_max_concurrency() |
| 904 | { |
| 905 | boost::lock_guard<boost::mutex> lock(max_concurrency_lock); |
| 906 | return max_concurrency; |
| 907 | } |
| 908 | |
| 909 | bool is_privacy_preserving_network(const std::string &address) |
| 910 | { |
| 911 | if (boost::ends_with(address, ".onion")) |
| 912 | return true; |
| 913 | if (boost::ends_with(address, ".i2p")) |
| 914 | return true; |
| 915 | return false; |
| 916 | } |
| 917 | |
| 918 | bool is_local_address(const std::string &address) |
| 919 | { |
| 920 | // extract host |
| 921 | epee::net_utils::http::url_content u_c; |
| 922 | if (!epee::net_utils::parse_url(address, u_c)) |
| 923 | { |
| 924 | MWARNING("Failed to determine whether address '" << address << "' is local, assuming not"); |
| 925 | return false; |
| 926 | } |
| 927 | if (u_c.host.empty()) |
| 928 | { |
| 929 | MWARNING("Failed to determine whether address '" << address << "' is local, assuming not"); |
| 930 | return false; |
| 931 | } |
| 932 | |
| 933 | if (u_c.host == "localhost" || boost::ends_with(u_c.host, ".localhost")) { // RFC 6761 (6.3) |
| 934 | MDEBUG("Address '" << address << "' is local"); |
| 935 | return true; |
| 936 | } |
| 937 | |
| 938 | boost::system::error_code ec; |
| 939 | const auto parsed_ip = boost::asio::ip::make_address(u_c.host, ec); |
| 940 | if (ec) { |
| 941 | MDEBUG("Failed to parse '" << address << "' as IP address: " << ec.message() << ". Considering it not local"); |
| 942 | return false; |
| 943 | } |
| 944 | |
| 945 | if (parsed_ip.is_loopback()) |
| 946 | { |
| 947 | MDEBUG("Address '" << address << "' is local"); |
| 948 | return true; |
| 949 | } |
| 950 | |
| 951 | MDEBUG("Address '" << address << "' is not local"); |
| 952 | return false; |
| 953 | } |
| 954 | int vercmp(const char *v0, const char *v1) |
| 955 | { |
| 956 | std::vector<std::string> f0, f1; |
| 957 | boost::split(f0, v0, boost::is_any_of(".-")); |
| 958 | boost::split(f1, v1, boost::is_any_of(".-")); |
| 959 | for (size_t i = 0; i < std::max(f0.size(), f1.size()); ++i) { |
| 960 | if (i >= f0.size()) |
| 961 | return -1; |
| 962 | if (i >= f1.size()) |
| 963 | return 1; |
| 964 | int f0i = atoi(f0[i].c_str()), f1i = atoi(f1[i].c_str()); |
| 965 | int n = f0i - f1i; |
| 966 | if (n) |
| 967 | return n; |
| 968 | } |
| 969 | return 0; |
| 970 | } |
| 971 | |
| 972 | bool sha256sum(const uint8_t *data, size_t len, crypto::hash &hash) |
| 973 | { |
| 974 | return EVP_Digest(data, len, (unsigned char*) hash.data, NULL, EVP_sha256(), NULL) != 0; |
| 975 | } |
| 976 | |
| 977 | bool sha256sum(const std::string &filename, crypto::hash &hash) |
| 978 | { |
| 979 | if (!epee::file_io_utils::is_file_exist(filename)) |
| 980 | return false; |
| 981 | std::ifstream f; |
| 982 | f.exceptions(std::ifstream::failbit | std::ifstream::badbit); |
| 983 | f.open(filename, std::ios_base::binary | std::ios_base::in | std::ios::ate); |
| 984 | if (!f) |
| 985 | return false; |
| 986 | std::ifstream::pos_type file_size = f.tellg(); |
| 987 | std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)> ctx(EVP_MD_CTX_new(), &EVP_MD_CTX_free); |
| 988 | if (!EVP_DigestInit_ex(ctx.get(), EVP_sha256(), nullptr)) |
| 989 | return false; |
| 990 | size_t size_left = file_size; |
| 991 | f.seekg(0, std::ios::beg); |
| 992 | while (size_left) |
| 993 | { |
| 994 | char buf[4096]; |
| 995 | std::ifstream::pos_type read_size = size_left > sizeof(buf) ? sizeof(buf) : size_left; |
| 996 | f.read(buf, read_size); |
| 997 | if (!f || !f.good()) |
| 998 | return false; |
| 999 | if (!EVP_DigestUpdate(ctx.get(), buf, read_size)) |
| 1000 | return false; |
| 1001 | size_left -= read_size; |
| 1002 | } |
| 1003 | f.close(); |
| 1004 | if (!EVP_DigestFinal_ex(ctx.get(), (unsigned char*)hash.data, nullptr)) |
| 1005 | return false; |
| 1006 | return true; |
| 1007 | } |
| 1008 | |
| 1009 | boost::optional<std::pair<uint32_t, uint32_t>> parse_subaddress_lookahead(const std::string& str) |
| 1010 | { |
| 1011 | auto pos = str.find(":"); |
| 1012 | bool r = pos != std::string::npos; |
| 1013 | uint32_t major; |
| 1014 | r = r && epee::string_tools::get_xtype_from_string(major, str.substr(0, pos)); |
| 1015 | uint32_t minor; |
| 1016 | r = r && epee::string_tools::get_xtype_from_string(minor, str.substr(pos + 1)); |
| 1017 | if (r) |
| 1018 | { |
| 1019 | return std::make_pair(major, minor); |
| 1020 | } |
| 1021 | else |
| 1022 | { |
| 1023 | return {}; |
| 1024 | } |
| 1025 | } |
| 1026 | |
| 1027 | std::string glob_to_regex(const std::string &val) |
| 1028 | { |
| 1029 | std::string newval; |
| 1030 | |
| 1031 | bool escape = false; |
| 1032 | for (char c: val) |
| 1033 | { |
| 1034 | if (c == '*') |
| 1035 | newval += escape ? "*" : ".*", escape = false; |
| 1036 | else if (c == '?') |
| 1037 | newval += escape ? "?" : ".", escape = false; |
| 1038 | else if (c == '\\') |
| 1039 | newval += '\\', escape = !escape; |
| 1040 | else |
| 1041 | newval += c, escape = false; |
| 1042 | } |
| 1043 | return newval; |
| 1044 | } |
| 1045 | |
| 1046 | #ifdef _WIN32 |
| 1047 | std::string input_line_win() |
| 1048 | { |
| 1049 | HANDLE hConIn = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); |
| 1050 | DWORD oldMode; |
| 1051 | |
| 1052 | FlushConsoleInputBuffer(hConIn); |
| 1053 | GetConsoleMode(hConIn, &oldMode); |
| 1054 | SetConsoleMode(hConIn, ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT); |
| 1055 | |
| 1056 | wchar_t buffer[1024]; |
| 1057 | DWORD read; |
| 1058 | |
| 1059 | ReadConsoleW(hConIn, buffer, sizeof(buffer)/sizeof(wchar_t)-1, &read, nullptr); |
| 1060 | buffer[read] = 0; |
| 1061 | |
| 1062 | SetConsoleMode(hConIn, oldMode); |
| 1063 | CloseHandle(hConIn); |
| 1064 | |
| 1065 | int size_needed = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL); |
| 1066 | std::string buf(size_needed, '\0'); |
| 1067 | WideCharToMultiByte(CP_UTF8, 0, buffer, -1, &buf[0], size_needed, NULL, NULL); |
| 1068 | buf.pop_back(); //size_needed includes null that we needed to have space for |
| 1069 | return buf; |
| 1070 | } |
| 1071 | #endif |
| 1072 | |
| 1073 | void closefrom(int fd) |
| 1074 | { |
| 1075 | #if defined __FreeBSD__ || defined __OpenBSD__ || defined __NetBSD__ || defined __DragonFly__ |
| 1076 | ::closefrom(fd); |
| 1077 | #else |
| 1078 | #if defined __GLIBC__ |
| 1079 | const int sc_open_max = sysconf(_SC_OPEN_MAX); |
| 1080 | const int MAX_FDS = std::min(65536, sc_open_max); |
| 1081 | #else |
| 1082 | const int MAX_FDS = 65536; |
| 1083 | #endif |
| 1084 | while (fd < MAX_FDS) |
| 1085 | { |
| 1086 | close(fd); |
| 1087 | ++fd; |
| 1088 | } |
| 1089 | #endif |
| 1090 | } |
| 1091 | |
| 1092 | std::string get_human_readable_timestamp(uint64_t ts) |
| 1093 | { |
| 1094 | char buffer[64]; |
| 1095 | if (ts < 1234567890) |
| 1096 | return "<unknown>"; |
| 1097 | time_t tt = ts; |
| 1098 | struct tm tm; |
| 1099 | misc_utils::get_gmt_time(tt, tm); |
| 1100 | strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &tm); |
| 1101 | return std::string(buffer); |
| 1102 | } |
| 1103 | |
| 1104 | std::string get_human_readable_timespan(uint64_t seconds) |
| 1105 | { |
| 1106 | if (seconds < 60) |
| 1107 | return std::to_string(seconds) + " seconds"; |
| 1108 | std::stringstream ss; |
| 1109 | ss << std::fixed << std::setprecision(1); |
| 1110 | if (seconds < 3600) |
| 1111 | { |
| 1112 | ss << seconds / 60.f; |
| 1113 | return ss.str() + " minutes"; |
| 1114 | } |
| 1115 | if (seconds < 3600 * 24) |
| 1116 | { |
| 1117 | ss << seconds / 3600.f; |
| 1118 | return ss.str() + " hours"; |
| 1119 | } |
| 1120 | if (seconds < 3600 * 24 * 30.5f) |
| 1121 | { |
| 1122 | ss << seconds / (3600 * 24.f); |
| 1123 | return ss.str() + " days"; |
| 1124 | } |
| 1125 | if (seconds < 3600 * 24 * 365.25f) |
| 1126 | { |
| 1127 | ss << seconds / (3600 * 24 * 30.5f); |
| 1128 | return ss.str() + " months"; |
| 1129 | } |
| 1130 | if (seconds < 3600 * 24 * 365.25f * 100) |
| 1131 | { |
| 1132 | ss << seconds / (3600 * 24 * 365.25f); |
| 1133 | return ss.str() + " years"; |
| 1134 | } |
| 1135 | return "a long time"; |
| 1136 | } |
| 1137 | |
| 1138 | std::string get_human_readable_bytes(uint64_t bytes) |
| 1139 | { |
| 1140 | // Use 1024 for "kilo", 1024*1024 for "mega" and so on instead of the more modern and standard-conforming |
| 1141 | // 1000, 1000*1000 and so on, to be consistent with other Monero code that also uses base 2 units |
| 1142 | struct byte_map |
| 1143 | { |
| 1144 | const char* const format; |
| 1145 | const std::uint64_t bytes; |
| 1146 | }; |
| 1147 | |
| 1148 | static constexpr const byte_map sizes[] = |
| 1149 | { |
| 1150 | {"%.0f B", 1024}, |
| 1151 | {"%.2f kB", 1024 * 1024}, |
| 1152 | {"%.2f MB", std::uint64_t(1024) * 1024 * 1024}, |
| 1153 | {"%.2f GB", std::uint64_t(1024) * 1024 * 1024 * 1024}, |
| 1154 | {"%.2f TB", std::uint64_t(1024) * 1024 * 1024 * 1024 * 1024} |
| 1155 | }; |
| 1156 | |
| 1157 | struct bytes_less |
| 1158 | { |
| 1159 | bool operator()(const byte_map& lhs, const byte_map& rhs) const noexcept |
| 1160 | { |
| 1161 | return lhs.bytes < rhs.bytes; |
| 1162 | } |
| 1163 | }; |
| 1164 | |
| 1165 | const auto size = std::upper_bound( |
| 1166 | std::begin(sizes), std::end(sizes) - 1, byte_map{"", bytes}, bytes_less{} |
| 1167 | ); |
| 1168 | const std::uint64_t divisor = size->bytes / 1024; |
| 1169 | return (boost::format(size->format) % (double(bytes) / divisor)).str(); |
| 1170 | } |
| 1171 | |
| 1172 | void clear_screen() |
| 1173 | { |
| 1174 | std::cout << "\033[2K" << std::flush; // clear whole line |
| 1175 | std::cout << "\033c" << std::flush; // clear current screen and scrollback |
| 1176 | std::cout << "\033[2J" << std::flush; // clear current screen only, scrollback is still around |
| 1177 | std::cout << "\033[3J" << std::flush; // does nothing, should clear current screen and scrollback |
| 1178 | std::cout << "\033[1;1H" << std::flush; // move cursor top/left |
| 1179 | std::cout << "\r \r" << std::flush; // erase odd chars if the ANSI codes were printed raw |
| 1180 | #ifdef _WIN32 |
| 1181 | COORD coord{0, 0}; |
| 1182 | CONSOLE_SCREEN_BUFFER_INFO csbi; |
| 1183 | HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); |
| 1184 | if (GetConsoleScreenBufferInfo(h, &csbi)) |
| 1185 | { |
| 1186 | DWORD cbConSize = csbi.dwSize.X * csbi.dwSize.Y, w; |
| 1187 | FillConsoleOutputCharacter(h, (TCHAR)' ', cbConSize, coord, &w); |
| 1188 | if (GetConsoleScreenBufferInfo(h, &csbi)) |
| 1189 | FillConsoleOutputAttribute(h, csbi.wAttributes, cbConSize, coord, &w); |
| 1190 | SetConsoleCursorPosition(h, coord); |
| 1191 | } |
| 1192 | #endif |
| 1193 | } |
| 1194 | |
| 1195 | std::pair<std::string, size_t> get_string_prefix_by_width(const std::string &s, size_t columns) |
| 1196 | { |
| 1197 | std::string sc = ""; |
| 1198 | size_t avail = s.size(); |
| 1199 | const char *ptr = s.data(); |
| 1200 | wint_t cp = 0; |
| 1201 | int bytes = 1; |
| 1202 | size_t sw = 0; |
| 1203 | char wbuf[8], *wptr; |
| 1204 | while (avail--) |
| 1205 | { |
| 1206 | if ((*ptr & 0x80) == 0) |
| 1207 | { |
| 1208 | cp = *ptr++; |
| 1209 | bytes = 1; |
| 1210 | } |
| 1211 | else if ((*ptr & 0xe0) == 0xc0) |
| 1212 | { |
| 1213 | if (avail < 1) |
| 1214 | { |
| 1215 | MERROR("Invalid UTF-8"); |
| 1216 | return std::make_pair(s, s.size()); |
| 1217 | } |
| 1218 | cp = (*ptr++ & 0x1f) << 6; |
| 1219 | cp |= *ptr++ & 0x3f; |
| 1220 | --avail; |
| 1221 | bytes = 2; |
| 1222 | } |
| 1223 | else if ((*ptr & 0xf0) == 0xe0) |
| 1224 | { |
| 1225 | if (avail < 2) |
| 1226 | { |
| 1227 | MERROR("Invalid UTF-8"); |
| 1228 | return std::make_pair(s, s.size()); |
| 1229 | } |
| 1230 | cp = (*ptr++ & 0xf) << 12; |
| 1231 | cp |= (*ptr++ & 0x3f) << 6; |
| 1232 | cp |= *ptr++ & 0x3f; |
| 1233 | avail -= 2; |
| 1234 | bytes = 3; |
| 1235 | } |
| 1236 | else if ((*ptr & 0xf8) == 0xf0) |
| 1237 | { |
| 1238 | if (avail < 3) |
| 1239 | { |
| 1240 | MERROR("Invalid UTF-8"); |
| 1241 | return std::make_pair(s, s.size()); |
| 1242 | } |
| 1243 | cp = (*ptr++ & 0x7) << 18; |
| 1244 | cp |= (*ptr++ & 0x3f) << 12; |
| 1245 | cp |= (*ptr++ & 0x3f) << 6; |
| 1246 | cp |= *ptr++ & 0x3f; |
| 1247 | avail -= 3; |
| 1248 | bytes = 4; |
| 1249 | } |
| 1250 | else |
| 1251 | { |
| 1252 | MERROR("Invalid UTF-8"); |
| 1253 | return std::make_pair(s, s.size()); |
| 1254 | } |
| 1255 | |
| 1256 | wptr = wbuf; |
| 1257 | switch (bytes) |
| 1258 | { |
| 1259 | case 1: *wptr++ = cp; break; |
| 1260 | case 2: *wptr++ = 0xc0 | (cp >> 6); *wptr++ = 0x80 | (cp & 0x3f); break; |
| 1261 | case 3: *wptr++ = 0xe0 | (cp >> 12); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; |
| 1262 | case 4: *wptr++ = 0xf0 | (cp >> 18); *wptr++ = 0x80 | ((cp >> 12) & 0x3f); *wptr++ = 0x80 | ((cp >> 6) & 0x3f); *wptr++ = 0x80 | (cp & 0x3f); break; |
| 1263 | default: MERROR("Invalid UTF-8"); return std::make_pair(s, s.size()); |
| 1264 | } |
| 1265 | *wptr = 0; |
| 1266 | sc += std::string(wbuf, bytes); |
| 1267 | #ifdef _WIN32 |
| 1268 | int cpw = 1; // Guess who does not implement wcwidth |
| 1269 | #else |
| 1270 | int cpw = wcwidth(cp); |
| 1271 | #endif |
| 1272 | if (cpw > 0) |
| 1273 | { |
| 1274 | if (cpw > (int)columns) |
| 1275 | break; |
| 1276 | columns -= cpw; |
| 1277 | sw += cpw; |
| 1278 | } |
| 1279 | cp = 0; |
| 1280 | bytes = 1; |
| 1281 | } |
| 1282 | return std::make_pair(sc, sw); |
| 1283 | } |
| 1284 | |
| 1285 | size_t get_string_width(const std::string &s) |
| 1286 | { |
| 1287 | return get_string_prefix_by_width(s, 999999999).second; |
| 1288 | }; |
| 1289 | |
| 1290 | std::vector<std::pair<std::string, size_t>> split_line_by_width(const std::string &s, size_t columns) |
| 1291 | { |
| 1292 | std::vector<std::string> words; |
| 1293 | std::vector<std::pair<std::string, size_t>> lines; |
| 1294 | boost::split(words, s, boost::is_any_of(" "), boost::token_compress_on); |
| 1295 | // split large "words" |
| 1296 | for (size_t i = 0; i < words.size(); ++i) |
| 1297 | { |
| 1298 | for (;;) |
| 1299 | { |
| 1300 | std::string prefix = get_string_prefix_by_width(words[i], columns).first; |
| 1301 | if (prefix == words[i]) |
| 1302 | break; |
| 1303 | words[i] = words[i].substr(prefix.size()); |
| 1304 | words.insert(words.begin() + i, prefix); |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | lines.push_back(std::make_pair("", 0)); |
| 1309 | while (!words.empty()) |
| 1310 | { |
| 1311 | const size_t word_len = get_string_width(words.front()); |
| 1312 | size_t line_len = get_string_width(lines.back().first); |
| 1313 | if (line_len > 0 && line_len + 1 + word_len > columns) |
| 1314 | { |
| 1315 | lines.push_back(std::make_pair("", 0)); |
| 1316 | line_len = 0; |
| 1317 | } |
| 1318 | if (line_len > 0) |
| 1319 | { |
| 1320 | lines.back().first += " "; |
| 1321 | lines.back().second++; |
| 1322 | } |
| 1323 | lines.back().first += words.front(); |
| 1324 | lines.back().second += word_len; |
| 1325 | words.erase(words.begin()); |
| 1326 | } |
| 1327 | return lines; |
| 1328 | } |
| 1329 | |
| 1330 | // Calculate a "sync weight" over ranges of blocks in the blockchain, suitable for |
| 1331 | // calculating sync time estimates |
| 1332 | uint64_t cumulative_block_sync_weight(cryptonote::network_type nettype, uint64_t start_block, uint64_t num_blocks) |
| 1333 | { |
| 1334 | if (nettype != cryptonote::MAINNET) |
| 1335 | { |
| 1336 | // No detailed data available except for Mainnet: Give back the number of blocks |
| 1337 | // as a very simple and non-varying block sync weight for ranges of Testnet and |
| 1338 | // Stagenet blocks |
| 1339 | return num_blocks; |
| 1340 | } |
| 1341 | |
| 1342 | // The following is a table of average blocks sizes in bytes over the Monero mainnet |
| 1343 | // blockchain, where the block size is averaged over ranges of 10,000 blocks |
| 1344 | // (about 2 weeks worth of blocks each). |
| 1345 | // The first array entry of 442 thus means "The average byte size of the blocks |
| 1346 | // 0 .. 9,999 is 442". The info "block_size" from the "get_block_header_by_height" |
| 1347 | // RPC call was used for calculating this. This table (and the whole mechanism |
| 1348 | // of calculating a "sync weight") is most important when estimating times for |
| 1349 | // syncing from scratch. Without it the fast progress through the (in comparison) |
| 1350 | // rather small blocks in the early blockchain) would lead to vastly underestimated |
| 1351 | // total sync times. |
| 1352 | // It's no big problem for estimates that this table will, over time, and if not |
| 1353 | // updated, miss larger and larger parts at the top of the blockchain, as long |
| 1354 | // as block size averages there do not differ wildly. |
| 1355 | // Without time-consuming tests it's hard to say how much the estimates would |
| 1356 | // improve if one would not only take block sizes into account, but also varying |
| 1357 | // verification times i.e. the different CPU effort needed for the different |
| 1358 | // transaction types (pre / post RingCT, pre / post Bulletproofs). |
| 1359 | // Testnet and Stagenet are neglected here because of their much smaller |
| 1360 | // importance. |
| 1361 | static const uint32_t average_block_sizes[] = |
| 1362 | { |
| 1363 | 442, 1211, 1445, 1763, 2272, 8217, 5603, 9999, 16358, 10805, 5290, 4362, |
| 1364 | 4325, 5584, 4515, 5008, 4789, 5196, 7660, 3829, 6034, 2925, 3762, 2545, |
| 1365 | 2437, 2553, 2167, 2761, 2015, 1969, 2350, 1731, 2367, 2078, 2026, 3518, |
| 1366 | 2214, 1908, 1780, 1640, 1976, 1647, 1921, 1716, 1895, 2150, 2419, 2451, |
| 1367 | 2147, 2327, 2251, 1644, 1750, 1481, 1570, 1524, 1562, 1668, 1386, 1494, |
| 1368 | 1637, 1880, 1431, 1472, 1637, 1363, 1762, 1597, 1999, 1564, 1341, 1388, |
| 1369 | 1530, 1476, 1617, 1488, 1368, 1906, 1403, 1695, 1535, 1598, 1318, 1234, |
| 1370 | 1358, 1406, 1698, 1554, 1591, 1758, 1426, 2389, 1946, 1533, 1308, 2701, |
| 1371 | 1525, 1653, 3580, 1889, 2913, 8164, 5154, 3762, 3356, 4360, 3589, 4844, |
| 1372 | 4232, 3781, 3882, 5924, 10790, 7185, 7442, 8214, 8509, 7484, 6939, 7391, |
| 1373 | 8210, 15572, 39680, 44810, 53873, 54639, 68227, 63428, 62386, 68504, |
| 1374 | 83073, 103858, 117573, 98089, 96793, 102337, 94714, 129568, 251584, |
| 1375 | 132026, 94579, 94516, 95722, 106495, 121824, 153983, 162338, 136608, |
| 1376 | 137104, 109872, 91114, 84757, 96339, 74251, 94314, 143216, 155837, |
| 1377 | 129968, 120201, 109913, 101588, 97332, 104611, 95310, 93419, 113345, |
| 1378 | 100743, 92152, 57565, 22533, 37564, 21823, 19980, 18277, 18402, 14344, |
| 1379 | 12142, 15842, 13677, 17631, 18294, 22270, 41422, 39296, 36688, 33512, |
| 1380 | 33831, 27582, 22276, 27516, 27317, 25505, 24426, 20566, 23045, 26766, |
| 1381 | 28185, 26169, 27011, 28642, 34994, 34442, 30682, 34357, 31640, 41167, |
| 1382 | 41301, 48616, 51075, 55061, 49909, 44606, 47091, 53828, 42520, 39023, |
| 1383 | 55245, 56145, 51119, 60398, 71821, 48142, 60310, 56041, 54176, 66220, |
| 1384 | 56336, 55248, 56656, 63305, 54029, 77136, 71902, 71618, 83587, 81068, |
| 1385 | 69062, 54848, 53681, 53555, |
| 1386 | 50616 // Blocks 2,400,000 to 2,409,999 in July 2021 |
| 1387 | }; |
| 1388 | const uint64_t block_range_size = 10000; |
| 1389 | |
| 1390 | uint64_t num_block_sizes = sizeof(average_block_sizes) / sizeof(average_block_sizes[0]); |
| 1391 | uint64_t weight = 0; |
| 1392 | uint64_t table_index = start_block / block_range_size; |
| 1393 | for (;;) { |
| 1394 | if (num_blocks == 0) |
| 1395 | { |
| 1396 | break; |
| 1397 | } |
| 1398 | if (table_index >= num_block_sizes) |
| 1399 | { |
| 1400 | // Take all blocks beyond our table as having the size of the blocks |
| 1401 | // in the last table entry i.e. in the most recent known block range |
| 1402 | weight += num_blocks * average_block_sizes[num_block_sizes - 1]; |
| 1403 | break; |
| 1404 | } |
| 1405 | uint64_t portion_size = std::min(num_blocks, block_range_size - start_block % block_range_size); |
| 1406 | weight += portion_size * average_block_sizes[table_index]; |
| 1407 | table_index++; |
| 1408 | num_blocks -= portion_size; |
| 1409 | start_block += portion_size; |
| 1410 | } |
| 1411 | return weight; |
| 1412 | } |
| 1413 | |
| 1414 | std::vector<std::pair<std::string, size_t>> split_string_by_width(const std::string &s, size_t columns) |
| 1415 | { |
| 1416 | std::vector<std::string> lines; |
| 1417 | std::vector<std::pair<std::string, size_t>> all_lines; |
| 1418 | boost::split(lines, s, boost::is_any_of("\n"), boost::token_compress_on); |
| 1419 | for (const auto &e: lines) |
| 1420 | { |
| 1421 | std::vector<std::pair<std::string, size_t>> new_lines = split_line_by_width(e, columns); |
| 1422 | for (auto &l: new_lines) |
| 1423 | all_lines.push_back(std::move(l)); |
| 1424 | } |
| 1425 | return all_lines; |
| 1426 | } |
| 1427 | } |