1 // Copyright (c) 1998-1999 Matra Datavision
2 // Copyright (c) 1999-2014 OPEN CASCADE SAS
4 // This file is part of Open CASCADE Technology software library.
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.
12 // Alternatively, this file may be used under the terms of Open CASCADE
13 // commercial license or contractual agreement.
16 //it is important to undefine NOUSER and enforce including <windows.h> before
17 //Standard_Macro.hxx defines it and includes <windows.h> causing compilation errors
19 #undef NOUSER // we need SW_HIDE from windows.h
24 #include <OSD_Process.hxx>
26 #include <NCollection_Array1.hxx>
27 #include <OSD_Environment.hxx>
28 #include <OSD_OSDError.hxx>
29 #include <OSD_Path.hxx>
30 #include <OSD_WhoAmI.hxx>
31 #include <Standard_PExtCharacter.hxx>
32 #include <TCollection_ExtendedString.hxx>
33 #include <Quantity_Date.hxx>
36 #include <OSD_WNT.hxx>
37 #include <lmcons.h> // for UNLEN - maximum user name length GetUserName()
39 const OSD_WhoAmI Iam = OSD_WProcess;
42 #include <sys/param.h>
44 #include <pwd.h> // For command getpwuid
48 #if defined(__APPLE__)
49 #include <mach-o/dyld.h>
54 OSD_Process::OSD_Process(){
58 void OSD_Process::TerminalType(TCollection_AsciiString& Name){
59 TCollection_AsciiString which="TERM";
60 OSD_Environment term (which,"");
68 // Get date of system date
70 Quantity_Date OSD_Process::SystemDate(){
72 Standard_Integer month=0,day=0,year=0,hh=0,mn=0,ss=0;
75 struct timezone tzone;
78 status = gettimeofday( &tval, &tzone );
79 if (status == -1) myError.SetValue (errno, Iam, "GetSystem");
81 memcpy(&transfert, localtime((time_t *)&tval.tv_sec), sizeof(struct
83 month = transfert.tm_mon + 1; // Add to January (month #1)
84 day = transfert.tm_mday;
85 year = transfert.tm_year;
86 hh = transfert.tm_hour;
87 mn = transfert.tm_min ;
88 ss = transfert.tm_sec ;
91 result.SetValues ( month, day, year+1900, hh, mn, ss);
96 Standard_Integer OSD_Process::ProcessId(){
100 TCollection_AsciiString OSD_Process::UserName()
102 struct passwd *anInfos = getpwuid (getuid());
103 return TCollection_AsciiString (anInfos ? anInfos->pw_name : "");
106 Standard_Boolean OSD_Process::IsSuperUser (){
108 return Standard_False;
111 return Standard_True;
116 OSD_Path OSD_Process::CurrentDirectory(){
117 char cwd[MAXPATHLEN+1] ;
119 TCollection_AsciiString Name;
121 if (!getcwd(cwd,MAXPATHLEN+1))
122 myError.SetValue (errno, Iam, "Where");
126 // JPT : August,20 1993. This code has been replaced by #ifdef ... #endif
127 // position = Name.SearchFromEnd(".");
128 // if (position != -1){
130 // Ext.Remove(1,position);
131 // Name.Remove( position,Ext.Length()+1);
133 // result.SetValues("","","","","",Name,Ext);
136 #if defined(vax) || defined(__vms)
137 Standard_Integer iDisk = Name.Search(":");
139 TCollection_AsciiString Disk;
140 TCollection_AsciiString Directory;
141 Disk = Name.SubString(1,iDisk-1);
142 Directory = Name.SubString(iDisk+1,Name.Length());
143 result.SetValues("","","",Disk,Directory,"","");
146 Name += TCollection_AsciiString("/");
147 result = OSD_Path(Name);
148 // result.SetValues("","","","",Name,"","");
156 void OSD_Process::SetCurrentDirectory(const OSD_Path& where){
157 TCollection_AsciiString Name;
160 where.SystemName(Name);
162 status = chdir (Name.ToCString());
163 if (status == -1) myError.SetValue(errno, Iam, "Move to directory");
167 void OSD_Process::Reset(){
171 Standard_Boolean OSD_Process::Failed()const{
172 return( myError.Failed());
175 void OSD_Process::Perror() {
180 Standard_Integer OSD_Process::Error()const{
181 return( myError.Error());
186 //------------------------------------------------------------------------
187 //------------------- WNT Sources of OSD_Path ---------------------------
188 //------------------------------------------------------------------------
190 void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
192 // =======================================================================
193 // function : OSD_Process
195 // =======================================================================
196 OSD_Process::OSD_Process()
201 void OSD_Process :: TerminalType ( TCollection_AsciiString& Name ) {
203 Name = "WIN32 console";
205 } // end OSD_Process :: TerminalType
207 Quantity_Date OSD_Process :: SystemDate () {
209 Quantity_Date retVal;
212 GetLocalTime ( &st );
215 st.wMonth, st.wDay, st.wYear, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds
220 } // end OSD_Process :: SystemDate
222 // =======================================================================
223 // function : UserName
225 // =======================================================================
226 TCollection_AsciiString OSD_Process::UserName()
229 wchar_t aUserName[UNLEN + 1];
230 DWORD aNameSize = UNLEN + 1;
231 TCollection_AsciiString retVal;
232 if (!GetUserNameW (aUserName, &aNameSize))
234 _osd_wnt_set_error(myError, OSD_WProcess);
235 return TCollection_AsciiString();
237 return TCollection_AsciiString (aUserName);
239 return TCollection_AsciiString();
243 Standard_Boolean OSD_Process :: IsSuperUser () {
245 Standard_Boolean retVal = FALSE;
247 HANDLE hProcessToken = INVALID_HANDLE_VALUE;
248 PTOKEN_GROUPS pTKgroups = NULL;
250 if ( !OpenProcessToken (
251 GetCurrentProcess (),
252 TOKEN_QUERY, &hProcessToken
254 ( pTKgroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
255 hProcessToken, TokenGroups
260 _osd_wnt_set_error ( myError, OSD_WProcess );
264 pSIDadmin = AdminSid ();
266 for ( int i = 0; i < ( int )pTKgroups -> GroupCount; ++i )
268 if ( EqualSid ( pTKgroups -> Groups[ i ].Sid, pSIDadmin ) ) {
277 if ( hProcessToken != INVALID_HANDLE_VALUE ) CloseHandle ( hProcessToken );
278 if ( pTKgroups != NULL ) FreeTokenInformation ( pTKgroups );
284 } // end OSD_Process :: IsSuperUser
286 // =======================================================================
287 // function : ProcessId
289 // =======================================================================
290 Standard_Integer OSD_Process::ProcessId()
292 return (Standard_Integer )GetCurrentProcessId();
295 // =======================================================================
296 // function : CurrentDirectory
298 // =======================================================================
299 OSD_Path OSD_Process::CurrentDirectory()
301 OSD_Path anCurrentDirectory;
303 const DWORD aBuffLen = GetCurrentDirectoryW (0, NULL);
306 wchar_t* aBuff = new wchar_t[aBuffLen + 1];
307 GetCurrentDirectoryW (aBuffLen, aBuff);
308 aBuff[aBuffLen] = L'\0';
309 const TCollection_AsciiString aPath (aBuff);
312 anCurrentDirectory = OSD_Path (aPath);
316 _osd_wnt_set_error (myError, OSD_WProcess);
319 return anCurrentDirectory;
322 void OSD_Process :: SetCurrentDirectory ( const OSD_Path& where ) {
324 TCollection_AsciiString path;
326 where.SystemName ( path );
327 TCollection_ExtendedString pathW(path);
329 if (!::SetCurrentDirectoryW (pathW.ToWideString()))
331 _osd_wnt_set_error ( myError, OSD_WProcess );
333 } // end OSD_Process :: SetCurrentDirectory
335 Standard_Boolean OSD_Process :: Failed () const {
337 return myError.Failed ();
339 } // end OSD_Process :: Failed
341 void OSD_Process :: Reset () {
345 } // end OSD_Process :: Reset
347 void OSD_Process :: Perror () {
351 } // end OSD_Process :: Perror
353 Standard_Integer OSD_Process :: Error () const {
355 return myError.Error ();
357 } // end OSD_Process :: Error
361 // =======================================================================
362 // function : ExecutablePath
364 // =======================================================================
365 TCollection_AsciiString OSD_Process::ExecutablePath()
368 wchar_t aBuff[MAX_PATH + 2];
369 DWORD aLenFilled = GetModuleFileNameW (0, aBuff, MAX_PATH + 1);
370 aBuff[MAX_PATH + 1] = 0;
373 return TCollection_AsciiString();
375 else if (aLenFilled <= MAX_PATH)
377 return TCollection_AsciiString (aBuff);
380 // buffer is not large enough (e.g. path uses \\?\ prefix)
381 wchar_t* aBuffDyn = NULL;
382 for (int anIter = 2;; ++anIter)
384 size_t aBuffLen = MAX_PATH * anIter;
385 aBuffDyn = reinterpret_cast<wchar_t*> (realloc (aBuffDyn, sizeof(wchar_t) * (aBuffLen + 1)));
386 if (aBuffDyn == NULL)
388 return TCollection_AsciiString();
391 aLenFilled = GetModuleFileNameW (NULL, aBuffDyn, DWORD(aBuffLen));
392 if (aLenFilled != aBuffLen)
394 aBuffDyn[aBuffLen] = L'\0';
395 TCollection_AsciiString aRes (aBuffDyn);
400 #elif defined(__APPLE__)
401 // determine buffer size
402 uint32_t aNbBytes = 0;
403 _NSGetExecutablePath (NULL, &aNbBytes);
406 return TCollection_AsciiString();
409 // retrieve path to executable (probably link)
410 NCollection_Array1<char> aBuff (0, aNbBytes);
411 _NSGetExecutablePath (&aBuff.ChangeFirst(), &aNbBytes);
412 aBuff[aNbBytes] = '\0';
414 // retrieve real path to executable (resolve links and normalize)
415 char* aResultBuf = realpath (&aBuff.First(), NULL);
416 if (aResultBuf == NULL)
418 return TCollection_AsciiString();
421 TCollection_AsciiString aProcessPath (aResultBuf);
422 free (aResultBuf); // according to man for realpath()
424 #elif defined(__linux__)
425 // get info from /proc/PID/exe
427 TCollection_AsciiString aSimLink = TCollection_AsciiString("/proc/") + TCollection_AsciiString(getpid()) + "/exe";
429 ssize_t aBytes = readlink (aSimLink.ToCString(), aBuff, 4096);
432 aBuff[aBytes] = '\0';
433 return TCollection_AsciiString(aBuff);
435 return TCollection_AsciiString();
438 return TCollection_AsciiString();
442 // =======================================================================
443 // function : ExecutableFolder
445 // =======================================================================
446 TCollection_AsciiString OSD_Process::ExecutableFolder()
448 TCollection_AsciiString aFullPath = ExecutablePath();
449 Standard_Integer aLastSplit = -1;
451 const char THE_FILE_SEPARATOR = '\\';
453 const char THE_FILE_SEPARATOR = '/';
455 for (Standard_Integer anIter = 1; anIter <= aFullPath.Length(); ++anIter)
457 if (aFullPath.Value (anIter) == THE_FILE_SEPARATOR)
463 if (aLastSplit != -1)
465 return aFullPath.SubString (1, aLastSplit);
467 return TCollection_AsciiString();