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 # if defined( UNICODE )
157 error = Kernel_Utils::encode_s((wchar_t*)cstr);
169 //================================================================================
171 * \brief Adjust file extension according to the platform
173 //================================================================================
175 bool setExtension( std::string& fileName, std::string& error )
177 if ( fileName.empty() )
179 error = "Library file name is empty";
183 std::string ext = ".dll";
184 #elif defined(__APPLE__)
185 std::string ext = ".dylib";
187 std::string ext = ".so";
190 fileName = fileName.substr( 0, fileName.find_last_of('.')) + ext;
194 //================================================================================
196 * \brief Check if library file name looks like an URL
197 * \param [in,out] libraryFile - holds file name and returns result in _isURL member field
198 * \return bool - true if the file name looks like an URL
200 //================================================================================
202 bool isURL( LibraryFile & libraryFile )
204 enum { SCHEME = 2, AUTHORITY = 4, PATH = 5 }; // sub-strings
205 std::regex urlRegex ( R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
206 std::regex::extended );
207 std::smatch matchResult;
209 libraryFile._isURL = false;
210 if ( std::regex_match( libraryFile._name, matchResult, urlRegex ))
211 libraryFile._isURL = ( !matchResult.str( SCHEME ).empty() &&
212 !matchResult.str( AUTHORITY ).empty() &&
213 !matchResult.str( PATH ).empty() );
215 return libraryFile._isURL;
218 //================================================================================
220 * \brief Download libraryFile._name URL to SALOME_TMP_DIR
221 * \param [in,out] libraryFile - holds the URL and returns name of a downloaded file
222 * \param [out] error - return error description
223 * \return bool - is a success
225 //================================================================================
227 bool downloadLib( LibraryFile& libraryFile, std::string & error )
229 // check if can write into SALOME_TMP_DIR
231 std::string tmpDir = Kernel_Utils::GetTmpDirByEnv( theTmpEnvVar );
232 if ( tmpDir.empty() ||
233 !Kernel_Utils::IsExists( tmpDir ))
235 error = "Can't download " + libraryFile._name + " as SALOME_TMP_DIR is not correctly set";
238 if ( !Kernel_Utils::IsWritable( tmpDir ))
240 error = "Can't download " + libraryFile._name + " as '" + tmpDir + "' is not writable. "
241 "Check SALOME_TMP_DIR environment variable";
247 std::string url = libraryFile._name;
251 std::string outFile = tmpDir + "MeshGemsKeyGenerator.dll";
253 // use wget (== Invoke-WebRequest) PowerShell command available since Windows 7
254 std::string psCmd = "wget -Uri " + url + " -OutFile " + outFile;
255 std::string cmd = "powershell.exe " + psCmd;
259 std::string outFile = tmpDir + "libMeshGemsKeyGenerator.so";
261 std::string cmd = "wget " + url + " -O " + outFile;
265 if ( Kernel_Utils::IsExists( outFile )) // remove existing file
267 SMESH_File lib( outFile, /*open=*/false );
275 system( cmd.c_str() ); // download
277 SMESH_File resultFile( outFile, /*open=*/false );
278 bool ok = ( resultFile.exists() && resultFile.size() > 0 );
281 libraryFile._name = outFile;
283 error = "Can't download file " + url;
288 //================================================================================
290 * \brief Load libMeshGemsKeyGenerator.so
291 * \param [out] error - return error description
292 * \param [out] libraryFile - return library file name and _isURL flag
293 * \return bool - is a success
295 //================================================================================
297 bool loadLibrary( std::string& error, LibraryFile& libraryFile )
299 if ( theLibraryHandle )
302 const char* libPath = getenv( theEnvVar );
305 error = SMESH_Comment( "Environment variable ") << theEnvVar << " is not set";
309 libraryFile._name = libPath;
310 // if ( !setExtension( libraryFile._name, error )) // is it necessary?
313 if ( isURL( libraryFile ))
315 if ( !downloadLib( libraryFile, error ))
317 // try to fix extension
318 std::string url = libraryFile._name;
319 if ( !setExtension( libraryFile._name, error ))
321 if ( url == libraryFile._name )
322 return false; // extension not changed
324 if ( !downloadLib( libraryFile, error ))
329 #if defined( WIN32 ) && defined( UNICODE )
330 std::wstring encodePath = Kernel_Utils::utf8_decode_s( libraryFile._name );
331 const wchar_t* path = encodePath.c_str();
333 const char* path = libraryFile._name.c_str();
336 theLibraryHandle = LoadLib( path );
337 if ( !theLibraryHandle )
339 if ( ! getLastError( error ))
340 error = "Can't load library '" + libraryFile._name + "'";
343 return theLibraryHandle;
346 } // anonymous namespace
349 namespace SMESHUtils_MGLicenseKeyGen // API implementation
351 //================================================================================
354 * \param [in] meshgems_cad - pointer to a MG CAD object (meshgems_cad_t)
355 * \param [out] error - return error description
356 * \return bool - is a success
358 //================================================================================
360 bool SignCAD( void* meshgems_cad, std::string& error )
362 LibraryFile libraryFile;
363 if ( !loadLibrary( error, libraryFile ))
367 typedef bool (*SignFun)(void* );
368 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignCAD" );
371 if ( ! getLastError( error ))
372 error = SMESH_Comment( "Can't find symbol 'SignCAD' in '") << getenv( theEnvVar ) << "'";
378 ok = signFun( meshgems_cad );
380 SMESH_CATCH( SMESH::returnError );
382 if ( !error.empty() )
385 error = "SignCAD() failed (located in '" + libraryFile._name + "')";
390 //================================================================================
393 * \param [in] meshgems_mesh - pointer to a MG mesh (meshgems_mesh_t)
394 * \param [out] error - return error description
395 * \return bool - is a success
397 //================================================================================
399 bool SignMesh( void* meshgems_mesh, std::string& error )
401 LibraryFile libraryFile;
402 if ( !loadLibrary( error, libraryFile ))
406 typedef bool (*SignFun)(void* );
407 SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignMesh" );
410 if ( ! getLastError( error ))
411 error = SMESH_Comment( "Can't find symbol 'SignMesh' in '") << getenv( theEnvVar ) << "'";
417 ok = signFun( meshgems_mesh );
419 SMESH_CATCH( SMESH::returnError );
421 if ( !error.empty() )
424 error = "SignMesh() failed (located in '" + libraryFile._name + "')";
429 //================================================================================
431 * \brief Return a license key to pass as argument to a MG mesher executable
432 * \param [in] gmfFile - path to an input mesh file
433 * \param [in] nb* - nb of entities in the input mesh
434 * \param [out] error - return error description
435 * \return std::string - the key
437 //================================================================================
439 std::string GetKey(const std::string& gmfFile,
447 LibraryFile libraryFile;
448 if ( !loadLibrary( error, libraryFile ))
451 typedef std::string (*GetKeyFun)(std::string const &, int, int, int, int );
452 GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
455 if ( ! getLastError( error ))
456 error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
460 key = keyFun( gmfFile, nbVertex, nbEdge, nbFace, nbVol );
463 error = "GetKey() failed (located in '" + libraryFile._name + "')";
468 //================================================================================
470 * \brief Return false if libMeshGemsKeyGenerator.so is not functional
471 * \param [out] error - return error description
472 * \return bool - is a success
474 //================================================================================
476 bool CheckKeyGenLibrary( std::string& error )
478 return !GetKey("",4,0,2,0,error ).empty();
481 //================================================================================
483 * \brief Return KeyGenerator library name
485 //================================================================================
487 std::string GetLibraryName()
489 std::string libName, error;
490 if ( const char* libPath = getenv( theEnvVar ))
492 libName = Kernel_Utils::GetBaseName( libPath );
496 libName = "libSalomeMeshGemsKeyGenerator";
498 setExtension( libName, error );