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.
15 //------------------------------------------------------------------------
17 //------------------------------------------------------------------------
22 #include <OSD_File.hxx>
23 #include <OSD_FromWhere.hxx>
24 #include <OSD_OSDError.hxx>
25 #include <OSD_Path.hxx>
26 #include <OSD_Printer.hxx>
27 #include <OSD_Protection.hxx>
28 #include <OSD_WhoAmI.hxx>
29 #include <Standard_PCharacter.hxx>
30 #include <Standard_ProgramError.hxx>
31 #include <TCollection_AsciiString.hxx>
33 const OSD_WhoAmI Iam = OSD_WFile;
35 #if defined (sun) || defined(SOLARIS)
48 #define NEWLINE '\10';
50 // ---------------------------------------------------------------------
51 // Create an empty file object
52 // ---------------------------------------------------------------------
54 OSD_File::OSD_File():OSD_FileNode()
56 ImperativeFlag = Standard_False;
59 myMode = OSD_ReadWrite;
60 myFILE = (Standard_Address) NULL;
65 // ---------------------------------------------------------------------
66 // Create and initialize a file object
67 // ---------------------------------------------------------------------
69 OSD_File::OSD_File(const OSD_Path& Name):OSD_FileNode(Name)
71 ImperativeFlag = Standard_False;
74 myMode = OSD_ReadWrite;
75 myFILE = (Standard_Address) NULL;
80 // protect against occasional use of myFileHande in Linux code
81 #define myFileHandle myFileHandle_is_only_for_Windows
83 // ---------------------------------------------------------------------
84 // Build a file if it doesn't exist or create again if it already exists
85 // ---------------------------------------------------------------------
87 void OSD_File::Build(const OSD_OpenMode Mode,
88 const OSD_Protection& Protect){
90 Standard_Integer internal_prot;
91 Standard_Integer internal_mode = O_CREAT | O_TRUNC ;
92 TCollection_AsciiString aBuffer;
94 if (myPath.Name().Length()==0)
95 Standard_ProgramError::Raise("OSD_File::Build : no name was given");
97 if (myFileChannel != -1)
98 Standard_ProgramError::Raise("OSD_File::Build : file is already open");
103 internal_prot = Protect.Internal();
105 const char* CMode = "r";
109 internal_mode |= O_RDONLY;
113 internal_mode |= O_WRONLY;
117 internal_mode |= O_RDWR;
122 myPath.SystemName( aBuffer );
123 myFileChannel = open (aBuffer.ToCString(), internal_mode, internal_prot);
124 if (myFileChannel >= 0) {
125 myFILE = fdopen (myFileChannel, CMode);
128 /* Handle OPEN errors */
130 myError.SetValue (errno, Iam, "Open");
136 // ---------------------------------------------------------------------
137 // Append to an existing file
138 // ---------------------------------------------------------------------
140 void OSD_File::Append(const OSD_OpenMode Mode,
141 const OSD_Protection& Protect){
143 Standard_Integer internal_prot;
144 Standard_Integer internal_mode = O_APPEND;;
145 TCollection_AsciiString aBuffer;
147 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
148 Standard_ProgramError::Raise("OSD_File::Append : it is a directory");
151 if (myPath.Name().Length()==0)
152 Standard_ProgramError::Raise("OSD_File::Append : no name was given");
154 if (myFileChannel != -1)
155 Standard_ProgramError::Raise("OSD_File::Append : file is already open");
157 internal_prot = Protect.Internal();
159 const char* CMode = "r";
163 internal_mode |= O_RDONLY;
167 internal_mode |= O_WRONLY;
171 internal_mode |= O_RDWR;
176 // If file doesn't exist, creates it.
178 if (!Exists()) internal_mode |= O_CREAT;
180 myPath.SystemName ( aBuffer );
181 myFileChannel = open (aBuffer.ToCString(), internal_mode, internal_prot);
182 if (myFileChannel >= 0)
183 myFILE = fdopen (myFileChannel, CMode);
185 /* Handle OPEN errors */
187 myError.SetValue (errno, Iam, "Open");
190 // ---------------------------------------------------------------------
192 // ---------------------------------------------------------------------
194 void OSD_File::Open(const OSD_OpenMode Mode,
195 const OSD_Protection& Protect){
197 Standard_Integer internal_prot;
198 Standard_Integer internal_mode = 0;
199 TCollection_AsciiString aBuffer;
201 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
202 myError.SetValue (1, Iam, "Could not be open : it is a directory");
205 if (myPath.Name().Length()==0)
206 Standard_ProgramError::Raise("OSD_File::Open : no name was given");
208 if (myFileChannel != -1)
209 Standard_ProgramError::Raise("OSD_File::Open : file is already open");
211 internal_prot = Protect.Internal();
213 const char* CMode = "r";
217 internal_mode |= O_RDONLY;
221 internal_mode |= O_WRONLY;
225 internal_mode |= O_RDWR;
230 myPath.SystemName ( aBuffer );
231 myFileChannel = open (aBuffer.ToCString(), internal_mode, internal_prot);
232 if (myFileChannel >= 0)
233 myFILE = fdopen (myFileChannel, CMode);
235 /* Handle OPEN errors */
237 myError.SetValue (errno, Iam, "Open");
242 // ---------------------------------------------------------------------
243 // ---------------------------------------------------------------------
244 void OSD_File::BuildTemporary(){
249 #if defined(vax) || defined(__vms) || defined(VAXVMS)
254 dummy = open("dummy", O_RDWR | O_CREAT); // Open a dummy file
255 myFileChannel = dummy - 1; // This is file channel of "fic" +1
256 close(dummy); // Close dummy file
257 unlink("dummy"); // Removes dummy file
260 char name[] = "/tmp/CSFXXXXXX";
261 myFileChannel = mkstemp( name );
263 TCollection_AsciiString aName ( name ) ;
264 OSD_Path aPath( aName ) ;
268 myFILE = fdopen( myFileChannel, "w+" ) ;
272 myMode = OSD_ReadWrite;
277 // ---------------------------------------------------------------------
278 // Read content of a file
279 // ---------------------------------------------------------------------
281 void OSD_File::Read(TCollection_AsciiString& Buffer,
282 const Standard_Integer Nbyte){
283 Standard_PCharacter readbuf;
286 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
287 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
290 if (myFileChannel == -1)
291 Standard_ProgramError::Raise("OSD_File::Read : file is not open");
293 if (Failed()) Perror();
295 if (myMode == OSD_WriteOnly)
296 Standard_ProgramError::Raise("OSD_File::Read : file is Write only");
299 Standard_ProgramError::Raise("OSD_File::Read : Nbyte is null");
301 TCollection_AsciiString transfert(Nbyte,' ');
302 readbuf = (Standard_PCharacter)transfert.ToCString();
304 status = read (myFileChannel, readbuf, Nbyte);
306 Buffer = transfert; // Copy transfert to Buffer
308 if (status == -1) myError.SetValue (errno, Iam, "Read");
310 if ( status < Nbyte ) myIO = EOF;
314 // ---------------------------------------------------------------------
315 // Read a line from a file
316 // ---------------------------------------------------------------------
318 void OSD_File::ReadLine(TCollection_AsciiString& Buffer,
319 const Standard_Integer Nbyte,
320 Standard_Integer& NByteRead)
322 Standard_PCharacter readbuf, abuffer;
324 if (OSD_File::KindOfFile() == OSD_DIRECTORY ) {
325 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
327 if (myFileChannel == -1){
328 Standard_ProgramError::Raise("OSD_File::ReadLine : file is not open");
333 if (myMode == OSD_WriteOnly) {
334 Standard_ProgramError::Raise("OSD_File::ReadLine : file is Write only");
337 Standard_ProgramError::Raise("OSD_File::ReadLine : Nbyte is null");
340 TCollection_AsciiString transfert(Nbyte,' ');
341 readbuf = (Standard_PCharacter)transfert.ToCString();
343 abuffer = fgets(readbuf, Nbyte, (FILE *) myFILE);
345 if (abuffer == NULL) {
346 if (!feof((FILE *) myFILE)) {
347 myError.SetValue (errno, Iam, "ReadLine");
357 NByteRead = (Standard_Integer)strlen(abuffer);
358 Buffer.SetValue(1,abuffer); // Copy transfert to Buffer
359 Buffer.Trunc(NByteRead);
362 // --------------------------------------------------------------------------
363 // OSD::KindOfFile Retourne le type de fichier.
364 // --------------------------------------------------------------------------
365 OSD_KindFile OSD_File::KindOfFile ( ) const{
368 TCollection_AsciiString FullName;
372 aPath.SystemName (FullName);
373 status = stat (FullName.ToCString() , &buffer );
375 if ( S_ISDIR(buffer.st_mode) ) { return OSD_DIRECTORY ; }
376 else if ( S_ISREG(buffer.st_mode) ) { return OSD_FILE ; }
377 else if ( S_ISLNK(buffer.st_mode) ) { return OSD_LINK ; }
378 else if ( S_ISSOCK(buffer.st_mode) ) { return OSD_SOCKET ; }
379 else { return OSD_UNKNOWN ; }
384 // --------------------------------------------------------------------------
385 // Read content of a file
386 // --------------------------------------------------------------------------
387 void OSD_File::Read(const Standard_Address Buffer,
388 const Standard_Integer Nbyte,
389 Standard_Integer& Readbyte)
394 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
395 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
398 if (myFileChannel == -1)
399 Standard_ProgramError::Raise("OSD_File::Read : file is not open");
401 if (Failed()) Perror();
403 if (myMode == OSD_WriteOnly)
404 Standard_ProgramError::Raise("OSD_File::Read : file is Write only");
407 Standard_ProgramError::Raise("OSD_File::Read : Nbyte is null");
410 Standard_ProgramError::Raise("OSD_File::Read : Buffer is null");
412 status = read (myFileChannel, (char*) Buffer, Nbyte);
414 if (status == -1) myError.SetValue (errno, Iam, "Read");
416 if ( status < Nbyte ) myIO = EOF;
421 // Write content of a file
423 void OSD_File::Write(const TCollection_AsciiString &Buffer,
424 const Standard_Integer Nbyte){
426 Standard_CString writebuf;
429 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
430 Standard_ProgramError::Raise("OSD_File::Write : it is a directory");
433 if (myFileChannel == -1)
434 Standard_ProgramError::Raise("OSD_File::Write : file is not open");
436 if (Failed()) Perror();
438 if (myMode == OSD_ReadOnly)
439 Standard_ProgramError::Raise("OSD_File::Write : file is Read only");
442 Standard_ProgramError::Raise("OSD_File::Write : Nbyte is null");
444 writebuf = Buffer.ToCString();
446 status = write (myFileChannel, writebuf, Nbyte);
448 if ( status == -1) myError.SetValue (errno, Iam, "Write");
450 if ( status < Nbyte ) myIO = EOF;
454 void OSD_File::Write(const Standard_Address Buffer,
455 const Standard_Integer Nbyte)
460 if (myFileChannel == -1)
461 Standard_ProgramError::Raise("OSD_File::Write : file is not open");
463 if (Failed()) Perror();
465 if (myMode == OSD_ReadOnly)
466 Standard_ProgramError::Raise("OSD_File::Write : file is Read only");
469 Standard_ProgramError::Raise("OSD_File::Write : Nbyte is null");
471 status = write (myFileChannel, (const char *)Buffer, Nbyte);
473 if ( status == -1) myError.SetValue (errno, Iam, "Write");
475 if ( status < Nbyte ) myIO = EOF;
482 // Move file pointer to a specified position
484 void OSD_File::Seek(const Standard_Integer Offset,
485 const OSD_FromWhere Whence){
488 if (myFileChannel == -1)
489 Standard_ProgramError::Raise("OSD_File::Seek : file is not open");
491 if (Failed()) Perror();
494 case OSD_FromBeginning :
504 myError.SetValue (EINVAL, Iam, "Seek");
507 off_t status = lseek (myFileChannel, Offset, iwhere);
508 if (status == -1) myError.SetValue (errno, Iam, "Seek");
518 void OSD_File::Close(){
521 if (myFileChannel == -1)
522 Standard_ProgramError::Raise("OSD_File::Close : file is not open");
524 if (Failed()) Perror();
526 // note: it probably should be single call to fclose()...
527 status = close (myFileChannel);
529 if (status == -1) myError.SetValue (errno, Iam, "Close");
531 if ( myFILE != NULL ) {
532 status = fclose ( (FILE*) myFILE );
541 // --------------------------------------------------------------------------
542 // Test if at end of file
543 // --------------------------------------------------------------------------
545 Standard_Boolean OSD_File::IsAtEnd(){
546 if (myFileChannel == -1)
547 Standard_ProgramError::Raise("OSD_File::IsAtEnd : file is not open");
549 if (myIO == EOF) return (Standard_True);
550 return (Standard_False);
555 /*void OSD_File::Link(const TCollection_AsciiString& ToFile){
556 if (myFileChannel == -1)
557 Standard_ProgramError::Raise("OSD_File::Link : file is not open");
559 TCollection_AsciiString aBuffer;
560 myPath.SystemName ( aBuffer );
561 link ( aBuffer.ToCString(), ToFile.ToCString() );
567 void OSD_File::SetLock(const OSD_LockType Lock){
570 if (myFileChannel == -1)
571 Standard_ProgramError::Raise("OSD_File::SetLock : file is not open");
579 case OSD_ExclusiveLock :
580 case OSD_WriteLock : lock = F_LOCK;
582 case OSD_ReadLock : return;
584 default : myError.SetValue (EINVAL, Iam, "SetLock");
588 if (fstat (myFileChannel, &buf) == -1) {
589 myError.SetValue (errno, Iam, "SetLock");
593 status = lockf(myFileChannel, lock, buf.st_size);
594 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
603 case OSD_ExclusiveLock :
604 case OSD_WriteLock : key.l_type = F_WRLCK;
606 case OSD_ReadLock : key.l_type = F_RDLCK;
608 case OSD_NoLock : return;
609 // default : myError.SetValue (EINVAL, Iam, "SetLock");
616 status = fcntl (myFileChannel, F_SETLKW, &key);
617 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
620 if (Lock == OSD_ExclusiveLock){
621 fstat (myFileChannel, &buf);
622 TCollection_AsciiString aBuffer;
623 myPath.SystemName ( aBuffer );
624 chmod( aBuffer.ToCString() ,buf.st_mode | S_ISGID);
625 ImperativeFlag = Standard_True;
632 case OSD_ExclusiveLock :
633 case OSD_WriteLock : lock = F_WRLCK;
635 case OSD_ReadLock : lock = F_RDLCK;
637 default : myError.SetValue (EINVAL, Iam, "SetLock");
640 status = flock (myFileChannel, lock);
641 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
650 // Remove a lock from a file
652 void OSD_File::UnLock(){
655 if (myFileChannel == -1)
656 Standard_ProgramError::Raise("OSD_File::UnLock : file is not open");
661 if (fstat(myFileChannel, &buf) == -1) {
662 myError.SetValue(errno, Iam, "UnsetLock");
666 status = lockf(myFileChannel,F_ULOCK, buf.st_size);
667 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
675 fstat (myFileChannel, &buf);
676 TCollection_AsciiString aBuffer;
677 myPath.SystemName ( aBuffer );
678 chmod(aBuffer.ToCString(),buf.st_mode & ~S_ISGID);
679 ImperativeFlag = Standard_False;
681 key.l_type = F_UNLCK;
682 status = fcntl (myFileChannel, F_SETLK, &key);
683 if (status == -1) myError.SetValue (errno, Iam, "UnSetLock");
686 status = flock (myFileChannel, LOCK_UN);
687 if (status == -1) myError.SetValue (errno, Iam, "UnSetLock");
690 else myLock = OSD_NoLock;
697 // Return lock of a file
699 OSD_LockType OSD_File::GetLock(){
706 // --------------------------------------------------------------------------
707 // Return size of a file
708 // --------------------------------------------------------------------------
710 Standard_Size OSD_File::Size(){
714 if (myPath.Name().Length()==0)
715 Standard_ProgramError::Raise("OSD_File::Size : empty file name");
717 TCollection_AsciiString aBuffer;
718 myPath.SystemName ( aBuffer );
719 status = stat( aBuffer.ToCString() ,&buffer );
721 myError.SetValue (errno, Iam, "Size");
725 return (Standard_Size)buffer.st_size;
729 // --------------------------------------------------------------------------
730 // Print contains of a file
731 // --------------------------------------------------------------------------
733 void OSD_File::Print (const OSD_Printer &WhichPrinter ){
735 TCollection_AsciiString PrinterName;
737 if (myPath.Name().Length()==0)
738 Standard_ProgramError::Raise("OSD_File::Print : empty file name");
740 WhichPrinter.Name(PrinterName);
742 TCollection_AsciiString aBuffer;
743 myPath.SystemName ( aBuffer );
745 if (PrinterName.Length()==0)
746 sprintf(buffer,"lp %s",aBuffer.ToCString());
748 sprintf(buffer,"lpr -P%s %s",PrinterName.ToCString(),aBuffer.ToCString());
750 if (system(buffer) != 0)
751 Standard_ProgramError::Raise("OSD_File::Print : No output device was available, or an error occurred");
755 // --------------------------------------------------------------------------
756 // Test if a file is open
757 // --------------------------------------------------------------------------
759 Standard_Boolean OSD_File::IsOpen()const{
760 return (myFileChannel != -1);
764 Standard_Boolean OSD_File::IsLocked(){
765 return(myLock != OSD_NoLock);
768 Standard_Boolean OSD_File::IsReadable()
770 TCollection_AsciiString FileName ;
772 myPath.SystemName(FileName) ;
774 if (access(FileName.ToCString(),F_OK|R_OK))
775 return Standard_False;
777 return Standard_True;
780 Standard_Boolean OSD_File::IsWriteable()
782 TCollection_AsciiString FileName ;
784 myPath.SystemName(FileName) ;
786 if (access(FileName.ToCString(),F_OK|R_OK|W_OK))
787 return Standard_False;
789 return Standard_True;
792 Standard_Boolean OSD_File::IsExecutable()
794 TCollection_AsciiString FileName ;
796 myPath.SystemName(FileName) ;
798 if (access(FileName.ToCString(),F_OK|X_OK))
799 return Standard_False;
801 return Standard_True;
804 int OSD_File::Capture(int theDescr) {
805 // Duplicate an old file descriptor of the given one to be able to restore output to it later.
806 int oldDescr = dup(theDescr);
807 // Redirect the output to this file
808 dup2(myFileChannel, theDescr);
810 // Return the old descriptor
814 void OSD_File::Rewind() {
815 rewind((FILE*)myFILE);
820 //------------------------------------------------------------------------
821 //------------------- Windows NT sources for OSD_File -------------------
822 //------------------------------------------------------------------------
826 #include <OSD_File.hxx>
827 #include <OSD_Protection.hxx>
828 #include <OSD_Printer.hxx>
829 #include <Standard_ProgramError.hxx>
831 #include <OSD_WNT_1.hxx>
835 #include <Standard_PCharacter.hxx>
836 #include <TCollection_ExtendedString.hxx>
844 #if defined(__CYGWIN32__) || defined(__MINGW32__)
848 #if defined(_MSC_VER)
849 #pragma comment( lib, "WSOCK32.LIB" )
850 #pragma comment( lib, "WINSPOOL.LIB" )
853 #define ACE_HEADER_SIZE ( sizeof ( ACCESS_ALLOWED_ACE ) - sizeof ( DWORD ) )
855 #define RAISE( arg ) Standard_ProgramError :: Raise ( ( arg ) )
856 #define TEST_RAISE( arg ) _test_raise ( myFileHandle, ( arg ) )
860 #define OPEN_APPEND 2
862 void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
864 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd ( const OSD_Protection&, BOOL, wchar_t* = NULL );
865 BOOL __fastcall _osd_wnt_sd_to_protection (
866 PSECURITY_DESCRIPTOR, OSD_Protection&, BOOL
868 BOOL __fastcall _osd_print (const Standard_PCharacter, const wchar_t* );
869 static int __fastcall _get_buffer(HANDLE, Standard_PCharacter&, DWORD, BOOL, BOOL);
871 static void __fastcall _test_raise ( HANDLE, Standard_CString );
872 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos);
873 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection );
874 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt );
875 static HANDLE __fastcall _open_file ( Standard_CString, OSD_OpenMode, DWORD, LPBOOL = NULL );
877 static OSD_SingleProtection __fastcall _get_protection ( DWORD );
878 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD );
880 typedef OSD_SingleProtection ( __fastcall *GET_PROT_FUNC ) ( DWORD );
882 Standard_Integer __fastcall _get_file_type ( Standard_CString, HANDLE );
884 // ---------------------------------------------------------------------
885 // Create an empty file object
886 // ---------------------------------------------------------------------
888 OSD_File :: OSD_File ()
890 ImperativeFlag = Standard_False;
894 myFileHandle = INVALID_HANDLE_VALUE;
895 } // end constructor ( 1 )
897 // ---------------------------------------------------------------------
898 // Create and initialize a file object
899 // ---------------------------------------------------------------------
901 OSD_File :: OSD_File ( const OSD_Path& Name ) : OSD_FileNode ( Name )
903 ImperativeFlag = Standard_False;
908 myFileHandle = INVALID_HANDLE_VALUE;
909 } // end constructor ( 2 )
911 // ---------------------------------------------------------------------
912 // Redirect a standard handle (fileno(stdout), fileno(stdin) or
913 // fileno(stderr) to this OSD_File and return the copy of the original
917 // aTmp.BuildTemporary();
918 // int stdfd = _fileno(stdout);
920 // int oldout = aTmp.Capture(stdfd);
921 // cout << "Some output to the file" << endl;
925 // _dup2(oldout, stdfd); // Restore standard output
927 // ---------------------------------------------------------------------
928 int OSD_File::Capture(int theDescr) {
929 // Get POSIX file descriptor from this file handle
930 int dFile = _open_osfhandle(reinterpret_cast<intptr_t>(myFileHandle), myMode);
934 _osd_wnt_set_error ( myError, OSD_WFile, myFileHandle );
938 // Duplicate an old file descriptor of the given one to be able to restore output to it later.
939 int oldDescr = _dup(theDescr);
940 // Redirect the output to this file
941 _dup2(dFile, theDescr);
943 // Return the old descriptor
947 void OSD_File::Rewind() {
948 LARGE_INTEGER aDistanceToMove = { 0 };
949 aDistanceToMove.QuadPart = 0;
950 SetFilePointerEx(myFileHandle, aDistanceToMove, NULL, FILE_BEGIN);
953 // protect against occasional use of myFileHande in Windows code
954 #define myFileChannel myFileChannel_is_only_for_Linux
956 // ---------------------------------------------------------------------
957 // Build a file if it doesn't exist or create again if it already exists
958 // ---------------------------------------------------------------------
960 void OSD_File :: Build ( const OSD_OpenMode Mode, const OSD_Protection& Protect) {
962 TCollection_AsciiString fName;
964 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
965 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
968 if (myFileHandle != INVALID_HANDLE_VALUE)
970 RAISE( "OSD_File :: Build (): incorrect call - file already opened" );
973 myPath.SystemName ( fName );
975 if ( fName.IsEmpty () )
977 RAISE( "OSD_File :: Build (): incorrent call - no filename given" );
979 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_NEW );
981 if (myFileHandle == INVALID_HANDLE_VALUE)
983 _osd_wnt_set_error ( myError, OSD_WFile );
987 SetProtection ( Protect );
995 } // end OSD_File :: Build
999 // ---------------------------------------------------------------------
1001 // ---------------------------------------------------------------------
1003 void OSD_File :: Open (const OSD_OpenMode Mode, const OSD_Protection& /*Protect*/)
1006 TCollection_AsciiString fName;
1009 if (myFileHandle != INVALID_HANDLE_VALUE)
1011 RAISE( "OSD_File :: Open (): incorrect call - file already opened" );
1014 myPath.SystemName ( fName );
1016 if ( fName.IsEmpty () )
1018 RAISE( "OSD_File :: Open (): incorrent call - no filename given" );
1020 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_OLD );
1022 if (myFileHandle == INVALID_HANDLE_VALUE) {
1024 _osd_wnt_set_error ( myError, OSD_WFile );
1028 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
1030 } // end OSD_File :: Open
1032 // ---------------------------------------------------------------------
1033 // Append to an existing file
1034 // ---------------------------------------------------------------------
1036 void OSD_File :: Append ( const OSD_OpenMode Mode, const OSD_Protection& Protect) {
1039 TCollection_AsciiString fName;
1041 if (myFileHandle != INVALID_HANDLE_VALUE)
1043 RAISE( "OSD_File :: Append (): incorrect call - file already opened" );
1046 myPath.SystemName ( fName );
1048 if ( fName.IsEmpty () )
1050 RAISE( "OSD_File :: Append (): incorrent call - no filename given" );
1052 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_APPEND, &fNew );
1054 if (myFileHandle == INVALID_HANDLE_VALUE)
1056 _osd_wnt_set_error ( myError, OSD_WFile );
1062 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
1063 Seek ( 0, OSD_FromEnd );
1067 SetProtection ( Protect );
1077 } // end OSD_File :: Append
1079 // ---------------------------------------------------------------------
1080 // Read content of a file
1081 // ---------------------------------------------------------------------
1083 void OSD_File :: Read (
1084 TCollection_AsciiString& Buffer, const Standard_Integer Nbyte
1087 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1089 cout << " OSD_File::Read : it is a directory " << endl;
1092 // Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1095 Standard_Integer NbyteRead;
1097 TEST_RAISE( "Read" );
1099 char* buff = new Standard_Character[ Nbyte + 1 ];
1101 Read ( buff, Nbyte, NbyteRead );
1103 buff[ NbyteRead ] = 0;
1105 if ( NbyteRead != 0 )
1115 } // end OSD_File :: Read
1117 // ---------------------------------------------------------------------
1118 // Read a line from a file
1119 // ---------------------------------------------------------------------
1121 // Modified so that we have <nl> at end of line if we have read <nl> or <cr>
1123 // by LD 17 dec 98 for B4.4
1125 void OSD_File :: ReadLine (
1126 TCollection_AsciiString& Buffer,
1127 const Standard_Integer NByte, Standard_Integer& NbyteRead
1132 Standard_Character peekChar;
1133 Standard_PCharacter ppeekChar;
1134 Standard_PCharacter cBuffer;
1137 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1138 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1141 TEST_RAISE( "ReadLine" );
1143 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1145 RAISE( "OSD_File :: ReadLine (): attempt to read from write only pipe" );
1147 // +----> leave space for end-of-string
1148 // | plus <CR><LF> sequence
1151 ppeekChar=&peekChar;
1152 cBuffer = new Standard_Character[ NByte + 3 ];
1154 if ( myIO & FLAG_FILE ) {
1156 if (!ReadFile (myFileHandle, cBuffer, NByte, &dwBytesRead, NULL)) { // an error occured
1158 _osd_wnt_set_error ( myError, OSD_WFile );
1162 } else if ( dwBytesRead == 0 ) { // end-of-file reached
1169 myIO &= ~FLAG_EOF ; // if the file increased since last read (LD)
1170 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1172 if ( NbyteRead == -1 ) // last character in the buffer is <CR> -
1173 { // peek next character to see if it is a <LF>
1174 if (!ReadFile (myFileHandle, ppeekChar, 1, &dwDummy, NULL)) {
1176 _osd_wnt_set_error ( myError, OSD_WFile );
1178 } else if ( dwDummy != 0 ) { // end-of-file reached ?
1180 if (peekChar != '\n') // if we did not get a <CR><LF> sequence
1182 // adjust file position
1183 LARGE_INTEGER aDistanceToMove = { 0 };
1184 aDistanceToMove.QuadPart = -1;
1185 SetFilePointerEx(myFileHandle, aDistanceToMove, NULL, FILE_CURRENT);
1190 NbyteRead = dwBytesRead;
1192 } else if ( aSeekPos != 0 )
1194 LARGE_INTEGER aDistanceToMove = { 0 };
1195 aDistanceToMove.QuadPart = aSeekPos;
1196 SetFilePointerEx(myFileHandle, aDistanceToMove, NULL, FILE_CURRENT);
1201 } else if ( myIO & FLAG_SOCKET || myIO & FLAG_PIPE || myIO & FLAG_NAMED_PIPE ) {
1203 dwBytesRead = (DWORD)_get_buffer (myFileHandle, cBuffer,
1204 (DWORD)NByte, TRUE, myIO & FLAG_SOCKET);
1206 if ( ( int )dwBytesRead == -1 ) { // an error occured
1208 _osd_wnt_set_error ( myError, OSD_WFile );
1212 } else if ( dwBytesRead == 0 ) { // connection closed - set end-of-file flag
1220 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1222 if (NbyteRead == -1) // last character in the buffer is <CR> -
1223 { // peek next character to see if it is a <LF>
1224 NbyteRead = dwBytesRead; // (LD) always fits this case.
1226 dwDummy = _get_buffer (myFileHandle, ppeekChar, 1, TRUE, myIO & FLAG_SOCKET);
1227 if ( ( int )dwDummy == -1 ) { // an error occured
1229 _osd_wnt_set_error ( myError, OSD_WFile );
1231 } else if ( dwDummy != 0 ) { // connection closed ?
1233 if ( peekChar == '\n' ) // we got a <CR><LF> sequence
1235 dwBytesRead++ ; // (LD) we have to jump <LF>
1240 } else if (aSeekPos != 0)
1242 dwBytesRead = dwBytesRead + aSeekPos;
1245 // Don't rewrite datas in cBuffer.
1247 Standard_PCharacter cDummyBuffer = new Standard_Character[ NByte + 3 ];
1249 // remove pending input
1250 _get_buffer (myFileHandle, cDummyBuffer, dwBytesRead, FALSE, myIO & FLAG_SOCKET);
1251 delete [] cDummyBuffer ;
1257 RAISE( "OSD_File :: ReadLine (): incorrect call - file is a directory" );
1259 if ( !Failed () && !IsAtEnd () )
1263 delete [] (Standard_PCharacter)cBuffer;
1265 } // end OSD_File :: ReadLine
1267 // --------------------------------------------------------------------------
1268 // Read content of a file
1269 // --------------------------------------------------------------------------
1271 void OSD_File :: Read (
1272 const Standard_Address Buffer,
1273 const Standard_Integer Nbyte, Standard_Integer& Readbyte
1278 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1279 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1282 TEST_RAISE( "Read" );
1284 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1286 RAISE( "OSD_File :: Read (): attempt to read from write only pipe" );
1288 if (!ReadFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesRead, NULL)) {
1290 _osd_wnt_set_error ( myError, OSD_WFile );
1293 } else if ( dwBytesRead == 0 )
1301 Readbyte = ( Standard_Integer )dwBytesRead;
1303 } // end OSD_File :: Read
1305 void OSD_File :: Write (
1306 const TCollection_AsciiString& Buffer,
1307 const Standard_Integer Nbyte
1310 Write ( ( Standard_Address )Buffer.ToCString (), Nbyte );
1312 } // end OSD_File :: Write
1314 // --------------------------------------------------------------------------
1315 // Write content of a file
1316 // --------------------------------------------------------------------------
1318 void OSD_File :: Write (
1319 const Standard_Address Buffer,
1320 const Standard_Integer Nbyte
1323 DWORD dwBytesWritten;
1325 TEST_RAISE( "Write" );
1327 if ( myIO & FLAG_PIPE && myIO & FLAG_READ_PIPE )
1329 RAISE( "OSD_File :: Write (): attempt to write to read only pipe" );
1331 if (!WriteFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesWritten, NULL) ||
1332 dwBytesWritten != (DWORD)Nbyte)
1334 _osd_wnt_set_error ( myError, OSD_WFile );
1336 } // end OSD_File :: Write
1338 void OSD_File :: Seek (
1339 const Standard_Integer Offset, const OSD_FromWhere Whence
1342 DWORD dwMoveMethod = 0;
1344 TEST_RAISE( "Seek" );
1346 if ( myIO & FLAG_FILE || myIO & FLAG_DIRECTORY ) {
1350 case OSD_FromBeginning:
1352 dwMoveMethod = FILE_BEGIN;
1358 dwMoveMethod = FILE_CURRENT;
1364 dwMoveMethod = FILE_END;
1370 RAISE( "OSD_File :: Seek (): invalid parameter" );
1373 LARGE_INTEGER aDistanceToMove, aNewFilePointer = { 0 };
1374 aDistanceToMove.QuadPart = Offset;
1376 if (!SetFilePointerEx(myFileHandle, aDistanceToMove, &aNewFilePointer, dwMoveMethod))
1378 _osd_wnt_set_error ( myError, OSD_WFile );
1384 } // end OSD_File :: Seek
1386 // --------------------------------------------------------------------------
1388 // --------------------------------------------------------------------------
1390 void OSD_File :: Close () {
1392 TEST_RAISE( "Close" );
1394 CloseHandle (myFileHandle);
1396 myFileHandle = INVALID_HANDLE_VALUE;
1399 } // end OSD_File :: Close
1401 // --------------------------------------------------------------------------
1402 // Test if at end of file
1403 // --------------------------------------------------------------------------
1405 Standard_Boolean OSD_File :: IsAtEnd () {
1407 TEST_RAISE( "IsAtEnd" );
1409 if (myIO & FLAG_EOF)
1410 return Standard_True ;
1411 return Standard_False ;
1413 } // end OSD_File :: IsAtEnd
1415 OSD_KindFile OSD_File :: KindOfFile () const {
1417 OSD_KindFile retVal;
1418 Standard_Integer flags;
1420 if (myFileHandle == INVALID_HANDLE_VALUE) {
1422 TCollection_AsciiString fName;
1424 myPath.SystemName ( fName );
1426 if ( fName.IsEmpty () )
1428 RAISE( "OSD_File :: KindOfFile (): incorrent call - no filename given" );
1430 flags = _get_file_type (fName.ToCString(), INVALID_HANDLE_VALUE);
1436 switch ( flags & FLAG_TYPE ) {
1444 case FLAG_DIRECTORY:
1446 retVal = OSD_DIRECTORY;
1452 retVal = OSD_SOCKET;
1458 retVal = OSD_UNKNOWN;
1464 } // end OSD_File :: KindOfFile
1466 //-------------------------------------------------debutpri???980424
1468 typedef struct _osd_wnt_key {
1471 const char* keyPath;
1476 void OSD_File::BuildTemporary () {
1479 wchar_t tmpPath[ MAX_PATH ];
1482 // Windows Registry not supported by UWP
1486 OSD_WNT_KEY regKey[ 2 ] = {
1488 { HKEY_LOCAL_MACHINE,
1489 "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"
1492 ".DEFAULT\\Environment"
1497 for ( int i = 0; i < 2; ++i ) {
1500 regKey[ i ].hKey, regKey[ i ].keyPath, 0, KEY_QUERY_VALUE, &hKey
1507 if ( RegQueryValueExW (
1508 hKey, L"TEMP", NULL, &dwType, NULL, &dwSize
1512 wchar_t* kVal = (wchar_t*)HeapAlloc (
1513 GetProcessHeap (), HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
1514 dwSize + sizeof (wchar_t)
1517 RegQueryValueExW ( hKey, L"TEMP", NULL, &dwType, ( LPBYTE )kVal, &dwSize );
1519 if ( dwType == REG_EXPAND_SZ )
1521 ExpandEnvironmentStringsW ( kVal, tmpPath, MAX_PATH );
1525 StringCchCopyW (tmpPath, _countof(tmpPath), kVal);
1527 HeapFree ( GetProcessHeap (), 0, ( LPVOID )kVal );
1532 RegCloseKey ( hKey );
1540 if (GetTempPathW(_countof(tmpPath), tmpPath))
1543 if ( !fOK ) StringCchCopyW(tmpPath, _countof(tmpPath), L"./");
1545 GetTempFileNameW ( tmpPath, L"CSF", 0, tmpPath );
1550 char tmpPathA[MAX_PATH];
1551 WideCharToMultiByte(CP_UTF8, 0, tmpPath, -1, tmpPathA, sizeof(tmpPathA), NULL, NULL);
1552 SetPath(OSD_Path(tmpPathA));
1554 Build ( OSD_ReadWrite, prt );
1555 } // end OSD_File :: BuildTemporary
1557 //-------------------------------------------------finpri???980424
1559 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1562 #define __leave return
1565 void OSD_File :: SetLock ( const OSD_LockType Lock ) {
1570 TEST_RAISE( "SetLock" );
1572 ZeroMemory ( &ovlp, sizeof ( OVERLAPPED ) );
1576 if ( ( myLock = Lock ) == OSD_NoLock ) {
1581 } else if ( myLock == OSD_ReadLock || myLock == OSD_ExclusiveLock ) {
1583 dwFlags = LOCKFILE_EXCLUSIVE_LOCK;
1589 LARGE_INTEGER aSize;
1590 aSize.QuadPart = Size();
1591 if (!LockFileEx (myFileHandle, dwFlags, 0, aSize.LowPart, aSize.HighPart, &ovlp)) {
1593 _osd_wnt_set_error ( myError, OSD_WFile );
1598 ImperativeFlag = Standard_True;
1605 leave: ; // added for VisualAge
1607 } // end OSD_File :: SetLock
1609 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1615 void OSD_File :: UnLock () {
1617 TEST_RAISE( "Unlock" );
1619 if ( ImperativeFlag ) {
1621 LARGE_INTEGER aSize;
1622 aSize.QuadPart = Size();
1624 OVERLAPPED anOverlappedArea;
1625 anOverlappedArea.Offset = 0;
1626 anOverlappedArea.OffsetHigh = 0;
1628 if (!UnlockFileEx(myFileHandle, 0, aSize.LowPart, aSize.HighPart,&anOverlappedArea))
1629 _osd_wnt_set_error ( myError, OSD_WFile );
1631 ImperativeFlag = Standard_False;
1635 } // end OSD_File :: UnLock
1637 OSD_LockType OSD_File :: GetLock () {
1641 } // end OSD_File :: GetLock
1643 Standard_Boolean OSD_File :: IsLocked () {
1645 TEST_RAISE( "IsLocked" );
1647 return ImperativeFlag;
1649 } // end OSD_File :: IsLocked
1652 // --------------------------------------------------------------------------
1653 // Return size of a file
1654 // --------------------------------------------------------------------------
1656 Standard_Size OSD_File::Size()
1659 #if (_WIN32_WINNT >= 0x0500)
1660 LARGE_INTEGER aSize;
1662 if (GetFileSizeEx (myFileHandle, &aSize) == 0)
1664 _osd_wnt_set_error (myError, OSD_WFile);
1666 return (Standard_Size)aSize.QuadPart;
1668 DWORD aSize = GetFileSize (myFileHandle, NULL);
1669 if (aSize == INVALID_FILE_SIZE)
1671 _osd_wnt_set_error (myError, OSD_WFile);
1677 // --------------------------------------------------------------------------
1678 // Print contains of a file
1679 // --------------------------------------------------------------------------
1680 void OSD_File :: Print ( const OSD_Printer& WhichPrinter) {
1682 if (myFileHandle != INVALID_HANDLE_VALUE)
1684 RAISE( "OSD_File :: Print (): incorrect call - file opened" );
1686 TCollection_AsciiString pName, fName;
1688 WhichPrinter.Name ( pName );
1689 myPath.SystemName ( fName );
1690 TCollection_ExtendedString fNameW(fName);
1692 if ( !_osd_print ( (Standard_PCharacter)pName.ToCString (),
1693 (const wchar_t*)fNameW.ToExtString () ) )
1695 _osd_wnt_set_error ( myError, OSD_WFile );
1699 } // end OSD_File :: Print
1700 // --------------------------------------------------------------------------
1701 // Test if a file is open
1702 // --------------------------------------------------------------------------
1704 Standard_Boolean OSD_File :: IsOpen () const {
1706 return myFileHandle != INVALID_HANDLE_VALUE;
1708 } // end OSD_File :: IsOpen
1710 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1713 #define __leave return retVal
1717 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd (
1718 const OSD_Protection& prot, BOOL fDir, wchar_t* fName
1724 HANDLE hProcess = NULL;
1729 DWORD dwAccessAdmin;
1730 DWORD dwAccessGroup;
1731 DWORD dwAccessOwner;
1732 DWORD dwAccessWorld;
1733 DWORD dwAccessAdminDir;
1734 // DWORD dwAccessGroupDir;
1735 DWORD dwAccessOwnerDir;
1736 // DWORD dwAccessWorldDir;
1737 DWORD dwACLsize = sizeof ( ACL );
1739 PTOKEN_OWNER pTkOwner = NULL;
1740 PTOKEN_GROUPS pTkGroups = NULL;
1741 PTOKEN_PRIMARY_GROUP pTkPrimaryGroup = NULL;
1742 PSECURITY_DESCRIPTOR retVal = NULL;
1743 PSECURITY_DESCRIPTOR pfSD = NULL;
1751 if ( !OpenProcessToken (
1752 GetCurrentProcess (), TOKEN_QUERY, &hProcess
1756 if ( ( pTkGroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
1757 hProcess, TokenGroups
1762 if ( ( pTkOwner = ( PTOKEN_OWNER )GetTokenInformationEx (
1763 hProcess, TokenOwner
1768 if ( ( pTkPrimaryGroup = ( PTOKEN_PRIMARY_GROUP )GetTokenInformationEx (
1769 hProcess, TokenPrimaryGroup
1776 if ( fName == NULL )
1778 pSIDowner = pTkOwner -> Owner;
1782 pfSD = GetFileSecurityEx ( fName, OWNER_SECURITY_INFORMATION );
1784 if ( pfSD == NULL || !GetSecurityDescriptorOwner ( pfSD, &pSIDowner, &fDummy ) ) {
1793 pSIDadmin = AdminSid ();
1794 pSIDworld = WorldSid ();
1796 dwAccessAdmin = _get_access_mask ( prot.System () );
1797 dwAccessGroup = _get_access_mask ( prot.Group () );
1798 dwAccessOwner = _get_access_mask ( prot.User () );
1799 dwAccessWorld = _get_access_mask ( prot.World () );
1801 dwAccessAdminDir = _get_dir_access_mask ( prot.System () );
1802 // dwAccessGroupDir = _get_dir_access_mask ( prot.Group () );
1803 dwAccessOwnerDir = _get_dir_access_mask ( prot.User () );
1804 // dwAccessWorldDir = _get_dir_access_mask ( prot.World () );
1806 if ( dwAccessGroup != 0 ) {
1808 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1810 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1812 if ( !NtPredefinedSid ( pSIDtemp ) &&
1813 !EqualSid ( pSIDtemp, pSIDworld ) &&
1814 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1815 IsValidSid ( pSIDtemp )
1818 dwACLsize += ( ( GetLengthSid ( pSIDtemp ) + ACE_HEADER_SIZE ) << j );
1824 dwACLsize += ( ( ( GetLengthSid ( pSIDowner ) + ACE_HEADER_SIZE ) << j ) +
1825 ( ( GetLengthSid ( pSIDadmin ) + ACE_HEADER_SIZE ) << j ) +
1826 ( ( GetLengthSid ( pSIDworld ) + ACE_HEADER_SIZE ) << j )
1829 if ( ( pACL = CreateAcl ( dwACLsize ) ) == NULL ) __leave;
1831 if ( dwAccessAdmin != 0 )
1833 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1840 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1844 pFileACE -> dwMask = dwAccessAdminDir;
1845 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1846 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1850 FreeAce ( pFileACE );
1854 if ( dwAccessOwner != 0 )
1856 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1857 dwAccessOwner, 0, pSIDowner
1862 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1866 pFileACE -> dwMask = dwAccessOwnerDir;
1867 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1868 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1872 FreeAce ( pFileACE );
1876 if ( dwAccessWorld != 0 )
1878 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1879 dwAccessWorld, 0, pSIDworld
1884 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1888 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1889 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1893 FreeAce ( pFileACE );
1897 if ( dwAccessGroup != 0 ) {
1899 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1901 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1903 if ( !NtPredefinedSid ( pSIDtemp ) &&
1904 !EqualSid ( pSIDtemp, pSIDworld ) &&
1905 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1906 IsValidSid ( pSIDtemp )
1909 if ( dwAccessGroup != 0 )
1911 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1912 dwAccessGroup, 0, pSIDtemp
1917 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1921 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1922 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1926 FreeAce ( pFileACE );
1936 if ( ( retVal = AllocSD () ) == NULL ) __leave;
1938 if ( !SetSecurityDescriptorDacl ( retVal, TRUE, pACL, TRUE ) ) __leave;
1948 if ( retVal != NULL )
1952 else if ( pACL != NULL )
1960 if ( hProcess != NULL ) CloseHandle ( hProcess );
1961 if ( pTkOwner != NULL ) FreeTokenInformation ( pTkOwner );
1962 if ( pTkGroups != NULL ) FreeTokenInformation ( pTkGroups );
1963 if ( pTkPrimaryGroup != NULL ) FreeTokenInformation ( pTkPrimaryGroup );
1964 if ( pfSD != NULL ) FreeFileSecurity ( pfSD );
1969 leave: ; // added for VisualAge
1974 } // end _osd_wnt_protection_to_sd */
1977 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1983 static void __fastcall _test_raise ( HANDLE hFile, Standard_CString str ) {
1985 if (hFile == INVALID_HANDLE_VALUE) {
1986 TCollection_AsciiString buff = "OSD_File :: ";
1988 buff += " (): wrong access";
1990 Standard_ProgramError::Raise(buff.ToCString());
1993 } // end _test_raise
1995 // Returns number of bytes in the string (including end \n, but excluding \r);
1997 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos)
2000 Standard_PCharacter ptr;
2002 buffer[ dwBuffSize ] = 0;
2005 while ( *ptr != 0 ) {
2009 ptr++ ; // jump newline char.
2011 theSeekPos = (LONG)(ptr - buffer - dwBuffSize);
2012 return (Standard_Integer)(ptr - buffer);
2014 else if ( *ptr == '\r' && ptr[ 1 ] == '\n' )
2016 *(ptr++) = '\n' ; // Substitue carriage return by newline.
2018 theSeekPos = (LONG)(ptr + 1 - buffer - dwBuffSize);
2019 return (Standard_Integer)(ptr - buffer);
2021 else if ( *ptr == '\r' && ptr[ 1 ] == 0 ) {
2022 *ptr = '\n' ; // Substitue carriage return by newline
2034 static int __fastcall _get_buffer (
2036 Standard_PCharacter& buffer,
2038 BOOL fPeek, BOOL fSocket
2048 flags = fPeek ? MSG_PEEK : 0;
2050 retVal = recv ( ( SOCKET )hChannel, buffer, ( int )dwSize, flags );
2052 if ( retVal == SOCKET_ERROR ) retVal = -1;
2058 if ( !PeekNamedPipe (
2059 hChannel, buffer, dwSize, &dwBytesRead, &dwDummy, &dwDummy
2060 ) && GetLastError () != ERROR_BROKEN_PIPE
2067 retVal = ( int )dwBytesRead;
2071 if ( !ReadFile ( hChannel, buffer, dwSize, &dwBytesRead, NULL ) )
2077 retVal = ( int )dwBytesRead;
2085 } // end _get_buffer
2088 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection prt ) {
2102 retVal = FILE_GENERIC_READ;
2108 retVal = FILE_GENERIC_WRITE;
2114 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
2120 retVal = FILE_GENERIC_EXECUTE;
2126 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
2132 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2138 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2150 retVal = FILE_GENERIC_READ | DELETE;
2156 retVal = FILE_GENERIC_WRITE | DELETE;
2162 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE;
2168 retVal = FILE_GENERIC_EXECUTE | DELETE;
2174 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE;
2180 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2186 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2192 RAISE( "_get_access_mask (): incorrect parameter" );
2198 } // end _get_access_mask
2200 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt ) {
2214 retVal = GENERIC_READ;
2220 retVal = GENERIC_WRITE;
2226 retVal = GENERIC_READ | GENERIC_WRITE;
2232 retVal = GENERIC_EXECUTE;
2238 retVal = GENERIC_READ | GENERIC_EXECUTE;
2244 retVal = GENERIC_WRITE | GENERIC_EXECUTE;
2250 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
2262 retVal = GENERIC_READ | DELETE;
2268 retVal = GENERIC_WRITE | DELETE;
2274 retVal = GENERIC_READ | GENERIC_WRITE | DELETE;
2280 retVal = GENERIC_EXECUTE | DELETE;
2286 retVal = GENERIC_READ | GENERIC_EXECUTE | DELETE;
2292 retVal = GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2298 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2304 RAISE( "_get_dir_access_mask (): incorrect parameter" );
2310 } // end _get_dir_access_mask
2312 static HANDLE __fastcall _open_file (
2313 Standard_CString fName,
2315 DWORD dwOptions, LPBOOL fNew
2318 HANDLE retVal = INVALID_HANDLE_VALUE;
2319 DWORD dwDesiredAccess = 0;
2320 DWORD dwCreationDistribution;
2326 dwDesiredAccess = GENERIC_READ;
2332 dwDesiredAccess = GENERIC_WRITE;
2338 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2344 RAISE( "_open_file (): incorrect parameter" );
2348 dwCreationDistribution = ( dwOptions != OPEN_NEW ) ? OPEN_EXISTING : CREATE_ALWAYS;
2350 // make wide character string from UTF-8
2351 TCollection_ExtendedString fNameW(fName, Standard_True);
2353 retVal = CreateFileW (
2354 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2355 FILE_SHARE_READ | FILE_SHARE_WRITE,
2356 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2359 CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams = {};
2360 pCreateExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
2361 pCreateExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
2362 pCreateExParams.lpSecurityAttributes = NULL;
2363 pCreateExParams.hTemplateFile = NULL;
2364 retVal = CreateFile2 (
2365 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2366 FILE_SHARE_READ | FILE_SHARE_WRITE,
2367 dwCreationDistribution, &pCreateExParams
2370 if ( retVal == INVALID_HANDLE_VALUE &&
2371 dwOptions == OPEN_APPEND &&
2372 GetLastError () == ERROR_FILE_NOT_FOUND
2376 dwCreationDistribution = CREATE_ALWAYS;
2378 retVal = CreateFileW (
2379 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2380 FILE_SHARE_READ | FILE_SHARE_WRITE,
2381 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2384 CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams2 = {};
2385 pCreateExParams2.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
2386 pCreateExParams2.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
2387 pCreateExParams2.lpSecurityAttributes = NULL;
2388 pCreateExParams2.hTemplateFile = NULL;
2389 retVal = CreateFile2(
2390 (const wchar_t*)fNameW.ToExtString(), dwDesiredAccess,
2391 FILE_SHARE_READ | FILE_SHARE_WRITE,
2392 dwCreationDistribution, &pCreateExParams2
2404 Standard_Integer __fastcall _get_file_type (
2405 Standard_CString fName, HANDLE fileHandle
2408 Standard_Integer retVal = 0;
2411 fileType = (fileHandle == INVALID_HANDLE_VALUE ?
2412 FILE_TYPE_DISK : GetFileType (fileHandle));
2414 switch ( fileType ) {
2416 case FILE_TYPE_UNKNOWN:
2418 retVal = FLAG_SOCKET;
2422 case FILE_TYPE_DISK:
2424 // make wide character string from UTF-8
2425 TCollection_ExtendedString fNameW(fName, Standard_True);
2427 WIN32_FILE_ATTRIBUTE_DATA aFileInfo;
2428 if (GetFileAttributesExW((const wchar_t*)fNameW.ToExtString(), GetFileExInfoStandard, &aFileInfo))
2430 retVal = aFileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ? FLAG_DIRECTORY : FLAG_FILE;
2434 retVal = 0x80000000;
2438 case FILE_TYPE_CHAR:
2440 retVal = FLAG_DEVICE;
2444 case FILE_TYPE_PIPE:
2454 } // end _get_file_type
2456 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2459 #define __leave return retVal
2463 // None of the existing security APIs are supported in a UWP applications
2464 BOOL __fastcall _osd_wnt_sd_to_protection (
2465 PSECURITY_DESCRIPTOR pSD, OSD_Protection& prot, BOOL fDir
2476 DWORD dwAccessOwner = 0;
2477 DWORD dwAccessGroup = 0;
2478 DWORD dwAccessAdmin = 0;
2479 DWORD dwAccessWorld = 0;
2480 BOOL retVal = FALSE;
2481 GET_PROT_FUNC _get_prot_func = fDir ? &_get_protection_dir : &_get_protection;
2485 if ( !GetSecurityDescriptorOwner ( pSD, &pSIDowner, &fDefaulted ) ) __leave;
2487 if ( !GetSecurityDescriptorDacl ( pSD, &fPresent, &pACL, &fDefaulted ) ||
2491 if ( pSIDowner == NULL || pACL == NULL ) {
2493 SetLastError ( ERROR_NO_SECURITY_ON_OBJECT );
2498 pSIDadmin = AdminSid ();
2499 pSIDworld = WorldSid ();
2501 for ( i = 0; i < ( int )pACL -> AceCount; ++i ) {
2503 if ( GetAce ( pACL, i, &pACE ) ) {
2505 if ( EqualSid ( pSIDowner, GET_SID( pACE ) ) )
2507 dwAccessOwner = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2508 0 : *GET_MSK( pACE );
2510 else if ( EqualSid ( pSIDadmin, GET_SID( pACE ) ) )
2512 dwAccessAdmin = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2513 0 : *GET_MSK( pACE );
2515 else if ( EqualSid ( pSIDworld, GET_SID( pACE ) ) )
2517 dwAccessWorld = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2518 0 : *GET_MSK( pACE );
2522 dwAccessGroup = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2523 0 : *GET_MSK( pACE );
2530 ( *_get_prot_func ) ( dwAccessAdmin ),
2531 ( *_get_prot_func ) ( dwAccessOwner ),
2532 ( *_get_prot_func ) ( dwAccessGroup ),
2533 ( *_get_prot_func ) ( dwAccessWorld )
2543 leave: ; // added for VisualAge
2548 } // end _osd_wnt_sd_to_protection
2551 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2557 static OSD_SingleProtection __fastcall _get_protection ( DWORD mask ) {
2559 OSD_SingleProtection retVal;
2563 case FILE_GENERIC_READ:
2569 case FILE_GENERIC_WRITE:
2575 case FILE_GENERIC_READ | FILE_GENERIC_WRITE:
2581 case FILE_GENERIC_EXECUTE:
2587 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE:
2593 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2599 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2611 case FILE_GENERIC_READ | DELETE:
2617 case FILE_GENERIC_WRITE | DELETE:
2623 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE:
2629 case FILE_GENERIC_EXECUTE | DELETE:
2635 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE:
2641 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2647 case FILE_ALL_ACCESS:
2648 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2663 } // end _get_protection
2665 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD mask ) {
2667 OSD_SingleProtection retVal;
2683 case GENERIC_READ | GENERIC_WRITE:
2689 case GENERIC_EXECUTE:
2695 case GENERIC_READ | GENERIC_EXECUTE:
2701 case GENERIC_WRITE | GENERIC_EXECUTE:
2707 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE:
2719 case GENERIC_READ | DELETE:
2725 case GENERIC_WRITE | DELETE:
2731 case GENERIC_READ | GENERIC_WRITE | DELETE:
2737 case GENERIC_EXECUTE | DELETE:
2743 case GENERIC_READ | GENERIC_EXECUTE | DELETE:
2749 case GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2755 case FILE_ALL_ACCESS:
2756 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2771 } // end _get_protection_dir
2774 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2777 #define __leave return fOK
2781 BOOL __fastcall _osd_print (const Standard_PCharacter pName, const wchar_t* fName ) {
2784 HANDLE hPrinter = NULL;
2785 BYTE jobInfo[ MAX_PATH + sizeof ( DWORD ) ];
2786 DWORD dwNeeded, dwCode = 0;
2792 if ( !OpenPrinter ( Standard_PCharacter(pName), &hPrinter, NULL ) ) {
2800 hPrinter, 1, jobInfo, MAX_PATH + sizeof ( DWORD ), &dwNeeded
2807 fName, (LPWSTR) ( ( ADDJOB_INFO_1* )jobInfo ) -> Path, FALSE
2812 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId
2825 DWORD dwBytesNeeded;
2827 dwCode = GetLastError ();
2829 if ( fJob && hPrinter != NULL ) {
2832 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId, 1,
2833 info, 1024, &dwBytesNeeded
2836 if ( fJob ) SetJob (
2838 ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId,
2839 1, info, JOB_CONTROL_CANCEL
2846 if ( hPrinter != NULL ) ClosePrinter ( hPrinter );
2851 leave: ; // added for VisualAge
2854 if ( !fOK ) SetLastError ( dwCode );
2861 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2867 Standard_Boolean OSD_File::IsReadable()
2869 TCollection_AsciiString FileName ;
2872 myPath.SystemName(FileName) ;
2873 Channel = _open_file(FileName.ToCString(), OSD_ReadOnly, OPEN_OLD) ;
2874 if (Channel == INVALID_HANDLE_VALUE)
2875 return Standard_False ;
2877 CloseHandle (Channel) ;
2878 return Standard_True ;
2883 Standard_Boolean OSD_File::IsWriteable()
2885 TCollection_AsciiString FileName ;
2888 myPath.SystemName(FileName) ;
2889 Channel = _open_file(FileName.ToCString(), OSD_ReadWrite, OPEN_OLD) ;
2890 if (Channel == INVALID_HANDLE_VALUE)
2891 return Standard_False ;
2893 CloseHandle (Channel) ;
2894 return Standard_True ;
2898 Standard_Boolean OSD_File::IsExecutable()
2900 return IsReadable() ;
2902 // if (_access(FileName.ToCString(),0))
2907 // ---------------------------------------------------------------------
2908 // Destructs a file object (unlocks and closes file if it is open)
2909 // ---------------------------------------------------------------------
2911 OSD_File::~OSD_File()
2921 // ---------------------------------------------------------------------
2922 // Read lines in a file while it is increasing.
2923 // Each line is terminated with a <nl>.
2924 // ---------------------------------------------------------------------
2928 Standard_Boolean OSD_File::ReadLastLine(TCollection_AsciiString& aLine,const Standard_Integer aDelay,const Standard_Integer aNbTries)
2930 static Standard_Integer MaxLength = 1000 ;
2931 Standard_Integer Len ;
2932 Standard_Integer Count = aNbTries ;
2935 return Standard_False ;
2937 ReadLine(aLine, MaxLength, Len) ;
2938 if (!aLine.IsEmpty())
2939 return Standard_True ;
2941 return Standard_False ;
2942 OSD::SecSleep(aDelay) ;
2947 Standard_Boolean OSD_File::Edit()
2949 cout << "Function OSD_File::Edit() not yet implemented." << endl;
2950 return Standard_False ;