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