1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 // File : SMESHUtils_MGLicenseKeyGen.cxx
20 // Created : Sat Jul 31 18:54:16 2021
21 // Author : Edward AGAPOV (OCC)
23 #include "SMESH_MGLicenseKeyGen.hxx"
25 #include "SMESH_Comment.hxx"
26 #include "SMESH_File.hxx"
27 #include "SMESH_TryCatch.hxx"
29 #include <Basics_DirUtils.hxx>
30 #include <Basics_Utils.hxx>
32 #include <cstdlib> // getenv, system
34 #include <boost/filesystem.hpp>
35 #include <boost/regex.hpp>
36 namespace boofs = boost::filesystem;
43 # define LibHandle HMODULE
44 # define LoadLib( name ) LoadLibrary( name )
45 # define GetProc GetProcAddress
46 # define UnLoadLib( handle ) FreeLibrary( handle );
52 # define LibHandle void*
53 # define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
54 # define GetProc dlsym
55 # define UnLoadLib( handle ) dlclose( handle );
59 // to retrieve description of exception caught by SMESH_TRY
61 #define SMESH_CAUGHT error =
63 constexpr char MESHGEMS_OLD_STYLE[] = "MESHGEMS_OLD_STYLE";
64 constexpr char SPATIAL_LICENSE[] = "SPATIAL_LICENSE";
69 static LibHandle theLibraryHandle = nullptr; //!< handle of a loaded library
71 const char* theEnvVar = "SALOME_MG_KEYGEN_LIB_PATH"; /* var specifies either full file name
72 of libSalomeMeshGemsKeyGenerator or
73 URL to download the library from */
75 const char* theTmpEnvVar = "SALOME_TMP_DIR"; // directory to download the library to
77 //-----------------------------------------------------------------------------------
79 * \brief Remove library file at destruction in case if it was downloaded from server
81 //-----------------------------------------------------------------------------------
85 std::string _name; // full file name
88 LibraryFile(): _isURL( false ) {}
94 if ( theLibraryHandle )
96 UnLoadLib( theLibraryHandle );
97 theLibraryHandle = nullptr;
100 std::string tmpDir; // tmp dir that should not be removed
101 if ( const char* libPath = getenv( theTmpEnvVar ))
104 while (( !tmpDir.empty() ) &&
105 ( tmpDir.back() == '/' || tmpDir.back() == '\\' ))
109 while ( SMESH_File( _name ).remove() )
111 size_t length = _name.size();
112 _name = boofs::path( _name ).parent_path().string(); // goto parent directory
113 if ( _name.size() == length )
114 break; // no more parents
116 if ( _name == tmpDir )
117 break; // don't remove tmp dir
119 if ( !Kernel_Utils::IsEmptyDir( _name ))
127 //================================================================================
129 * \brief Retrieve description of the last error
130 * \param [out] error - return the description
131 * \return bool - true if the description found
133 //================================================================================
135 bool getLastError( std::string& error )
139 if ( const char* text = dlerror() )
148 DWORD dw = GetLastError();
150 DWORD msgLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
153 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
159 # if defined( UNICODE )
160 error = Kernel_Utils::encode_s((wchar_t*)cstr);
172 //================================================================================
174 * \brief Adjust file extension according to the platform
176 //================================================================================
178 bool setExtension( std::string& fileName, std::string& error )
180 if ( fileName.empty() )
182 error = "Library file name is empty";
186 std::string ext = ".dll";
187 #elif defined(__APPLE__)
188 std::string ext = ".dylib";
190 std::string ext = ".so";
193 fileName = fileName.substr( 0, fileName.find_last_of('.')) + ext;
197 //================================================================================
199 * \brief Check if library file name looks like an URL
200 * \param [in,out] libraryFile - holds file name and returns result in _isURL member field
201 * \return bool - true if the file name looks like an URL
203 //================================================================================
205 bool isURL( LibraryFile & libraryFile )
208 enum { SCHEME = 2, AUTHORITY = 4, PATH = 5 }; // sub-strings
209 boost::regex urlRegex ( R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
210 boost::regex::extended );
211 boost::smatch matchResult;
213 libraryFile._isURL = false;
214 if ( boost::regex_match( libraryFile._name, matchResult, urlRegex ))
215 libraryFile._isURL = ( !matchResult.str( SCHEME ).empty() &&
216 !matchResult.str( AUTHORITY ).empty() &&
217 !matchResult.str( PATH ).empty() );
219 if(libraryFile._isURL)
222 enum { HOST = 2, PORT = 3, PATH = 4 }; // sub-strings
223 boost::regex urlRegex ( R"(^(([^:\/?#]+):)?([^/]+)?(/[^#]*))",
224 boost::regex::extended );
225 boost::smatch matchResult;
227 libraryFile._isURL = false;
228 if ( boost::regex_match( libraryFile._name, matchResult, urlRegex ))
229 libraryFile._isURL = ( !matchResult.str( HOST ).empty() &&
230 !matchResult.str( PORT ).empty() &&
231 !matchResult.str( PATH ).empty() );
233 return libraryFile._isURL;
236 //================================================================================
238 * \brief Download libraryFile._name URL to SALOME_TMP_DIR
239 * \param [in,out] libraryFile - holds the URL and returns name of a downloaded file
240 * \param [out] error - return error description
241 * \return bool - is a success
243 //================================================================================
245 bool downloadLib( LibraryFile& libraryFile, std::string & error )
247 // check if can write into SALOME_TMP_DIR
249 std::string tmpDir = Kernel_Utils::GetTmpDirByEnv( theTmpEnvVar );
250 if ( tmpDir.empty() ||
251 !Kernel_Utils::IsExists( tmpDir ))
253 error = "Can't download " + libraryFile._name + " as SALOME_TMP_DIR is not correctly set";
256 if ( !Kernel_Utils::IsWritable( tmpDir ))
258 error = "Can't download " + libraryFile._name + " as '" + tmpDir + "' is not writable. "
259 "Check SALOME_TMP_DIR environment variable";
265 std::string url = libraryFile._name;
269 std::string outFile = tmpDir + "MeshGemsKeyGenerator.dll";
271 // use wget (== Invoke-WebRequest) PowerShell command available since Windows 7
272 std::string psCmd = "wget -Uri " + url + " -OutFile " + outFile;
273 std::string cmd = "powershell.exe " + psCmd;
277 std::string outFile = tmpDir + "libMeshGemsKeyGenerator.so";
279 std::string cmd = "smesh_wget.py " + url + " -O " + outFile;
283 if ( Kernel_Utils::IsExists( outFile )) // remove existing file
285 SMESH_File lib( outFile, /*open=*/false );
295 std::string redirect = tmpDir + "redirect.out";
296 std::ostringstream oss;
297 oss << cmd << " " << redirect;
301 system( cmd.c_str() ); // download
305 std::ifstream infile(redirect);
306 infile.seekg(0, std::ios::end);
307 size_t length = infile.tellg();
308 infile.seekg(0, std::ios::beg);
309 std::unique_ptr<char []> buffer(new char[length+1]);
310 buffer[length] = '\0';
311 infile.read(const_cast<char *>( buffer.get() ),length);
313 MESSAGE( buffer.get() );
316 SMESH_File redirectFile( redirect, /*open=*/false );
317 redirectFile.remove();
321 SMESH_File resultFile( outFile, /*open=*/false );
322 bool ok = ( resultFile.exists() && resultFile.size() > 0 );
325 libraryFile._name = outFile;
327 error = "Can't download file " + url;
332 //================================================================================
334 * \brief Load libMeshGemsKeyGenerator.so
335 * \param [out] error - return error description
336 * \param [out] libraryFile - return library file name and _isURL flag
337 * \return bool - is a success
339 //================================================================================
341 bool loadLibrary( std::string& error, LibraryFile& libraryFile )
343 if ( theLibraryHandle )
346 const char* libPath = getenv( theEnvVar );
349 error = SMESH_Comment( "Environment variable ") << theEnvVar << " is not set";
353 libraryFile._name = libPath;
354 // if ( !setExtension( libraryFile._name, error )) // is it necessary?
357 if ( isURL( libraryFile ))
359 if ( !downloadLib( libraryFile, error ))
361 // try to fix extension
362 std::string url = libraryFile._name;
363 if ( !setExtension( libraryFile._name, error ))
365 if ( url == libraryFile._name )
366 return false; // extension not changed
368 if ( !downloadLib( libraryFile, error ))
373 #if defined( WIN32 ) && defined( UNICODE )
374 std::wstring encodePath = Kernel_Utils::utf8_decode_s( libraryFile._name );
375 const wchar_t* path = encodePath.c_str();
377 const char* path = libraryFile._name.c_str();
380 theLibraryHandle = LoadLib( path );
381 if ( !theLibraryHandle )
383 if ( ! getLastError( error ))
384 error = "Can't load library '" + libraryFile._name + "'";
387 return theLibraryHandle;
390 } // anonymous namespace
393 namespace SMESHUtils_MGLicenseKeyGen // API implementation
395 //================================================================================
398 * \param [in] meshgems_cad - pointer to a MG CAD object (meshgems_cad_t)
399 * \param [out] error - return error description
400 * \return bool - is a success
402 //================================================================================
404 bool SignCAD_After( void* meshgems_cad, std::string& error )
406 LibraryFile libraryFile;
407 if ( !loadLibrary( error, libraryFile ))
411 typedef bool (*SignFun)(void* );
412 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignCAD" );
415 if ( ! getLastError( error ))
416 error = SMESH_Comment( "Can't find symbol 'SignCAD' in '") << getenv( theEnvVar ) << "'";
422 ok = signFun( meshgems_cad );
424 SMESH_CATCH( SMESH::returnError );
426 if ( !error.empty() )
429 error = "SignCAD() failed (located in '" + libraryFile._name + "')";
434 bool SignCAD( void* meshgems_cad, std::string& error )
436 const char *meshGemsOldStyleEnvVar( getenv( MESHGEMS_OLD_STYLE ) );
437 if ( !meshGemsOldStyleEnvVar || strlen(meshGemsOldStyleEnvVar) == 0 )
438 return SignCAD_After(meshgems_cad, error);
443 //================================================================================
446 * \param [in] meshgems_mesh - pointer to a MG mesh (meshgems_mesh_t)
447 * \param [out] error - return error description
448 * \return bool - is a success
450 //================================================================================
452 bool SignMesh_After( void* meshgems_mesh, std::string& error )
454 LibraryFile libraryFile;
455 if ( !loadLibrary( error, libraryFile ))
459 typedef bool (*SignFun)(void* );
460 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignMesh" );
463 if ( ! getLastError( error ))
464 error = SMESH_Comment( "Can't find symbol 'SignMesh' in '") << getenv( theEnvVar ) << "'";
470 ok = signFun( meshgems_mesh );
472 SMESH_CATCH( SMESH::returnError );
474 if ( !error.empty() )
477 error = "SignMesh() failed (located in '" + libraryFile._name + "')";
482 bool SignMesh( void* meshgems_mesh, std::string& error )
484 const char *meshGemsOldStyleEnvVar( getenv( MESHGEMS_OLD_STYLE ) );
485 if ( !meshGemsOldStyleEnvVar || strlen(meshGemsOldStyleEnvVar) == 0 )
486 // sign the mesh (MG 2.13 and 2.14)
487 return SignMesh_After(meshgems_mesh, error);
489 // use DLIM8 server (nothing to do here)
493 //================================================================================
495 * \brief Return a license key to pass as argument to a MG mesher executable
496 * \param [in] gmfFile - path to an input mesh file
497 * \param [in] nb* - nb of entities in the input mesh
498 * \param [out] error - return error description
499 * \return std::string - the key
501 //================================================================================
503 std::string GetKey_After(const std::string& gmfFile,
511 LibraryFile libraryFile;
512 if ( !loadLibrary( error, libraryFile ))
515 typedef std::string (*GetKeyFun)(std::string const &, int, int, int, int );
516 GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
519 if ( ! getLastError( error ))
520 error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
524 key = keyFun( gmfFile, nbVertex, nbEdge, nbFace, nbVol );
527 error = "GetKey() failed (located in '" + libraryFile._name + "')";
532 //================================================================================
534 * \brief Return a license key to pass as argument to a MG mesher executable (>2.15)
535 * \param [out] error - return error description
536 * \return std::string - the key
538 //================================================================================
540 std::string GetKey_After(std::string& error)
543 LibraryFile libraryFile;
544 if ( !loadLibrary( error, libraryFile ))
547 typedef std::string (*GetKeyFun)();
548 GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
551 if ( ! getLastError( error ))
552 error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
559 error = "GetKey() failed (located in '" + libraryFile._name + "')";
565 //================================================================================
567 * \brief Get MeshGems version from the keygen library and meshgems built-in functions
568 * \param [out] error - return error description
569 * \return int - the version
571 //================================================================================
572 int GetMGVersionHex(std::string& error)
576 LibraryFile libraryFile;
577 if ( !loadLibrary( error, libraryFile ))
580 typedef int (*GetKeyFun)();
581 GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "meshgems_core_get_version_minor" );
584 if ( ! getLastError( error ))
585 error = SMESH_Comment( "Can't find symbol 'meshgems_core_get_version_minor' in '") << getenv( theEnvVar ) << "'";
592 error = "meshgems_core_get_version_minor() failed (located in '" + libraryFile._name + "')";
594 MESSAGE("meshgems_core_get_version_minor: " << v_min);
599 typedef int (*GetKeyFun)();
600 keyFun = (GetKeyFun) GetProc( theLibraryHandle, "meshgems_core_get_version_major" );
603 if ( ! getLastError( error ))
604 error = SMESH_Comment( "Can't find symbol 'meshgems_core_get_version_major' in '") << getenv( theEnvVar ) << "'";
611 error = "meshgems_core_get_version_major() failed (located in '" + libraryFile._name + "')";
613 MESSAGE("meshgems_core_get_version_major: " << v_maj);
618 typedef int (*GetKeyFun)();
619 keyFun = (GetKeyFun) GetProc( theLibraryHandle, "meshgems_core_get_version_patch" );
622 if ( ! getLastError( error ))
623 error = SMESH_Comment( "Can't find symbol 'meshgems_core_get_version_patch' in '") << getenv( theEnvVar ) << "'";
630 error = "meshgems_core_get_version_patch() failed (located in '" + libraryFile._name + "')";
632 MESSAGE("meshgems_core_get_version_patch: " << v_patch );
634 int v_hex = (v_maj << 16 | v_min << 8 | v_patch);
636 MESSAGE("v_hex: " << v_hex);
641 //================================================================================
643 * \brief Guess if the Spatial license is needed (if MeshGems is > 2.15.0)
644 * \param [out] error - return error description
645 * \return bool - true if MeshGems is > 2.15.0
647 //================================================================================
648 bool NeedsMGSpatialEnvLicense(std::string& error)
650 // if MeshGems version is > 2.15.0, need to set SPATIAL_LICENSE
651 int v_hex = GetMGVersionHex(error);
652 bool ok = (v_hex > MESHGEMS_215);
654 MESSAGE("MeshGems version is > 2.15.0, need to set SPATIAL_LICENSE");
658 //================================================================================
660 * \brief Set the SPATIAL_LICENSE environment variable
661 * \param [out] error - return error description
662 * \return bool - true in case of success
664 //================================================================================
665 bool SetMGSpatialEnvLicense(std::string& error)
668 std::string key = GetKey(error);
670 ok = setenv(SPATIAL_LICENSE, key.c_str(), 0); // 0 means do not overwrite
672 ok = Kernel_Utils::setenv(SPATIAL_LICENSE, key.c_str(), 0 );
674 MESSAGE("Set SPATIAL_LICENSE");
678 //================================================================================
680 * \brief Get the license key from libMeshGemsKeyGenerator.so or $SPATIAL_LICENSE
681 * Called by plugins calling MG products as executables.
682 * If MESHGEMS_OLD_STYLE is set, return "0", to use old DLIM8 server license
683 * instead of the key.
684 * \param [in] gmfFile - path to an input mesh file
685 * \param [in] nb* - nb of entities in the input mesh
686 * \param [out] error - return error description
687 * \return std::string - the key
689 //================================================================================
690 std::string GetKey(const std::string& gmfFile,
697 // default key if MESHGEMS_OLD_STYLE or SPATIAL_LICENSE is set
698 std::string key("0");
699 const char *meshGemsOldStyleEnvVar( getenv( MESHGEMS_OLD_STYLE ) );
700 if ( !meshGemsOldStyleEnvVar || strlen(meshGemsOldStyleEnvVar) == 0 )
702 const char *spatialLicenseEnvVar( getenv( SPATIAL_LICENSE ) );
703 if ( !spatialLicenseEnvVar || strlen(spatialLicenseEnvVar) == 0 )
705 if (NeedsMGSpatialEnvLicense(error))
707 // if MG version > 2.15, set environment license, don't return it as a key
708 // otherwise it will be printed in the command line
709 MESSAGE("SPATIAL_LICENSE not in env => we add it from MGKeygen .so");
710 SetMGSpatialEnvLicense(error);
714 // generate the key from the mesh info (MG 2.13 and 2.14)
715 MESSAGE("MG < 2.15 => get the key from MGKeygen .so and this mesh info");
716 key = GetKey_After(gmfFile,nbVertex,nbEdge,nbFace,nbVol,error);
720 MESSAGE("SPATIAL_LICENSE already in env => we use it");
727 //================================================================================
729 * \brief Get the license key from libMeshGemsKeyGenerator.so or $SPATIAL_LICENSE
730 * Called for MG 2.15 by CADSurf and MG plugins calling MG products as library,
731 * i.e. compiled as library with -DSALOME_USE_MG_LIBS=ON
732 * \param [out] error - return error description
733 * \return std::string - the key
735 //================================================================================
736 std::string GetKey(std::string& error)
738 // default key if not found in .so or in SPATIAL_LICENSE
739 std::string key("0");
740 const char *meshGemsOldStyleEnvVar( getenv( MESHGEMS_OLD_STYLE ) );
741 if ( !meshGemsOldStyleEnvVar || strlen(meshGemsOldStyleEnvVar) == 0 ){
742 const char *spatialLicenseEnvVar( getenv( SPATIAL_LICENSE ) );
743 if ( !spatialLicenseEnvVar || strlen(spatialLicenseEnvVar) == 0 )
745 MESSAGE("SPATIAL_LICENSE not in env => we add it from MGKeygen .so");
746 // use new style, i.e. key in a library
747 key = GetKey_After(error);
751 MESSAGE("SPATIAL_LICENSE already in env => we use it");
752 key = std::string(spatialLicenseEnvVar);
760 //================================================================================
762 * \brief Return false if libMeshGemsKeyGenerator.so is not functional
763 * \param [out] error - return error description
764 * \return bool - is a success
766 //================================================================================
768 bool CheckKeyGenLibrary( std::string& error )
770 return !GetKey("",4,0,2,0,error ).empty();
773 //================================================================================
775 * \brief Return KeyGenerator library name
777 //================================================================================
779 std::string GetLibraryName()
781 std::string libName, error;
782 if ( const char* libPath = getenv( theEnvVar ))
784 libName = Kernel_Utils::GetBaseName( libPath );
788 libName = "libSalomeMeshGemsKeyGenerator";
790 setExtension( libName, error );