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