Salome HOME
bos #24596 [CEA] New MeshGems license
[modules/smesh.git] / src / SMESHUtils / SMESH_MGLicenseKeyGen.cxx
1 // Copyright (C) 2007-2021  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
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.
7 //
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.
12 //
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
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // File      : SMESHUtils_MGLicenseKeyGen.cxx
20 // Created   : Sat Jul 31 18:54:16 2021
21 // Author    : Edward AGAPOV (OCC)
22
23 #include "SMESH_MGLicenseKeyGen.hxx"
24
25 #include "SMESH_Comment.hxx"
26 #include "SMESH_File.hxx"
27 #include "SMESH_TryCatch.hxx"
28
29 #include <Basics_DirUtils.hxx>
30 #include <Basics_Utils.hxx>
31
32 #include <regex>
33 #include <cstdlib> // getenv, system
34
35 #include <boost/filesystem.hpp>
36 namespace boofs = boost::filesystem;
37
38 #ifdef WIN32
39
40 #  include <windows.h>
41 #  include <process.h>
42
43 #  define LibHandle HMODULE
44 #  define LoadLib( name ) LoadLibrary( name )
45 #  define GetProc GetProcAddress
46 #  define UnLoadLib( handle ) FreeLibrary( handle );
47
48 #else // WIN32
49
50 #  include <dlfcn.h>
51
52 #  define LibHandle void*
53 #  define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
54 #  define GetProc dlsym
55 #  define UnLoadLib( handle ) dlclose( handle );
56
57 #endif // WIN32
58
59 // to retrieve description of exception caught by SMESH_TRY
60 #undef SMESH_CAUGHT
61 #define SMESH_CAUGHT error =
62
63
64 namespace
65 {
66   static LibHandle theLibraryHandle = nullptr; //!< handle of a loaded library
67
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 */
71
72   const char* theTmpEnvVar = "SALOME_TMP_DIR"; // directory to download the library to
73
74   //-----------------------------------------------------------------------------------
75   /*!
76    * \brief Remove library file at destruction in case if it was downloaded from server
77    */
78   //-----------------------------------------------------------------------------------
79
80   struct LibraryFile
81   {
82     std::string _name; // full file name
83     bool        _isURL;
84
85     LibraryFile(): _isURL( false ) {}
86
87     ~LibraryFile()
88     {
89       if ( _isURL )
90       {
91         if ( theLibraryHandle )
92         {
93           UnLoadLib( theLibraryHandle );
94           theLibraryHandle = nullptr;
95         }
96
97         std::string tmpDir; // tmp dir that should not be removed
98         if ( const char* libPath = getenv( theTmpEnvVar ))
99         {
100           tmpDir = libPath;
101           while (( !tmpDir.empty() ) &&
102                  ( tmpDir.back() == '/' || tmpDir.back() == '\\' ))
103             tmpDir.pop_back();
104         }
105
106         while ( SMESH_File( _name ).remove() )
107         {
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
112
113           if ( _name == tmpDir )
114             break; // don't remove tmp dir
115
116           if ( !Kernel_Utils::IsEmptyDir( _name ))
117             break;
118         }
119       }
120     }
121   };
122
123
124   //================================================================================
125   /*!
126    * \brief Retrieve description of the last error
127    *  \param [out] error - return the description
128    *  \return bool - true if the description found
129    */
130   //================================================================================
131
132   bool getLastError( std::string& error )
133   {
134 #ifndef WIN32
135
136     if ( const char* text = dlerror() )
137     {
138       error = text;
139       return true;
140     }
141     return false;
142
143 #else
144
145     DWORD dw = GetLastError();
146     void* cstr;
147     DWORD msgLen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
148                                  NULL,
149                                  dw,
150                                  MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
151                                  (LPTSTR) &cstr,
152                                  0,
153                                  NULL
154                                  );
155     if ( msgLen > 0 )
156       error = (char*) cstr;
157
158     LocalFree(cstr);
159
160     return msgLen;
161
162 #endif
163   }
164
165   //================================================================================
166   /*!
167    * \brief Adjust file extension according to the platform
168    */
169   //================================================================================
170
171   bool setExtension( std::string& fileName, std::string& error )
172   {
173     if ( fileName.empty() )
174     {
175       error = "Library file name is empty";
176       return false;
177     }
178 #if defined(WIN32)
179     std::string ext = ".dll";
180 #elif defined(__APPLE__)
181     std::string ext = ".dylib";
182 #else
183     std::string ext = ".so";
184 #endif
185
186     fileName = fileName.substr( 0, fileName.find_last_of('.')) + ext;
187     return true;
188   }
189
190   //================================================================================
191   /*!
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
195    */
196   //================================================================================
197
198   bool isURL( LibraryFile & libraryFile )
199   {
200     enum { SCHEME = 2, AUTHORITY = 4, PATH = 5 }; // sub-strings
201     std::regex urlRegex ( R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
202                           std::regex::extended );
203     std::smatch matchResult;
204
205     libraryFile._isURL = false;
206     if ( std::regex_match( libraryFile._name, matchResult, urlRegex ))
207       libraryFile._isURL = ( !matchResult.str( SCHEME    ).empty() &&
208                              !matchResult.str( AUTHORITY ).empty() &&
209                              !matchResult.str( PATH      ).empty() );
210
211     return libraryFile._isURL;
212   }
213
214   //================================================================================
215   /*!
216    * \brief Download libraryFile._name URL to SALOME_TMP_DIR
217    *  \param [in,out] libraryFile - holds the URL and returns name of a downloaded file
218    *  \param [out] error - return error description
219    *  \return bool - is a success
220    */
221   //================================================================================
222
223   bool downloadLib( LibraryFile& libraryFile, std::string & error )
224   {
225     // check if can write into SALOME_TMP_DIR
226
227     std::string tmpDir = Kernel_Utils::GetTmpDirByEnv( theTmpEnvVar );
228     if ( tmpDir.empty() ||
229          !Kernel_Utils::IsExists( tmpDir ))
230     {
231       error = "Can't download " + libraryFile._name + " as SALOME_TMP_DIR is not correctly set";
232       return false;
233     }
234     if ( !Kernel_Utils::IsWritable( tmpDir ))
235     {
236       error = "Can't download " + libraryFile._name + " as '" + tmpDir + "' is not writable. "
237         "Check SALOME_TMP_DIR environment variable";
238       return false;
239     }
240
241     // Download
242
243     std::string url = libraryFile._name;
244
245 #ifdef WIN32
246
247     std::string outFile = tmpDir + "libMeshGemsKeyGenerator.dll";
248
249     // use wget (== Invoke-WebRequest) PowerShell command available since Windows 7
250     std::string psCmd = "wget -Uri " + url + " -OutFile " + outFile;
251     std::string   cmd = "start powershell.exe " + psCmd;
252
253 #else
254
255     std::string outFile = tmpDir + "libMeshGemsKeyGenerator.so";
256
257     std::string cmd = "wget " + url + " -O " + outFile;
258
259 #endif
260
261     if ( Kernel_Utils::IsExists( outFile )) // remove existing file
262     {
263       SMESH_File lib( outFile, /*open=*/false );
264       if ( !lib.remove() )
265       {
266         error = lib.error();
267         return false;
268       }
269     }
270
271     system( cmd.c_str() ); // download
272
273     SMESH_File resultFile( outFile, /*open=*/false );
274     bool ok = ( resultFile.exists() && resultFile.size() > 0 );
275
276     if ( ok )
277       libraryFile._name = outFile;
278
279     return ok;
280   }
281
282   //================================================================================
283   /*!
284    * \brief Load libMeshGemsKeyGenerator.so
285    *  \param [out] error - return error description
286    *  \param [out] libraryFile - return library file name and _isURL flag
287    *  \return bool - is a success
288    */
289   //================================================================================
290
291   bool loadLibrary( std::string& error, LibraryFile& libraryFile )
292   {
293     if ( theLibraryHandle )
294       return true;
295
296     const char* libPath = getenv( theEnvVar );
297     if ( !libPath )
298     {
299       error = SMESH_Comment( "Environment variable ") <<  theEnvVar << " is not set";
300       return false;
301     }
302
303     libraryFile._name = libPath;
304     // if ( !setExtension( libraryFile._name, error )) // is it necessary?
305     //   return false;
306
307     if ( isURL( libraryFile ))
308     {
309       if ( !downloadLib( libraryFile, error ))
310       {
311         // try to fix extension
312         std::string url = libraryFile._name;
313         if ( !setExtension( libraryFile._name, error ))
314           return false;
315         if ( url == libraryFile._name )
316           return false; // extension not changed
317
318         if ( !downloadLib( libraryFile, error ))
319           return false;
320       }
321     }
322
323 #if defined( WIN32 ) && defined( UNICODE )
324     std::wstring encodePath = Kernel_Utils::utf8_decode_s( libraryFile._name );
325     const wchar_t*     path = encodePath.c_str();
326 #else
327     const char*        path = libraryFile._name.c_str();
328 #endif
329
330     theLibraryHandle = LoadLib( path );
331     if ( !theLibraryHandle )
332     {
333       if ( ! getLastError( error ))
334         error = "Can't load library '" + libraryFile._name + "'";
335     }
336
337     return theLibraryHandle;
338   }
339
340 } // anonymous namespace
341
342
343 namespace SMESHUtils_MGLicenseKeyGen // API implementation
344 {
345   //================================================================================
346   /*!
347    * \brief Sign a CAD
348    *  \param [in] meshgems_cad - pointer to a MG CAD object (meshgems_cad_t)
349    *  \param [out] error - return error description
350    *  \return bool - is a success
351    */
352   //================================================================================
353
354   bool SignCAD( void* meshgems_cad, std::string& error )
355   {
356     LibraryFile libraryFile;
357     if ( !loadLibrary( error, libraryFile ))
358       return false;
359
360     typedef bool (*SignFun)(void* );
361     SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignCAD" ); 
362     if ( !signFun )
363     {
364       if ( ! getLastError( error ))
365         error = SMESH_Comment( "Can't find symbol 'SignCAD' in '") << getenv( theEnvVar ) << "'";
366     }
367
368     bool ok;
369
370     SMESH_TRY;
371
372     ok = signFun( meshgems_cad );
373
374     SMESH_CATCH( SMESH::returnError );
375
376     if ( !error.empty() )
377       ok = false;
378     else if ( !ok )
379       error = "SignCAD() failed (located in '" + libraryFile._name + "')";
380
381     return ok;
382   }
383
384   //================================================================================
385   /*!
386    * \brief Sign a mesh
387    *  \param [in] meshgems_mesh - pointer to a MG mesh (meshgems_mesh_t)
388    *  \param [out] error - return error description
389    *  \return bool - is a success
390    */
391   //================================================================================
392
393   bool SignMesh( void* meshgems_mesh, std::string& error )
394   {
395     LibraryFile libraryFile;
396     if ( !loadLibrary( error, libraryFile ))
397       return false;
398
399     typedef bool (*SignFun)(void* );
400     SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignMesh" );
401     if ( !signFun )
402     {
403       if ( ! getLastError( error ))
404         error = SMESH_Comment( "Can't find symbol 'SignMesh' in '") << getenv( theEnvVar ) << "'";
405     }
406     bool ok;
407
408     SMESH_TRY;
409
410     ok = signFun( meshgems_mesh );
411
412     SMESH_CATCH( SMESH::returnError );
413
414     if ( !error.empty() )
415       ok = false;
416     else if ( !ok )
417       error = "SignMesh() failed (located in '" + libraryFile._name + "')";
418
419     return ok;
420   }
421
422   //================================================================================
423   /*!
424    * \brief Return a license key to pass as argument to a MG mesher executable
425    *  \param [in] gmfFile - path to an input mesh file
426    *  \param [in] nb* - nb of entities in the input mesh
427    *  \param [out] error - return error description
428    *  \return std::string - the key
429    */
430   //================================================================================
431
432   std::string GetKey(const std::string& gmfFile,
433                      int                nbVertex,
434                      int                nbEdge,
435                      int                nbFace,
436                      int                nbVol,
437                      std::string&       error)
438   {
439     std::string key;
440     LibraryFile libraryFile;
441     if ( !loadLibrary( error, libraryFile ))
442       return key;
443
444     typedef std::string (*GetKeyFun)(std::string const &, int, int, int, int );
445     GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
446     if ( !keyFun )
447     {
448       if ( ! getLastError( error ))
449         error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
450     }
451     key = keyFun( gmfFile, nbVertex, nbEdge, nbFace, nbVol );
452
453     if ( key.empty() )
454       error = "GetKey() failed (located in '" + libraryFile._name + "')";
455
456     return key;
457   }
458
459   //================================================================================
460   /*!
461    * \brief Return false if libMeshGemsKeyGenerator.so is not functional
462    *  \param [out] error - return error description
463    *  \return bool - is a success
464    */
465   //================================================================================
466
467   bool CheckKeyGenLibrary( std::string& error )
468   {
469     return !GetKey("",4,0,2,0,error ).empty();
470   }
471
472   //================================================================================
473   /*!
474    * \brief Return KeyGenerator library name
475    */
476   //================================================================================
477
478   std::string GetLibraryName()
479   {
480     std::string libName, error;
481     if ( const char* libPath = getenv( theEnvVar ))
482     {
483       libName = Kernel_Utils::GetBaseName( libPath );
484     }
485     else
486     {
487       libName = "libSalomeMeshGemsKeyGenerator";
488     }
489     setExtension( libName, error );
490     return libName;
491   }
492 }