1 // Copyright (C) 2007-2021 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>
33 #include <cstdlib> // getenv, system
35 #include <boost/filesystem.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 =
66 static LibHandle theLibraryHandle = nullptr; //!< handle of a loaded library
68 const char* theEnvVar = "SALOME_MG_KEYGEN_LIB_PATH"; /* var specifies either full file name
69 of libSalomeMeshGemsKeyGenerator or
70 URL to download the library from */
72 const char* theTmpEnvVar = "SALOME_TMP_DIR"; // directory to download the library to
74 //-----------------------------------------------------------------------------------
76 * \brief Remove library file at destruction in case if it was downloaded from server
78 //-----------------------------------------------------------------------------------
82 std::string _name; // full file name
85 LibraryFile(): _isURL( false ) {}
91 if ( theLibraryHandle )
93 UnLoadLib( theLibraryHandle );
94 theLibraryHandle = nullptr;
97 std::string tmpDir; // tmp dir that should not be removed
98 if ( const char* libPath = getenv( theTmpEnvVar ))
101 while (( !tmpDir.empty() ) &&
102 ( tmpDir.back() == '/' || tmpDir.back() == '\\' ))
106 while ( SMESH_File( _name ).remove() )
108 size_t length = _name.size();
109 _name = boofs::path( _name ).parent_path().string(); // goto parent directory
110 if ( _name.size() == length )
111 break; // no more parents
113 if ( _name == tmpDir )
114 break; // don't remove tmp dir
116 if ( !Kernel_Utils::IsEmptyDir( _name ))
124 //================================================================================
126 * \brief Retrieve description of the last error
127 * \param [out] error - return the description
128 * \return bool - true if the description found
130 //================================================================================
132 bool getLastError( std::string& error )
136 if ( const char* text = dlerror() )
145 DWORD dw = GetLastError();
147 DWORD msgLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
150 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
156 error = (char*) cstr;
165 //================================================================================
167 * \brief Adjust file extension according to the platform
169 //================================================================================
171 bool setExtension( std::string& fileName, std::string& error )
173 if ( fileName.empty() )
175 error = "Library file name is empty";
179 std::string ext = ".dll";
180 #elif defined(__APPLE__)
181 std::string ext = ".dylib";
183 std::string ext = ".so";
186 fileName = fileName.substr( 0, fileName.find_last_of('.')) + ext;
190 //================================================================================
192 * \brief Check if library file name looks like an URL
193 * \param [in,out] libraryFile - holds file name and returns result in _isURL member field
194 * \return bool - true if the file name looks like an URL
196 //================================================================================
198 bool isURL( LibraryFile & libraryFile )
201 enum { SCHEME = 2, AUTHORITY = 4, PATH = 5 }; // sub-strings
202 std::regex urlRegex ( R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
203 std::regex::extended );
204 std::smatch matchResult;
206 libraryFile._isURL = false;
207 if ( std::regex_match( libraryFile._name, matchResult, urlRegex ))
208 libraryFile._isURL = ( !matchResult.str( SCHEME ).empty() &&
209 !matchResult.str( AUTHORITY ).empty() &&
210 !matchResult.str( PATH ).empty() );
212 if(libraryFile._isURL)
215 enum { HOST = 2, PORT = 3, PATH = 4 }; // sub-strings
216 std::regex urlRegex ( R"(^(([^:\/?#]+):)?([^/]+)?(/[^#]*))",
217 std::regex::extended );
218 std::smatch matchResult;
220 libraryFile._isURL = false;
221 if ( std::regex_match( libraryFile._name, matchResult, urlRegex ))
222 libraryFile._isURL = ( !matchResult.str( HOST ).empty() &&
223 !matchResult.str( PORT ).empty() &&
224 !matchResult.str( PATH ).empty() );
226 return libraryFile._isURL;
229 //================================================================================
231 * \brief Download libraryFile._name URL to SALOME_TMP_DIR
232 * \param [in,out] libraryFile - holds the URL and returns name of a downloaded file
233 * \param [out] error - return error description
234 * \return bool - is a success
236 //================================================================================
238 bool downloadLib( LibraryFile& libraryFile, std::string & error )
240 // check if can write into SALOME_TMP_DIR
242 std::string tmpDir = Kernel_Utils::GetTmpDirByEnv( theTmpEnvVar );
243 if ( tmpDir.empty() ||
244 !Kernel_Utils::IsExists( tmpDir ))
246 error = "Can't download " + libraryFile._name + " as SALOME_TMP_DIR is not correctly set";
249 if ( !Kernel_Utils::IsWritable( tmpDir ))
251 error = "Can't download " + libraryFile._name + " as '" + tmpDir + "' is not writable. "
252 "Check SALOME_TMP_DIR environment variable";
258 std::string url = libraryFile._name;
262 std::string outFile = tmpDir + "libMeshGemsKeyGenerator.dll";
264 // use wget (== Invoke-WebRequest) PowerShell command available since Windows 7
265 std::string psCmd = "wget -Uri " + url + " -OutFile " + outFile;
266 std::string cmd = "start powershell.exe " + psCmd;
270 std::string outFile = tmpDir + "libMeshGemsKeyGenerator.so";
272 std::string cmd = "wget " + url + " -O " + outFile;
276 if ( Kernel_Utils::IsExists( outFile )) // remove existing file
278 SMESH_File lib( outFile, /*open=*/false );
286 system( cmd.c_str() ); // download
288 SMESH_File resultFile( outFile, /*open=*/false );
289 bool ok = ( resultFile.exists() && resultFile.size() > 0 );
292 libraryFile._name = outFile;
297 //================================================================================
299 * \brief Load libMeshGemsKeyGenerator.so
300 * \param [out] error - return error description
301 * \param [out] libraryFile - return library file name and _isURL flag
302 * \return bool - is a success
304 //================================================================================
306 bool loadLibrary( std::string& error, LibraryFile& libraryFile )
308 if ( theLibraryHandle )
311 const char* libPath = getenv( theEnvVar );
314 error = SMESH_Comment( "Environment variable ") << theEnvVar << " is not set";
318 libraryFile._name = libPath;
319 // if ( !setExtension( libraryFile._name, error )) // is it necessary?
322 if ( isURL( libraryFile ))
324 if ( !downloadLib( libraryFile, error ))
326 // try to fix extension
327 std::string url = libraryFile._name;
328 if ( !setExtension( libraryFile._name, error ))
330 if ( url == libraryFile._name )
331 return false; // extension not changed
333 if ( !downloadLib( libraryFile, error ))
338 #if defined( WIN32 ) && defined( UNICODE )
339 std::wstring encodePath = Kernel_Utils::utf8_decode_s( libraryFile._name );
340 const wchar_t* path = encodePath.c_str();
342 const char* path = libraryFile._name.c_str();
345 theLibraryHandle = LoadLib( path );
346 if ( !theLibraryHandle )
348 if ( ! getLastError( error ))
349 error = "Can't load library '" + libraryFile._name + "'";
352 return theLibraryHandle;
355 } // anonymous namespace
358 namespace SMESHUtils_MGLicenseKeyGen // API implementation
360 //================================================================================
363 * \param [in] meshgems_cad - pointer to a MG CAD object (meshgems_cad_t)
364 * \param [out] error - return error description
365 * \return bool - is a success
367 //================================================================================
369 bool SignCAD( void* meshgems_cad, std::string& error )
371 LibraryFile libraryFile;
372 if ( !loadLibrary( error, libraryFile ))
375 typedef bool (*SignFun)(void* );
376 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignCAD" );
379 if ( ! getLastError( error ))
380 error = SMESH_Comment( "Can't find symbol 'SignCAD' in '") << getenv( theEnvVar ) << "'";
387 ok = signFun( meshgems_cad );
389 SMESH_CATCH( SMESH::returnError );
391 if ( !error.empty() )
394 error = "SignCAD() failed (located in '" + libraryFile._name + "')";
399 //================================================================================
402 * \param [in] meshgems_mesh - pointer to a MG mesh (meshgems_mesh_t)
403 * \param [out] error - return error description
404 * \return bool - is a success
406 //================================================================================
408 bool SignMesh( void* meshgems_mesh, std::string& error )
410 LibraryFile libraryFile;
411 if ( !loadLibrary( error, libraryFile ))
414 typedef bool (*SignFun)(void* );
415 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignMesh" );
418 if ( ! getLastError( error ))
419 error = SMESH_Comment( "Can't find symbol 'SignMesh' in '") << getenv( theEnvVar ) << "'";
425 ok = signFun( meshgems_mesh );
427 SMESH_CATCH( SMESH::returnError );
429 if ( !error.empty() )
432 error = "SignMesh() failed (located in '" + libraryFile._name + "')";
437 //================================================================================
439 * \brief Return a license key to pass as argument to a MG mesher executable
440 * \param [in] gmfFile - path to an input mesh file
441 * \param [in] nb* - nb of entities in the input mesh
442 * \param [out] error - return error description
443 * \return std::string - the key
445 //================================================================================
447 std::string GetKey(const std::string& gmfFile,
455 LibraryFile libraryFile;
456 if ( !loadLibrary( error, libraryFile ))
459 typedef std::string (*GetKeyFun)(std::string const &, int, int, int, int );
460 GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
463 if ( ! getLastError( error ))
464 error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
466 key = keyFun( gmfFile, nbVertex, nbEdge, nbFace, nbVol );
469 error = "GetKey() failed (located in '" + libraryFile._name + "')";
474 //================================================================================
476 * \brief Return false if libMeshGemsKeyGenerator.so is not functional
477 * \param [out] error - return error description
478 * \return bool - is a success
480 //================================================================================
482 bool CheckKeyGenLibrary( std::string& error )
484 return !GetKey("",4,0,2,0,error ).empty();
487 //================================================================================
489 * \brief Return KeyGenerator library name
491 //================================================================================
493 std::string GetLibraryName()
495 std::string libName, error;
496 if ( const char* libPath = getenv( theEnvVar ))
498 libName = Kernel_Utils::GetBaseName( libPath );
502 libName = "libSalomeMeshGemsKeyGenerator";
504 setExtension( libName, error );