0024428: Implementation of LGPL license
[occt.git] / src / OSD / OSD_Process.cxx
1 // Copyright (c) 1998-1999 Matra Datavision
2 // Copyright (c) 1999-2014 OPEN CASCADE SAS
3 //
4 // This file is part of Open CASCADE Technology software library.
5 //
6 // This library is free software; you can redistribute it and / or modify it
7 // under the terms of the GNU Lesser General Public version 2.1 as published
8 // by the Free Software Foundation, with special exception defined in the file
9 // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
10 // distribution for complete text of the license and disclaimer of any warranty.
11 //
12 // Alternatively, this file may be used under the terms of Open CASCADE
13 // commercial license or contractual agreement.
14
15 #ifdef HAVE_CONFIG_H
16 # include <config.h>
17 #endif
18
19 #ifndef WNT
20
21 #include <OSD_Process.ixx>
22 #include <OSD_WhoAmI.hxx>
23 #include <OSD_Environment.hxx>
24
25 const OSD_WhoAmI Iam = OSD_WProcess;
26
27 #include <errno.h>
28
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32
33 #include <stdlib.h>
34
35 #ifdef HAVE_SYS_PARAM_H
36 # include <sys/param.h>
37 #endif
38
39 #if defined(HAVE_TIME_H) || defined(WNT)
40 # include <time.h>
41 #endif
42
43 #ifdef HAVE_SYS_TIME_H
44 # include <sys/time.h>
45 #endif
46
47 #ifdef HAVE_PWD_H
48 # include <pwd.h>       // For command getpwuid
49 #endif
50
51 OSD_Process::OSD_Process(){
52 }
53
54
55 void OSD_Process::Spawn (const TCollection_AsciiString& cmd,
56                          const Standard_Boolean /*ShowWindow*/)
57 {
58  system(cmd.ToCString());
59 }
60
61
62 void OSD_Process::TerminalType(TCollection_AsciiString& Name){
63 TCollection_AsciiString which="TERM";
64 OSD_Environment term (which,"");
65
66  term.Value();
67  which = term.Value();
68  Name = term.Name();
69 }
70
71
72 // Get date of system date
73
74 Quantity_Date  OSD_Process::SystemDate(){
75 Quantity_Date result;
76 Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
77 struct tm transfert;
78 struct timeval tval;
79 struct timezone tzone;
80 int status;
81
82  status = gettimeofday( &tval, &tzone );
83  if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
84  else {
85   memcpy(&transfert, localtime((time_t *)&tval.tv_sec), sizeof(struct
86 tm));
87   month = transfert.tm_mon + 1;  // Add to January (month #1)
88   day   = transfert.tm_mday;
89   year  = transfert.tm_year;
90   hh    = transfert.tm_hour;
91   mn    = transfert.tm_min ;
92   ss    = transfert.tm_sec ;
93 }
94
95  result.SetValues ( month, day, year+1900, hh, mn, ss);
96  return (result);
97 }
98
99
100 Standard_Integer OSD_Process::ProcessId(){
101  return (getpid());
102 }
103
104
105 Standard_Integer OSD_Process::UserId(){
106  return (getuid());
107 }
108
109
110 TCollection_AsciiString OSD_Process::UserName(){
111  struct passwd *infos;
112  infos = getpwuid(getuid()); 
113  TCollection_AsciiString result=infos->pw_name;
114
115  return(result);
116 }
117
118 Standard_Boolean OSD_Process::IsSuperUser (){
119   if (getuid()) {
120     return Standard_False;
121   }
122   else {
123     return Standard_True;
124   }
125 }
126
127
128 OSD_Path OSD_Process::CurrentDirectory(){
129 char cwd[MAXPATHLEN+1] ;
130 OSD_Path result;
131 TCollection_AsciiString Name;
132
133  if (!getcwd(cwd,MAXPATHLEN+1))
134    myError.SetValue (errno, Iam, "Where");
135  else {
136    Name = cwd;
137
138 //   JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
139 //   position = Name.SearchFromEnd(".");
140 //   if (position != -1){
141 //     Ext = Name;
142 //     Ext.Remove(1,position);
143 //     Name.Remove( position,Ext.Length()+1);
144 //   }
145 //   result.SetValues("","","","","",Name,Ext);
146 //   End
147
148 #if defined(vax) || defined(__vms)
149    Standard_Integer iDisk = Name.Search(":");
150    if (iDisk){
151      TCollection_AsciiString Disk;
152      TCollection_AsciiString Directory;
153      Disk = Name.SubString(1,iDisk-1);
154      Directory = Name.SubString(iDisk+1,Name.Length());
155      result.SetValues("","","",Disk,Directory,"","");
156    }
157 #else
158    Name += TCollection_AsciiString("/");
159    result = OSD_Path(Name);
160    //      result.SetValues("","","","",Name,"","");
161 #endif
162
163  }
164 return (result);
165 }
166
167
168 void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
169 TCollection_AsciiString Name;
170 int status;
171
172  where.SystemName(Name);
173
174  status = chdir (Name.ToCString());
175  if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
176 }
177
178
179 void OSD_Process::Reset(){
180  myError.Reset();
181 }
182
183 Standard_Boolean OSD_Process::Failed()const{
184  return( myError.Failed());
185 }
186
187 void OSD_Process::Perror() {
188  myError.Perror();
189 }
190
191
192 Standard_Integer OSD_Process::Error()const{
193  return( myError.Error());
194 }
195
196 #else
197
198 //------------------------------------------------------------------------
199 //-------------------  WNT Sources of OSD_Path ---------------------------
200 //------------------------------------------------------------------------
201
202 //it is important to undefine NOUSER and enforce including <windows.h> before
203 //Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
204 #ifdef NOUSER
205 #undef NOUSER /* we need SW_HIDE from windows.h */
206 #endif
207 #include <windows.h>
208
209 #ifdef SetCurrentDirectory
210 # undef SetCurrentDirectory /* undefine SetCurrentDirectory from <winbase.h> to correctly include <OSD_Process.hxx> */
211 #endif
212 #include <OSD_Process.hxx>
213
214 #include <OSD_Path.hxx>
215 #include <Quantity_Date.hxx>
216
217 #include <OSD_WNT_1.hxx>
218 #include <LMCONS.H> /// pour UNLEN  ( see MSDN about GetUserName() )
219
220
221 #pragma warning( disable : 4700 )
222
223 void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
224
225 OSD_Process :: OSD_Process () {
226
227 }  // end constructor
228
229 void OSD_Process :: Spawn ( const TCollection_AsciiString& cmd ,
230                             const Standard_Boolean ShowWindow /* = Standard_True */) {
231
232  STARTUPINFO         si;
233  PROCESS_INFORMATION pi;
234
235  ZeroMemory (  &si, sizeof ( STARTUPINFO )  );
236
237  si.cb = sizeof ( STARTUPINFO );
238  //============================================
239  //---> Added by Stephane Routelous ( stephane.routelous@altavista.net )        [16.03.01]
240  //---> Reason : to allow to hide the window
241  if ( !ShowWindow )
242  {
243          si.dwFlags             = STARTF_USESHOWWINDOW;
244          si.wShowWindow = SW_HIDE;      
245  }
246  //<--- End Added by Stephane Routelous ( stephane.routelous@altavista.net )    [16.03.01]
247  //============================================
248
249  if (!CreateProcess (
250       NULL, (char *)cmd.ToCString (), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi
251                     )
252  )
253
254   _osd_wnt_set_error ( myError, OSD_WProcess );
255
256  else {
257  
258   CloseHandle ( pi.hThread );
259
260   WaitForSingleObject ( pi.hProcess, INFINITE );
261
262   CloseHandle ( pi.hProcess );
263  
264  }  // end else
265
266 }  // end OSD_Process :: Spawn
267
268 void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
269
270  Name = TEXT( "WIN32 console" );
271
272 }  // end OSD_Process :: TerminalType
273
274 Quantity_Date OSD_Process :: SystemDate () {
275
276  Quantity_Date retVal;
277  SYSTEMTIME    st;
278
279  GetLocalTime ( &st );
280
281  retVal.SetValues (
282          st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
283         );
284
285  return retVal;
286
287 }  // end OSD_Process :: SystemDate
288
289 Standard_Integer OSD_Process :: UserId () {
290
291  PSID         retVal        = NULL;
292  HANDLE       hProcessToken = INVALID_HANDLE_VALUE;
293  PTOKEN_OWNER pTKowner      = NULL;
294
295  if (  !OpenProcessToken (
296          GetCurrentProcess (),
297          TOKEN_QUERY, &hProcessToken
298         ) ||
299         (  pTKowner = ( PTOKEN_OWNER )GetTokenInformationEx (
300                                        hProcessToken, TokenOwner
301                                       )
302         ) == NULL ||
303         (  retVal   = CopySidEx ( pTKowner -> Owner )  ) == NULL
304  )
305
306   _osd_wnt_set_error ( myError, OSD_WProcess );
307
308  if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
309  if ( pTKowner      != NULL                 ) FreeTokenInformation ( pTKowner );
310
311  return ( Standard_Integer )retVal;
312
313 }  // end OSD_Process :: UserId
314
315 TCollection_AsciiString OSD_Process :: UserName () 
316 {
317         Standard_PCharacter pBuff = new char[UNLEN + 1];
318         DWORD                   dwSize = UNLEN + 1;
319         TCollection_AsciiString retVal;
320         if (  !GetUserName ( pBuff, &dwSize )  )
321         {
322                 _osd_wnt_set_error ( myError, OSD_WProcess );
323         }
324         else
325         {
326                 TCollection_AsciiString theTmpUserName(pBuff,(int)dwSize -1 );
327                 retVal = theTmpUserName;
328         }
329         delete [] pBuff;
330         return retVal;
331 }  // end OSD_Process :: UserName
332
333 Standard_Boolean OSD_Process :: IsSuperUser () {
334
335  Standard_Boolean retVal = FALSE;
336  PSID             pSIDadmin;
337  HANDLE           hProcessToken = INVALID_HANDLE_VALUE;
338  PTOKEN_GROUPS    pTKgroups = NULL;
339
340  if (  !OpenProcessToken (
341          GetCurrentProcess (),
342          TOKEN_QUERY, &hProcessToken
343         ) ||
344         (  pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
345                                          hProcessToken, TokenGroups
346                                         )
347         ) == NULL
348  )
349
350   _osd_wnt_set_error ( myError, OSD_WProcess );
351
352  else {
353  
354   pSIDadmin = AdminSid ();
355
356   for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
357
358    if (  EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin )  ) {
359    
360     retVal = TRUE;
361     break;
362    
363    }  // end if
364  
365  }  // end else
366
367  if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
368  if ( pTKgroups     != NULL                 ) FreeTokenInformation ( pTKgroups );
369
370  return retVal;
371
372 }  // end OSD_Process :: IsSuperUser
373
374 Standard_Integer OSD_Process :: ProcessId () {
375
376  return ( Standard_Integer )GetCurrentProcessId ();
377
378 }  // end OSD_Process :: ProcessId
379
380 OSD_Path OSD_Process :: CurrentDirectory () {
381
382   OSD_Path anCurrentDirectory;
383
384   DWORD dwSize = PATHLEN + 1;
385   Standard_PCharacter pBuff = new char[dwSize];
386
387   if ( GetCurrentDirectory(dwSize, pBuff) > 0 )
388     anCurrentDirectory = OSD_Path ( pBuff );
389   else
390     _osd_wnt_set_error ( myError, OSD_WProcess );
391  
392   delete[] pBuff;
393   return anCurrentDirectory;
394 }  // end OSD_Process :: CurrentDirectory
395
396 void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
397
398 #ifdef UNICODE
399 # define SetCurrentDirectory  SetCurrentDirectoryW
400 #else
401 # define SetCurrentDirectory  SetCurrentDirectoryA
402 #endif  // UNICODE
403
404  TCollection_AsciiString path;
405
406  where.SystemName ( path );
407
408  if (   !::SetCurrentDirectory (  path.ToCString ()  )   )
409
410   _osd_wnt_set_error ( myError, OSD_WProcess );
411
412 }  // end OSD_Process :: SetCurrentDirectory
413
414 Standard_Boolean OSD_Process :: Failed () const {
415
416  return myError.Failed ();
417
418 }  // end OSD_Process :: Failed
419
420 void OSD_Process :: Reset () {
421
422  myError.Reset ();
423
424 }  // end OSD_Process :: Reset
425
426 void OSD_Process :: Perror () {
427
428  myError.Perror ();
429
430 }  // end OSD_Process :: Perror
431
432 Standard_Integer OSD_Process :: Error () const {
433
434  return myError.Error ();
435
436 }  // end OSD_Process :: Error
437
438 #endif