Salome HOME
Allow EDF URL style
[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     {// round1
201       enum { SCHEME = 2, AUTHORITY = 4, PATH = 5 }; // sub-strings
202       std::regex urlRegex ( R"(^(([^:\/?#]+):)?(//([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)",
203                             std::regex::extended );
204       std::smatch matchResult;
205
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() );
211     }
212     if(libraryFile._isURL)
213       return true;
214     {// round2
215       enum { HOST = 2, PORT = 3, PATH = 4 }; // sub-strings
216       std::regex urlRegex ( R"(^(([^:\/?#]+):)?([^/]+)?(/[^#]*))",
217                             std::regex::extended );
218       std::smatch matchResult;
219
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() );
225     }
226     return libraryFile._isURL;
227   }
228
229   //================================================================================
230   /*!
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
235    */
236   //================================================================================
237
238   bool downloadLib( LibraryFile& libraryFile, std::string & error )
239   {
240     // check if can write into SALOME_TMP_DIR
241
242     std::string tmpDir = Kernel_Utils::GetTmpDirByEnv( theTmpEnvVar );
243     if ( tmpDir.empty() ||
244          !Kernel_Utils::IsExists( tmpDir ))
245     {
246       error = "Can't download " + libraryFile._name + " as SALOME_TMP_DIR is not correctly set";
247       return false;
248     }
249     if ( !Kernel_Utils::IsWritable( tmpDir ))
250     {
251       error = "Can't download " + libraryFile._name + " as '" + tmpDir + "' is not writable. "
252         "Check SALOME_TMP_DIR environment variable";
253       return false;
254     }
255
256     // Download
257
258     std::string url = libraryFile._name;
259
260 #ifdef WIN32
261
262     std::string outFile = tmpDir + "libMeshGemsKeyGenerator.dll";
263
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;
267
268 #else
269
270     std::string outFile = tmpDir + "libMeshGemsKeyGenerator.so";
271
272     std::string cmd = "wget " + url + " -O " + outFile;
273
274 #endif
275
276     if ( Kernel_Utils::IsExists( outFile )) // remove existing file
277     {
278       SMESH_File lib( outFile, /*open=*/false );
279       if ( !lib.remove() )
280       {
281         error = lib.error();
282         return false;
283       }
284     }
285
286     system( cmd.c_str() ); // download
287
288     SMESH_File resultFile( outFile, /*open=*/false );
289     bool ok = ( resultFile.exists() && resultFile.size() > 0 );
290
291     if ( ok )
292       libraryFile._name = outFile;
293
294     return ok;
295   }
296
297   //================================================================================
298   /*!
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
303    */
304   //================================================================================
305
306   bool loadLibrary( std::string& error, LibraryFile& libraryFile )
307   {
308     if ( theLibraryHandle )
309       return true;
310
311     const char* libPath = getenv( theEnvVar );
312     if ( !libPath )
313     {
314       error = SMESH_Comment( "Environment variable ") <<  theEnvVar << " is not set";
315       return false;
316     }
317
318     libraryFile._name = libPath;
319     // if ( !setExtension( libraryFile._name, error )) // is it necessary?
320     //   return false;
321
322     if ( isURL( libraryFile ))
323     {
324       if ( !downloadLib( libraryFile, error ))
325       {
326         // try to fix extension
327         std::string url = libraryFile._name;
328         if ( !setExtension( libraryFile._name, error ))
329           return false;
330         if ( url == libraryFile._name )
331           return false; // extension not changed
332
333         if ( !downloadLib( libraryFile, error ))
334           return false;
335       }
336     }
337
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();
341 #else
342     const char*        path = libraryFile._name.c_str();
343 #endif
344
345     theLibraryHandle = LoadLib( path );
346     if ( !theLibraryHandle )
347     {
348       if ( ! getLastError( error ))
349         error = "Can't load library '" + libraryFile._name + "'";
350     }
351
352     return theLibraryHandle;
353   }
354
355 } // anonymous namespace
356
357
358 namespace SMESHUtils_MGLicenseKeyGen // API implementation
359 {
360   //================================================================================
361   /*!
362    * \brief Sign a CAD
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
366    */
367   //================================================================================
368
369   bool SignCAD( void* meshgems_cad, std::string& error )
370   {
371     LibraryFile libraryFile;
372     if ( !loadLibrary( error, libraryFile ))
373       return false;
374
375     typedef bool (*SignFun)(void* );
376     SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignCAD" ); 
377     if ( !signFun )
378     {
379       if ( ! getLastError( error ))
380         error = SMESH_Comment( "Can't find symbol 'SignCAD' in '") << getenv( theEnvVar ) << "'";
381     }
382
383     bool ok;
384
385     SMESH_TRY;
386
387     ok = signFun( meshgems_cad );
388
389     SMESH_CATCH( SMESH::returnError );
390
391     if ( !error.empty() )
392       ok = false;
393     else if ( !ok )
394       error = "SignCAD() failed (located in '" + libraryFile._name + "')";
395
396     return ok;
397   }
398
399   //================================================================================
400   /*!
401    * \brief Sign a mesh
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
405    */
406   //================================================================================
407
408   bool SignMesh( void* meshgems_mesh, std::string& error )
409   {
410     LibraryFile libraryFile;
411     if ( !loadLibrary( error, libraryFile ))
412       return false;
413
414     typedef bool (*SignFun)(void* );
415     SignFun signFun = (SignFun) GetProc( theLibraryHandle, "SignMesh" );
416     if ( !signFun )
417     {
418       if ( ! getLastError( error ))
419         error = SMESH_Comment( "Can't find symbol 'SignMesh' in '") << getenv( theEnvVar ) << "'";
420     }
421     bool ok;
422
423     SMESH_TRY;
424
425     ok = signFun( meshgems_mesh );
426
427     SMESH_CATCH( SMESH::returnError );
428
429     if ( !error.empty() )
430       ok = false;
431     else if ( !ok )
432       error = "SignMesh() failed (located in '" + libraryFile._name + "')";
433
434     return ok;
435   }
436
437   //================================================================================
438   /*!
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
444    */
445   //================================================================================
446
447   std::string GetKey(const std::string& gmfFile,
448                      int                nbVertex,
449                      int                nbEdge,
450                      int                nbFace,
451                      int                nbVol,
452                      std::string&       error)
453   {
454     std::string key;
455     LibraryFile libraryFile;
456     if ( !loadLibrary( error, libraryFile ))
457       return key;
458
459     typedef std::string (*GetKeyFun)(std::string const &, int, int, int, int );
460     GetKeyFun keyFun = (GetKeyFun) GetProc( theLibraryHandle, "GetKey" );
461     if ( !keyFun )
462     {
463       if ( ! getLastError( error ))
464         error = SMESH_Comment( "Can't find symbol 'GetKey' in '") << getenv( theEnvVar ) << "'";
465     }
466     key = keyFun( gmfFile, nbVertex, nbEdge, nbFace, nbVol );
467
468     if ( key.empty() )
469       error = "GetKey() failed (located in '" + libraryFile._name + "')";
470
471     return key;
472   }
473
474   //================================================================================
475   /*!
476    * \brief Return false if libMeshGemsKeyGenerator.so is not functional
477    *  \param [out] error - return error description
478    *  \return bool - is a success
479    */
480   //================================================================================
481
482   bool CheckKeyGenLibrary( std::string& error )
483   {
484     return !GetKey("",4,0,2,0,error ).empty();
485   }
486
487   //================================================================================
488   /*!
489    * \brief Return KeyGenerator library name
490    */
491   //================================================================================
492
493   std::string GetLibraryName()
494   {
495     std::string libName, error;
496     if ( const char* libPath = getenv( theEnvVar ))
497     {
498       libName = Kernel_Utils::GetBaseName( libPath );
499     }
500     else
501     {
502       libName = "libSalomeMeshGemsKeyGenerator";
503     }
504     setExtension( libName, error );
505     return libName;
506   }
507 }