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 OSD_File OSD_File::BuildTemporary(){
246 #if defined(vax) || defined(__vms) || defined(VAXVMS)
252 dummy = open("dummy", O_RDWR | O_CREAT); // Open a dummy file
253 result.myFileChannel = dummy - 1; // This is file channel of "fic" +1
254 close(dummy); // Close dummy file
255 unlink("dummy"); // Removes dummy file
259 char *name = tmpnam((char*) 0) ;
262 TCollection_AsciiString aName ( name ) ;
263 OSD_Path aPath( aName ) ;
265 result.SetPath( aPath ) ;
267 result.myFILE = fopen( name, "w+" ) ;
269 result.myFileChannel = fileno( (FILE*)result.myFILE );
273 result.myMode = OSD_ReadWrite;
280 // ---------------------------------------------------------------------
281 // Read content of a file
282 // ---------------------------------------------------------------------
284 void OSD_File::Read(TCollection_AsciiString& Buffer,
285 const Standard_Integer Nbyte){
286 Standard_PCharacter readbuf;
289 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
290 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
293 if (myFileChannel == -1)
294 Standard_ProgramError::Raise("OSD_File::Read : file is not open");
296 if (Failed()) Perror();
298 if (myMode == OSD_WriteOnly)
299 Standard_ProgramError::Raise("OSD_File::Read : file is Write only");
302 Standard_ProgramError::Raise("OSD_File::Read : Nbyte is null");
304 TCollection_AsciiString transfert(Nbyte,' ');
305 readbuf = (Standard_PCharacter)transfert.ToCString();
307 status = read (myFileChannel, readbuf, Nbyte);
309 Buffer = transfert; // Copy transfert to Buffer
311 if (status == -1) myError.SetValue (errno, Iam, "Read");
313 if ( status < Nbyte ) myIO = EOF;
317 // ---------------------------------------------------------------------
318 // Read a line from a file
319 // ---------------------------------------------------------------------
321 void OSD_File::ReadLine(TCollection_AsciiString& Buffer,
322 const Standard_Integer Nbyte,
323 Standard_Integer& NByteRead)
325 Standard_PCharacter readbuf, abuffer;
327 if (OSD_File::KindOfFile() == OSD_DIRECTORY ) {
328 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
330 if (myFileChannel == -1){
331 Standard_ProgramError::Raise("OSD_File::ReadLine : file is not open");
336 if (myMode == OSD_WriteOnly) {
337 Standard_ProgramError::Raise("OSD_File::ReadLine : file is Write only");
340 Standard_ProgramError::Raise("OSD_File::ReadLine : Nbyte is null");
343 TCollection_AsciiString transfert(Nbyte,' ');
344 readbuf = (Standard_PCharacter)transfert.ToCString();
346 abuffer = fgets(readbuf, Nbyte, (FILE *) myFILE);
348 if (abuffer == NULL) {
349 if (!feof((FILE *) myFILE)) {
350 myError.SetValue (errno, Iam, "ReadLine");
360 NByteRead = (Standard_Integer)strlen(abuffer);
361 Buffer.SetValue(1,abuffer); // Copy transfert to Buffer
362 Buffer.Trunc(NByteRead);
365 // --------------------------------------------------------------------------
366 // OSD::KindOfFile Retourne le type de fichier.
367 // --------------------------------------------------------------------------
368 OSD_KindFile OSD_File::KindOfFile ( ) const{
371 TCollection_AsciiString FullName;
375 aPath.SystemName (FullName);
376 status = stat (FullName.ToCString() , &buffer );
378 if ( S_ISDIR(buffer.st_mode) ) { return OSD_DIRECTORY ; }
379 else if ( S_ISREG(buffer.st_mode) ) { return OSD_FILE ; }
380 else if ( S_ISLNK(buffer.st_mode) ) { return OSD_LINK ; }
381 else if ( S_ISSOCK(buffer.st_mode) ) { return OSD_SOCKET ; }
382 else { return OSD_UNKNOWN ; }
387 // --------------------------------------------------------------------------
388 // Read content of a file
389 // --------------------------------------------------------------------------
390 void OSD_File::Read( Standard_Address& Buffer,
391 const Standard_Integer Nbyte,
392 Standard_Integer& Readbyte)
397 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
398 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
401 if (myFileChannel == -1)
402 Standard_ProgramError::Raise("OSD_File::Read : file is not open");
404 if (Failed()) Perror();
406 if (myMode == OSD_WriteOnly)
407 Standard_ProgramError::Raise("OSD_File::Read : file is Write only");
410 Standard_ProgramError::Raise("OSD_File::Read : Nbyte is null");
413 Standard_ProgramError::Raise("OSD_File::Read : Buffer is null");
415 status = read (myFileChannel, (char*) Buffer, Nbyte);
417 if (status == -1) myError.SetValue (errno, Iam, "Read");
419 if ( status < Nbyte ) myIO = EOF;
424 // Write content of a file
426 void OSD_File::Write(const TCollection_AsciiString &Buffer,
427 const Standard_Integer Nbyte){
429 Standard_CString writebuf;
432 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
433 Standard_ProgramError::Raise("OSD_File::Write : it is a directory");
436 if (myFileChannel == -1)
437 Standard_ProgramError::Raise("OSD_File::Write : file is not open");
439 if (Failed()) Perror();
441 if (myMode == OSD_ReadOnly)
442 Standard_ProgramError::Raise("OSD_File::Write : file is Read only");
445 Standard_ProgramError::Raise("OSD_File::Write : Nbyte is null");
447 writebuf = Buffer.ToCString();
449 status = write (myFileChannel, writebuf, Nbyte);
451 if ( status == -1) myError.SetValue (errno, Iam, "Write");
453 if ( status < Nbyte ) myIO = EOF;
457 void OSD_File::Write(const Standard_Address Buffer,
458 const Standard_Integer Nbyte)
463 if (myFileChannel == -1)
464 Standard_ProgramError::Raise("OSD_File::Write : file is not open");
466 if (Failed()) Perror();
468 if (myMode == OSD_ReadOnly)
469 Standard_ProgramError::Raise("OSD_File::Write : file is Read only");
472 Standard_ProgramError::Raise("OSD_File::Write : Nbyte is null");
474 status = write (myFileChannel, (const char *)Buffer, Nbyte);
476 if ( status == -1) myError.SetValue (errno, Iam, "Write");
478 if ( status < Nbyte ) myIO = EOF;
485 // Move file pointer to a specified position
487 void OSD_File::Seek(const Standard_Integer Offset,
488 const OSD_FromWhere Whence){
491 if (myFileChannel == -1)
492 Standard_ProgramError::Raise("OSD_File::Seek : file is not open");
494 if (Failed()) Perror();
497 case OSD_FromBeginning :
507 myError.SetValue (EINVAL, Iam, "Seek");
510 off_t status = lseek (myFileChannel, Offset, iwhere);
511 if (status == -1) myError.SetValue (errno, Iam, "Seek");
521 void OSD_File::Close(){
524 if (myFileChannel == -1)
525 Standard_ProgramError::Raise("OSD_File::Close : file is not open");
527 if (Failed()) Perror();
529 // note: it probably should be single call to fclose()...
530 status = close (myFileChannel);
532 if (status == -1) myError.SetValue (errno, Iam, "Close");
534 if ( myFILE != NULL ) {
535 status = fclose ( (FILE*) myFILE );
544 // --------------------------------------------------------------------------
545 // Test if at end of file
546 // --------------------------------------------------------------------------
548 Standard_Boolean OSD_File::IsAtEnd(){
549 if (myFileChannel == -1)
550 Standard_ProgramError::Raise("OSD_File::IsAtEnd : file is not open");
552 if (myIO == EOF) return (Standard_True);
553 return (Standard_False);
558 /*void OSD_File::Link(const TCollection_AsciiString& ToFile){
559 if (myFileChannel == -1)
560 Standard_ProgramError::Raise("OSD_File::Link : file is not open");
562 TCollection_AsciiString aBuffer;
563 myPath.SystemName ( aBuffer );
564 link ( aBuffer.ToCString(), ToFile.ToCString() );
570 void OSD_File::SetLock(const OSD_LockType Lock){
573 if (myFileChannel == -1)
574 Standard_ProgramError::Raise("OSD_File::SetLock : file is not open");
582 case OSD_ExclusiveLock :
583 case OSD_WriteLock : lock = F_LOCK;
585 case OSD_ReadLock : return;
587 default : myError.SetValue (EINVAL, Iam, "SetLock");
591 if (fstat (myFileChannel, &buf) == -1) {
592 myError.SetValue (errno, Iam, "SetLock");
596 status = lockf(myFileChannel, lock, buf.st_size);
597 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
606 case OSD_ExclusiveLock :
607 case OSD_WriteLock : key.l_type = F_WRLCK;
609 case OSD_ReadLock : key.l_type = F_RDLCK;
611 case OSD_NoLock : return;
612 // default : myError.SetValue (EINVAL, Iam, "SetLock");
619 status = fcntl (myFileChannel, F_SETLKW, &key);
620 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
623 if (Lock == OSD_ExclusiveLock){
624 fstat (myFileChannel, &buf);
625 TCollection_AsciiString aBuffer;
626 myPath.SystemName ( aBuffer );
627 chmod( aBuffer.ToCString() ,buf.st_mode | S_ISGID);
628 ImperativeFlag = Standard_True;
635 case OSD_ExclusiveLock :
636 case OSD_WriteLock : lock = F_WRLCK;
638 case OSD_ReadLock : lock = F_RDLCK;
640 default : myError.SetValue (EINVAL, Iam, "SetLock");
643 status = flock (myFileChannel, lock);
644 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
653 // Remove a lock from a file
655 void OSD_File::UnLock(){
658 if (myFileChannel == -1)
659 Standard_ProgramError::Raise("OSD_File::UnLock : file is not open");
664 if (fstat(myFileChannel, &buf) == -1) {
665 myError.SetValue(errno, Iam, "UnsetLock");
669 status = lockf(myFileChannel,F_ULOCK, buf.st_size);
670 if (status == -1) myError.SetValue (errno, Iam, "SetLock");
678 fstat (myFileChannel, &buf);
679 TCollection_AsciiString aBuffer;
680 myPath.SystemName ( aBuffer );
681 chmod(aBuffer.ToCString(),buf.st_mode & ~S_ISGID);
682 ImperativeFlag = Standard_False;
684 key.l_type = F_UNLCK;
685 status = fcntl (myFileChannel, F_SETLK, &key);
686 if (status == -1) myError.SetValue (errno, Iam, "UnSetLock");
689 status = flock (myFileChannel, LOCK_UN);
690 if (status == -1) myError.SetValue (errno, Iam, "UnSetLock");
693 else myLock = OSD_NoLock;
700 // Return lock of a file
702 OSD_LockType OSD_File::GetLock(){
709 // --------------------------------------------------------------------------
710 // Return size of a file
711 // --------------------------------------------------------------------------
713 Standard_Size OSD_File::Size(){
717 if (myPath.Name().Length()==0)
718 Standard_ProgramError::Raise("OSD_File::Size : empty file name");
720 TCollection_AsciiString aBuffer;
721 myPath.SystemName ( aBuffer );
722 status = stat( aBuffer.ToCString() ,&buffer );
724 myError.SetValue (errno, Iam, "Size");
728 return (Standard_Size)buffer.st_size;
732 // --------------------------------------------------------------------------
733 // Print contains of a file
734 // --------------------------------------------------------------------------
736 void OSD_File::Print (const OSD_Printer &WhichPrinter ){
738 TCollection_AsciiString PrinterName;
740 if (myPath.Name().Length()==0)
741 Standard_ProgramError::Raise("OSD_File::Print : empty file name");
743 WhichPrinter.Name(PrinterName);
745 TCollection_AsciiString aBuffer;
746 myPath.SystemName ( aBuffer );
748 if (PrinterName.Length()==0)
749 sprintf(buffer,"lp %s",aBuffer.ToCString());
751 sprintf(buffer,"lpr -P%s %s",PrinterName.ToCString(),aBuffer.ToCString());
753 if (system(buffer) != 0)
754 Standard_ProgramError::Raise("OSD_File::Print : No output device was available, or an error occurred");
758 // --------------------------------------------------------------------------
759 // Test if a file is open
760 // --------------------------------------------------------------------------
762 Standard_Boolean OSD_File::IsOpen()const{
763 return (myFileChannel != -1);
767 Standard_Boolean OSD_File::IsLocked(){
768 return(myLock != OSD_NoLock);
771 Standard_Boolean OSD_File::IsReadable()
773 TCollection_AsciiString FileName ;
775 myPath.SystemName(FileName) ;
777 if (access(FileName.ToCString(),F_OK|R_OK))
778 return Standard_False;
780 return Standard_True;
783 Standard_Boolean OSD_File::IsWriteable()
785 TCollection_AsciiString FileName ;
787 myPath.SystemName(FileName) ;
789 if (access(FileName.ToCString(),F_OK|R_OK|W_OK))
790 return Standard_False;
792 return Standard_True;
795 Standard_Boolean OSD_File::IsExecutable()
797 TCollection_AsciiString FileName ;
799 myPath.SystemName(FileName) ;
801 if (access(FileName.ToCString(),F_OK|X_OK))
802 return Standard_False;
804 return Standard_True;
809 //------------------------------------------------------------------------
810 //------------------- Windows NT sources for OSD_File -------------------
811 //------------------------------------------------------------------------
815 #include <OSD_File.hxx>
816 #include <OSD_Protection.hxx>
817 #include <OSD_Printer.hxx>
818 #include <Standard_ProgramError.hxx>
820 #include <OSD_WNT_1.hxx>
824 #include <Standard_PCharacter.hxx>
825 #include <TCollection_ExtendedString.hxx>
831 #if defined(__CYGWIN32__) || defined(__MINGW32__)
836 #pragma comment( lib, "WSOCK32.LIB" )
837 #pragma comment( lib, "WINSPOOL.LIB" )
839 #define ACE_HEADER_SIZE ( sizeof ( ACCESS_ALLOWED_ACE ) - sizeof ( DWORD ) )
841 #define RAISE( arg ) Standard_ProgramError :: Raise ( ( arg ) )
842 #define TEST_RAISE( arg ) _test_raise ( myFileHandle, ( arg ) )
846 #define OPEN_APPEND 2
848 void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
849 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd ( const OSD_Protection&, BOOL, wchar_t* = NULL );
850 BOOL __fastcall _osd_wnt_sd_to_protection (
851 PSECURITY_DESCRIPTOR, OSD_Protection&, BOOL
853 BOOL __fastcall _osd_print (const Standard_PCharacter, const wchar_t* );
855 static void __fastcall _test_raise ( HANDLE, Standard_CString );
856 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos);
857 static int __fastcall _get_buffer ( HANDLE, Standard_PCharacter&, DWORD, BOOL, BOOL );
858 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection );
859 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt );
860 static HANDLE __fastcall _open_file ( Standard_CString, OSD_OpenMode, DWORD, LPBOOL = NULL );
862 static OSD_SingleProtection __fastcall _get_protection ( DWORD );
863 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD );
865 typedef OSD_SingleProtection ( __fastcall *GET_PROT_FUNC ) ( DWORD );
867 Standard_Integer __fastcall _get_file_type ( Standard_CString, HANDLE );
869 // ---------------------------------------------------------------------
870 // Create an empty file object
871 // ---------------------------------------------------------------------
873 OSD_File :: OSD_File ()
875 ImperativeFlag = Standard_False;
879 myFileHandle = INVALID_HANDLE_VALUE;
880 } // end constructor ( 1 )
882 // ---------------------------------------------------------------------
883 // Create and initialize a file object
884 // ---------------------------------------------------------------------
886 OSD_File :: OSD_File ( const OSD_Path& Name ) : OSD_FileNode ( Name )
888 ImperativeFlag = Standard_False;
893 myFileHandle = INVALID_HANDLE_VALUE;
894 } // end constructor ( 2 )
896 // protect against occasional use of myFileHande in Windows code
897 #define myFileChannel myFileChannel_is_only_for_Linux
899 // ---------------------------------------------------------------------
900 // Build a file if it doesn't exist or create again if it already exists
901 // ---------------------------------------------------------------------
903 void OSD_File :: Build (
904 const OSD_OpenMode Mode, const OSD_Protection& Protect
907 TCollection_AsciiString fName;
909 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
910 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
913 if (myFileHandle != INVALID_HANDLE_VALUE)
915 RAISE( "OSD_File :: Build (): incorrect call - file already opened" );
918 myPath.SystemName ( fName );
920 if ( fName.IsEmpty () )
922 RAISE( "OSD_File :: Build (): incorrent call - no filename given" );
924 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_NEW );
926 if (myFileHandle == INVALID_HANDLE_VALUE)
928 _osd_wnt_set_error ( myError, OSD_WFile );
932 SetProtection ( Protect );
937 } // end OSD_File :: Build
941 // ---------------------------------------------------------------------
943 // ---------------------------------------------------------------------
945 void OSD_File :: Open (const OSD_OpenMode Mode, const OSD_Protection& /*Protect*/)
948 TCollection_AsciiString fName;
951 if (myFileHandle != INVALID_HANDLE_VALUE)
953 RAISE( "OSD_File :: Open (): incorrect call - file already opened" );
956 myPath.SystemName ( fName );
958 if ( fName.IsEmpty () )
960 RAISE( "OSD_File :: Open (): incorrent call - no filename given" );
962 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_OLD );
964 if (myFileHandle == INVALID_HANDLE_VALUE) {
966 _osd_wnt_set_error ( myError, OSD_WFile );
970 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
972 } // end OSD_File :: Open
974 // ---------------------------------------------------------------------
975 // Append to an existing file
976 // ---------------------------------------------------------------------
978 void OSD_File :: Append (
979 const OSD_OpenMode Mode, const OSD_Protection& Protect
983 TCollection_AsciiString fName;
985 if (myFileHandle != INVALID_HANDLE_VALUE)
987 RAISE( "OSD_File :: Append (): incorrect call - file already opened" );
990 myPath.SystemName ( fName );
992 if ( fName.IsEmpty () )
994 RAISE( "OSD_File :: Append (): incorrent call - no filename given" );
996 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_APPEND, &fNew );
998 if (myFileHandle == INVALID_HANDLE_VALUE)
1000 _osd_wnt_set_error ( myError, OSD_WFile );
1006 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
1007 Seek ( 0, OSD_FromEnd );
1011 SetProtection ( Protect );
1018 } // end OSD_File :: Append
1020 // ---------------------------------------------------------------------
1021 // Read content of a file
1022 // ---------------------------------------------------------------------
1024 void OSD_File :: Read (
1025 TCollection_AsciiString& Buffer, const Standard_Integer Nbyte
1028 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1030 cout << " OSD_File::Read : it is a directory " << endl;
1033 // Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1036 Standard_Integer NbyteRead;
1037 Standard_Address buff;
1039 TEST_RAISE( "Read" );
1041 buff = ( Standard_Address )new Standard_Character[ Nbyte + 1 ];
1043 Read ( buff, Nbyte, NbyteRead );
1045 ( ( Standard_PCharacter )buff )[ NbyteRead ] = 0;
1047 if ( NbyteRead != 0 )
1049 Buffer = ( Standard_PCharacter )buff;
1057 } // end OSD_File :: Read
1059 // ---------------------------------------------------------------------
1060 // Read a line from a file
1061 // ---------------------------------------------------------------------
1063 // Modified so that we have <nl> at end of line if we have read <nl> or <cr>
1065 // by LD 17 dec 98 for B4.4
1067 void OSD_File :: ReadLine (
1068 TCollection_AsciiString& Buffer,
1069 const Standard_Integer NByte, Standard_Integer& NbyteRead
1074 Standard_Character peekChar;
1075 Standard_PCharacter ppeekChar;
1076 Standard_PCharacter cBuffer;
1079 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1080 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1083 TEST_RAISE( "ReadLine" );
1085 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1087 RAISE( "OSD_File :: ReadLine (): attempt to read from write only pipe" );
1089 // +----> leave space for end-of-string
1090 // | plus <CR><LF> sequence
1093 ppeekChar=&peekChar;
1094 cBuffer = new Standard_Character[ NByte + 3 ];
1096 if ( myIO & FLAG_FILE ) {
1098 if (!ReadFile (myFileHandle, cBuffer, NByte, &dwBytesRead, NULL)) { // an error occured
1100 _osd_wnt_set_error ( myError, OSD_WFile );
1104 } else if ( dwBytesRead == 0 ) { // end-of-file reached
1111 myIO &= ~FLAG_EOF ; // if the file increased since last read (LD)
1112 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1114 if ( NbyteRead == -1 ) // last character in the buffer is <CR> -
1115 { // peek next character to see if it is a <LF>
1116 if (!ReadFile (myFileHandle, ppeekChar, 1, &dwDummy, NULL)) {
1118 _osd_wnt_set_error ( myError, OSD_WFile );
1120 } else if ( dwDummy != 0 ) { // end-of-file reached ?
1122 if ( peekChar != '\n' ) // if we did not get a <CR><LF> sequence
1124 // adjust file position
1126 SetFilePointer (myFileHandle, -1, NULL, FILE_CURRENT);
1131 NbyteRead = dwBytesRead;
1133 } else if ( aSeekPos != 0 )
1135 SetFilePointer (myFileHandle, aSeekPos, NULL, FILE_CURRENT);
1140 } else if ( myIO & FLAG_SOCKET || myIO & FLAG_PIPE || myIO & FLAG_NAMED_PIPE ) {
1142 dwBytesRead = (DWORD)_get_buffer (myFileHandle, cBuffer,
1143 (DWORD)NByte, TRUE, myIO & FLAG_SOCKET);
1145 if ( ( int )dwBytesRead == -1 ) { // an error occured
1147 _osd_wnt_set_error ( myError, OSD_WFile );
1151 } else if ( dwBytesRead == 0 ) { // connection closed - set end-of-file flag
1159 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1161 if (NbyteRead == -1) // last character in the buffer is <CR> -
1162 { // peek next character to see if it is a <LF>
1163 NbyteRead = dwBytesRead; // (LD) always fits this case.
1165 dwDummy = _get_buffer (myFileHandle, ppeekChar, 1, TRUE, myIO & FLAG_SOCKET);
1166 if ( ( int )dwDummy == -1 ) { // an error occured
1168 _osd_wnt_set_error ( myError, OSD_WFile );
1170 } else if ( dwDummy != 0 ) { // connection closed ?
1172 if ( peekChar == '\n' ) // we got a <CR><LF> sequence
1174 dwBytesRead++ ; // (LD) we have to jump <LF>
1179 } else if (aSeekPos != 0)
1181 dwBytesRead = dwBytesRead + aSeekPos;
1184 // Don't rewrite datas in cBuffer.
1186 Standard_PCharacter cDummyBuffer = new Standard_Character[ NByte + 3 ];
1188 // remove pending input
1189 _get_buffer (myFileHandle, cDummyBuffer, dwBytesRead, FALSE, myIO & FLAG_SOCKET);
1190 delete [] cDummyBuffer ;
1196 RAISE( "OSD_File :: ReadLine (): incorrect call - file is a directory" );
1198 if ( !Failed () && !IsAtEnd () )
1202 delete [] (Standard_PCharacter)cBuffer;
1204 } // end OSD_File :: ReadLine
1206 // --------------------------------------------------------------------------
1207 // Read content of a file
1208 // --------------------------------------------------------------------------
1210 void OSD_File :: Read (
1211 Standard_Address& Buffer,
1212 const Standard_Integer Nbyte, Standard_Integer& Readbyte
1217 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1218 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1221 TEST_RAISE( "Read" );
1223 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1225 RAISE( "OSD_File :: Read (): attempt to read from write only pipe" );
1227 if (!ReadFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesRead, NULL)) {
1229 _osd_wnt_set_error ( myError, OSD_WFile );
1232 } else if ( dwBytesRead == 0 )
1240 Readbyte = ( Standard_Integer )dwBytesRead;
1242 } // end OSD_File :: Read
1244 void OSD_File :: Write (
1245 const TCollection_AsciiString& Buffer,
1246 const Standard_Integer Nbyte
1249 Write ( ( Standard_Address )Buffer.ToCString (), Nbyte );
1251 } // end OSD_File :: Write
1253 // --------------------------------------------------------------------------
1254 // Write content of a file
1255 // --------------------------------------------------------------------------
1257 void OSD_File :: Write (
1258 const Standard_Address Buffer,
1259 const Standard_Integer Nbyte
1262 DWORD dwBytesWritten;
1264 TEST_RAISE( "Write" );
1266 if ( myIO & FLAG_PIPE && myIO & FLAG_READ_PIPE )
1268 RAISE( "OSD_File :: Write (): attempt to write to read only pipe" );
1270 if (!WriteFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesWritten, NULL) ||
1271 dwBytesWritten != (DWORD)Nbyte)
1273 _osd_wnt_set_error ( myError, OSD_WFile );
1275 } // end OSD_File :: Write
1277 void OSD_File :: Seek (
1278 const Standard_Integer Offset, const OSD_FromWhere Whence
1281 DWORD dwMoveMethod = 0;
1283 TEST_RAISE( "Seek" );
1285 if ( myIO & FLAG_FILE || myIO & FLAG_DIRECTORY ) {
1289 case OSD_FromBeginning:
1291 dwMoveMethod = FILE_BEGIN;
1297 dwMoveMethod = FILE_CURRENT;
1303 dwMoveMethod = FILE_END;
1309 RAISE( "OSD_File :: Seek (): invalid parameter" );
1313 if (SetFilePointer (myFileHandle, (LONG)Offset, NULL, dwMoveMethod) == 0xFFFFFFFF)
1315 _osd_wnt_set_error ( myError, OSD_WFile );
1321 } // end OSD_File :: Seek
1323 // --------------------------------------------------------------------------
1325 // --------------------------------------------------------------------------
1327 void OSD_File :: Close () {
1329 TEST_RAISE( "Close" );
1331 CloseHandle (myFileHandle);
1333 myFileHandle = INVALID_HANDLE_VALUE;
1336 } // end OSD_File :: Close
1338 // --------------------------------------------------------------------------
1339 // Test if at end of file
1340 // --------------------------------------------------------------------------
1342 Standard_Boolean OSD_File :: IsAtEnd () {
1344 TEST_RAISE( "IsAtEnd" );
1346 if (myIO & FLAG_EOF)
1347 return Standard_True ;
1348 return Standard_False ;
1350 } // end OSD_File :: IsAtEnd
1352 OSD_KindFile OSD_File :: KindOfFile () const {
1354 OSD_KindFile retVal;
1355 Standard_Integer flags;
1357 if (myFileHandle == INVALID_HANDLE_VALUE) {
1359 TCollection_AsciiString fName;
1361 myPath.SystemName ( fName );
1363 if ( fName.IsEmpty () )
1365 RAISE( "OSD_File :: KindOfFile (): incorrent call - no filename given" );
1367 flags = _get_file_type (fName.ToCString(), INVALID_HANDLE_VALUE);
1373 switch ( flags & FLAG_TYPE ) {
1381 case FLAG_DIRECTORY:
1383 retVal = OSD_DIRECTORY;
1389 retVal = OSD_SOCKET;
1395 retVal = OSD_UNKNOWN;
1401 } // end OSD_File :: KindOfFile
1404 char tmpbuf [MAX_PATH];
1405 if (GetTempPath (MAX_PATH, tmpbuf) == 0)
1407 perror ("ERROR in GetTempPath");
1410 char tmpbuf2 [MAX_PATH];
1411 if (GetTempFileName (tmpbuf, NULL, 0, tmpbuf2) == 0)
1413 perror ("ERROR in GetTempFileName");
1416 TCollection_AsciiString fileName ( tmpbuf2 );
1418 TCollection_AsciiString fileName ( _ttmpnam ( NULL ) );
1422 //-------------------------------------------------debutpri???980424
1424 typedef struct _osd_wnt_key {
1432 OSD_File OSD_File :: BuildTemporary () {
1437 TCHAR tmpPath[ MAX_PATH ];
1439 OSD_WNT_KEY regKey[ 2 ] = {
1441 { HKEY_LOCAL_MACHINE,
1442 "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"
1445 ".DEFAULT\\Environment"
1450 for ( int i = 0; i < 2; ++i ) {
1453 regKey[ i ].hKey, regKey[ i ].keyPath, 0, KEY_QUERY_VALUE, &hKey
1460 if ( RegQueryValueEx (
1461 hKey, "TEMP", NULL, &dwType, NULL, &dwSize
1465 LPTSTR kVal = ( LPTSTR )HeapAlloc (
1466 GetProcessHeap (), HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
1467 dwSize + sizeof ( TCHAR )
1470 RegQueryValueEx ( hKey, "TEMP", NULL, &dwType, ( LPBYTE )kVal, &dwSize );
1472 if ( dwType == REG_EXPAND_SZ )
1474 ExpandEnvironmentStrings ( kVal, tmpPath, MAX_PATH );
1478 lstrcpy ( tmpPath, kVal );
1480 HeapFree ( GetProcessHeap (), 0, ( LPVOID )kVal );
1485 RegCloseKey ( hKey );
1493 if ( !fOK ) lstrcpy ( tmpPath, "./" );
1495 GetTempFileName ( tmpPath, "CSF", 0, tmpPath );
1497 retVal.SetPath ( OSD_Path ( tmpPath ) );
1498 retVal.Build ( OSD_ReadWrite, prt );
1502 } // end OSD_File :: BuildTemporary
1504 //-------------------------------------------------finpri???980424
1506 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1509 #define __leave return
1512 void OSD_File :: SetLock ( const OSD_LockType Lock ) {
1517 TEST_RAISE( "SetLock" );
1519 ZeroMemory ( &ovlp, sizeof ( OVERLAPPED ) );
1523 if ( ( myLock = Lock ) == OSD_NoLock ) {
1528 } else if ( myLock == OSD_ReadLock || myLock == OSD_ExclusiveLock ) {
1530 dwFlags = LOCKFILE_EXCLUSIVE_LOCK;
1536 LARGE_INTEGER aSize;
1537 aSize.QuadPart = Size();
1538 if (!LockFileEx (myFileHandle, dwFlags, 0, aSize.LowPart, aSize.HighPart, &ovlp)) {
1540 _osd_wnt_set_error ( myError, OSD_WFile );
1545 ImperativeFlag = Standard_True;
1552 leave: ; // added for VisualAge
1554 } // end OSD_File :: SetLock
1556 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1562 void OSD_File :: UnLock () {
1564 TEST_RAISE( "Unlock" );
1566 if ( ImperativeFlag ) {
1568 LARGE_INTEGER aSize;
1569 aSize.QuadPart = Size();
1570 if (!UnlockFile (myFileHandle, 0, 0, aSize.LowPart, aSize.HighPart))
1572 _osd_wnt_set_error ( myError, OSD_WFile );
1574 ImperativeFlag = Standard_False;
1578 } // end OSD_File :: UnLock
1580 OSD_LockType OSD_File :: GetLock () {
1584 } // end OSD_File :: GetLock
1586 Standard_Boolean OSD_File :: IsLocked () {
1588 TEST_RAISE( "IsLocked" );
1590 return ImperativeFlag;
1592 } // end OSD_File :: IsLocked
1595 // --------------------------------------------------------------------------
1596 // Return size of a file
1597 // --------------------------------------------------------------------------
1599 Standard_Size OSD_File :: Size () {
1601 Standard_Integer retVal;
1603 TEST_RAISE( "Size" );
1605 LARGE_INTEGER aSize;
1607 retVal = GetFileSizeEx (myFileHandle, &aSize);
1611 _osd_wnt_set_error ( myError, OSD_WFile );
1613 return (Standard_Size)aSize.QuadPart;
1615 } // end OSD_File :: Size
1617 // --------------------------------------------------------------------------
1618 // Print contains of a file
1619 // --------------------------------------------------------------------------
1621 void OSD_File :: Print ( const OSD_Printer& WhichPrinter ) {
1623 if (myFileHandle != INVALID_HANDLE_VALUE)
1625 RAISE( "OSD_File :: Print (): incorrect call - file opened" );
1627 TCollection_AsciiString pName, fName;
1629 WhichPrinter.Name ( pName );
1630 myPath.SystemName ( fName );
1631 TCollection_ExtendedString fNameW(fName);
1633 if ( !_osd_print ( (Standard_PCharacter)pName.ToCString (),
1634 (const wchar_t*)fNameW.ToExtString () ) )
1636 _osd_wnt_set_error ( myError, OSD_WFile );
1638 } // end OSD_File :: Print
1640 // --------------------------------------------------------------------------
1641 // Test if a file is open
1642 // --------------------------------------------------------------------------
1644 Standard_Boolean OSD_File :: IsOpen () const {
1646 return myFileHandle != INVALID_HANDLE_VALUE;
1648 } // end OSD_File :: IsOpen
1650 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1653 #define __leave return retVal
1656 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd (
1657 const OSD_Protection& prot, BOOL fDir, wchar_t* fName
1663 HANDLE hProcess = NULL;
1668 DWORD dwAccessAdmin;
1669 DWORD dwAccessGroup;
1670 DWORD dwAccessOwner;
1671 DWORD dwAccessWorld;
1672 DWORD dwAccessAdminDir;
1673 DWORD dwAccessGroupDir;
1674 DWORD dwAccessOwnerDir;
1675 DWORD dwAccessWorldDir;
1676 DWORD dwACLsize = sizeof ( ACL );
1678 PTOKEN_OWNER pTkOwner = NULL;
1679 PTOKEN_GROUPS pTkGroups = NULL;
1680 PTOKEN_PRIMARY_GROUP pTkPrimaryGroup = NULL;
1681 PSECURITY_DESCRIPTOR retVal = NULL;
1682 PSECURITY_DESCRIPTOR pfSD = NULL;
1690 if ( !OpenProcessToken (
1691 GetCurrentProcess (), TOKEN_QUERY, &hProcess
1695 if ( ( pTkGroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
1696 hProcess, TokenGroups
1701 if ( ( pTkOwner = ( PTOKEN_OWNER )GetTokenInformationEx (
1702 hProcess, TokenOwner
1707 if ( ( pTkPrimaryGroup = ( PTOKEN_PRIMARY_GROUP )GetTokenInformationEx (
1708 hProcess, TokenPrimaryGroup
1715 if ( fName == NULL )
1717 pSIDowner = pTkOwner -> Owner;
1721 pfSD = GetFileSecurityEx ( fName, OWNER_SECURITY_INFORMATION );
1723 if ( pfSD == NULL || !GetSecurityDescriptorOwner ( pfSD, &pSIDowner, &fDummy ) ) {
1732 pSIDadmin = AdminSid ();
1733 pSIDworld = WorldSid ();
1735 dwAccessAdmin = _get_access_mask ( prot.System () );
1736 dwAccessGroup = _get_access_mask ( prot.Group () );
1737 dwAccessOwner = _get_access_mask ( prot.User () );
1738 dwAccessWorld = _get_access_mask ( prot.World () );
1740 dwAccessAdminDir = _get_dir_access_mask ( prot.System () );
1741 dwAccessGroupDir = _get_dir_access_mask ( prot.Group () );
1742 dwAccessOwnerDir = _get_dir_access_mask ( prot.User () );
1743 dwAccessWorldDir = _get_dir_access_mask ( prot.World () );
1745 if ( dwAccessGroup != 0 ) {
1747 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1749 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1751 if ( !NtPredefinedSid ( pSIDtemp ) &&
1752 !EqualSid ( pSIDtemp, pSIDworld ) &&
1753 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1754 IsValidSid ( pSIDtemp )
1757 dwACLsize += ( ( GetLengthSid ( pSIDtemp ) + ACE_HEADER_SIZE ) << j );
1763 dwACLsize += ( ( ( GetLengthSid ( pSIDowner ) + ACE_HEADER_SIZE ) << j ) +
1764 ( ( GetLengthSid ( pSIDadmin ) + ACE_HEADER_SIZE ) << j ) +
1765 ( ( GetLengthSid ( pSIDworld ) + ACE_HEADER_SIZE ) << j )
1768 if ( ( pACL = CreateAcl ( dwACLsize ) ) == NULL ) __leave;
1770 if ( dwAccessAdmin != 0 )
1772 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1779 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1783 pFileACE -> dwMask = dwAccessAdminDir;
1784 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1785 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1789 FreeAce ( pFileACE );
1793 if ( dwAccessOwner != 0 )
1795 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1796 dwAccessOwner, 0, pSIDowner
1801 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1805 pFileACE -> dwMask = dwAccessOwnerDir;
1806 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1807 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1811 FreeAce ( pFileACE );
1815 if ( dwAccessWorld != 0 )
1817 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1818 dwAccessWorld, 0, pSIDworld
1823 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1827 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1828 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1832 FreeAce ( pFileACE );
1836 if ( dwAccessGroup != 0 ) {
1838 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1840 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1842 if ( !NtPredefinedSid ( pSIDtemp ) &&
1843 !EqualSid ( pSIDtemp, pSIDworld ) &&
1844 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1845 IsValidSid ( pSIDtemp )
1848 if ( dwAccessGroup != 0 )
1850 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1851 dwAccessGroup, 0, pSIDtemp
1856 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1860 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1861 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1865 FreeAce ( pFileACE );
1875 if ( ( retVal = AllocSD () ) == NULL ) __leave;
1877 if ( !SetSecurityDescriptorDacl ( retVal, TRUE, pACL, TRUE ) ) __leave;
1887 if ( retVal != NULL )
1891 else if ( pACL != NULL )
1899 if ( hProcess != NULL ) CloseHandle ( hProcess );
1900 if ( pTkOwner != NULL ) FreeTokenInformation ( pTkOwner );
1901 if ( pTkGroups != NULL ) FreeTokenInformation ( pTkGroups );
1902 if ( pTkPrimaryGroup != NULL ) FreeTokenInformation ( pTkPrimaryGroup );
1903 if ( pfSD != NULL ) FreeFileSecurity ( pfSD );
1908 leave: ; // added for VisualAge
1913 } // end _osd_wnt_protection_to_sd */
1915 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1921 static void __fastcall _test_raise ( HANDLE hFile, Standard_CString str ) {
1923 Standard_Character buff[ 64 ];
1925 if (hFile == INVALID_HANDLE_VALUE) {
1927 strcpy ( buff, "OSD_File :: " );
1928 strcat ( buff, str );
1929 strcat ( buff, " (): wrong access" );
1931 Standard_ProgramError :: Raise ( buff );
1935 } // end _test_raise
1937 // Returns number of bytes in the string (including end \n, but excluding \r);
1939 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos)
1942 Standard_PCharacter ptr;
1944 buffer[ dwBuffSize ] = 0;
1947 while ( *ptr != 0 ) {
1951 ptr++ ; // jump newline char.
1953 theSeekPos = (LONG)(ptr - buffer - dwBuffSize);
1954 return (Standard_Integer)(ptr - buffer);
1956 else if ( *ptr == '\r' && ptr[ 1 ] == '\n' )
1958 *(ptr++) = '\n' ; // Substitue carriage return by newline.
1960 theSeekPos = (LONG)(ptr + 1 - buffer - dwBuffSize);
1961 return (Standard_Integer)(ptr - buffer);
1963 else if ( *ptr == '\r' && ptr[ 1 ] == 0 ) {
1964 *ptr = '\n' ; // Substitue carriage return by newline
1975 static int __fastcall _get_buffer (
1977 Standard_PCharacter& buffer,
1979 BOOL fPeek, BOOL fSocket
1989 flags = fPeek ? MSG_PEEK : 0;
1991 retVal = recv ( ( SOCKET )hChannel, buffer, ( int )dwSize, flags );
1993 if ( retVal == SOCKET_ERROR ) retVal = -1;
1999 if ( !PeekNamedPipe (
2000 hChannel, buffer, dwSize, &dwBytesRead, &dwDummy, &dwDummy
2001 ) && GetLastError () != ERROR_BROKEN_PIPE
2008 retVal = ( int )dwBytesRead;
2012 if ( !ReadFile ( hChannel, buffer, dwSize, &dwBytesRead, NULL ) )
2018 retVal = ( int )dwBytesRead;
2026 } // end _get_buffer
2029 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection prt ) {
2043 retVal = FILE_GENERIC_READ;
2049 retVal = FILE_GENERIC_WRITE;
2055 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
2061 retVal = FILE_GENERIC_EXECUTE;
2067 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
2073 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2079 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2091 retVal = FILE_GENERIC_READ | DELETE;
2097 retVal = FILE_GENERIC_WRITE | DELETE;
2103 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE;
2109 retVal = FILE_GENERIC_EXECUTE | DELETE;
2115 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE;
2121 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2127 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2133 RAISE( "_get_access_mask (): incorrect parameter" );
2139 } // end _get_access_mask
2141 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt ) {
2155 retVal = GENERIC_READ;
2161 retVal = GENERIC_WRITE;
2167 retVal = GENERIC_READ | GENERIC_WRITE;
2173 retVal = GENERIC_EXECUTE;
2179 retVal = GENERIC_READ | GENERIC_EXECUTE;
2185 retVal = GENERIC_WRITE | GENERIC_EXECUTE;
2191 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
2203 retVal = GENERIC_READ | DELETE;
2209 retVal = GENERIC_WRITE | DELETE;
2215 retVal = GENERIC_READ | GENERIC_WRITE | DELETE;
2221 retVal = GENERIC_EXECUTE | DELETE;
2227 retVal = GENERIC_READ | GENERIC_EXECUTE | DELETE;
2233 retVal = GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2239 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2245 RAISE( "_get_dir_access_mask (): incorrect parameter" );
2251 } // end _get_dir_access_mask
2253 static HANDLE __fastcall _open_file (
2254 Standard_CString fName,
2256 DWORD dwOptions, LPBOOL fNew
2259 HANDLE retVal = INVALID_HANDLE_VALUE;
2260 DWORD dwDesiredAccess = 0;
2261 DWORD dwCreationDistribution;
2267 dwDesiredAccess = GENERIC_READ;
2273 dwDesiredAccess = GENERIC_WRITE;
2279 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2285 RAISE( "_open_file (): incorrect parameter" );
2289 dwCreationDistribution = ( dwOptions != OPEN_NEW ) ? OPEN_EXISTING : CREATE_ALWAYS;
2291 // make wide character string from UTF-8
2292 TCollection_ExtendedString fNameW(fName, Standard_True);
2293 retVal = CreateFileW (
2294 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2295 FILE_SHARE_READ | FILE_SHARE_WRITE,
2296 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2299 if ( retVal == INVALID_HANDLE_VALUE &&
2300 dwOptions == OPEN_APPEND &&
2301 GetLastError () == ERROR_FILE_NOT_FOUND
2305 dwCreationDistribution = CREATE_ALWAYS;
2307 retVal = CreateFileW (
2308 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2309 FILE_SHARE_READ | FILE_SHARE_WRITE,
2310 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2321 Standard_Integer __fastcall _get_file_type (
2322 Standard_CString fName, HANDLE fileHandle
2325 Standard_Integer retVal = 0;
2329 fileType = (fileHandle == INVALID_HANDLE_VALUE ?
2330 FILE_TYPE_DISK : GetFileType (fileHandle));
2332 switch ( fileType ) {
2334 case FILE_TYPE_UNKNOWN:
2336 retVal = FLAG_SOCKET;
2340 case FILE_TYPE_DISK:
2342 // make wide character string from UTF-8
2343 TCollection_ExtendedString fNameW(fName, Standard_True);
2344 dwType = GetFileAttributesW ( (const wchar_t*) fNameW.ToExtString() );
2345 if ( dwType != 0xFFFFFFFF )
2347 retVal = dwType & FILE_ATTRIBUTE_DIRECTORY ? FLAG_DIRECTORY : FLAG_FILE;
2351 retVal = 0x80000000;
2355 case FILE_TYPE_CHAR:
2357 retVal = FLAG_DEVICE;
2361 case FILE_TYPE_PIPE:
2371 } // end _get_file_type
2373 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2376 #define __leave return retVal
2379 BOOL __fastcall _osd_wnt_sd_to_protection (
2380 PSECURITY_DESCRIPTOR pSD, OSD_Protection& prot, BOOL fDir
2391 DWORD dwAccessOwner = 0;
2392 DWORD dwAccessGroup = 0;
2393 DWORD dwAccessAdmin = 0;
2394 DWORD dwAccessWorld = 0;
2395 BOOL retVal = FALSE;
2396 GET_PROT_FUNC _get_prot_func = fDir ? &_get_protection_dir : &_get_protection;
2400 if ( !GetSecurityDescriptorOwner ( pSD, &pSIDowner, &fDefaulted ) ) __leave;
2402 if ( !GetSecurityDescriptorDacl ( pSD, &fPresent, &pACL, &fDefaulted ) ||
2406 if ( pSIDowner == NULL || pACL == NULL ) {
2408 SetLastError ( ERROR_NO_SECURITY_ON_OBJECT );
2413 pSIDadmin = AdminSid ();
2414 pSIDworld = WorldSid ();
2416 for ( i = 0; i < ( int )pACL -> AceCount; ++i ) {
2418 if ( GetAce ( pACL, i, &pACE ) ) {
2420 if ( EqualSid ( pSIDowner, GET_SID( pACE ) ) )
2422 dwAccessOwner = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2423 0 : *GET_MSK( pACE );
2425 else if ( EqualSid ( pSIDadmin, GET_SID( pACE ) ) )
2427 dwAccessAdmin = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2428 0 : *GET_MSK( pACE );
2430 else if ( EqualSid ( pSIDworld, GET_SID( pACE ) ) )
2432 dwAccessWorld = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2433 0 : *GET_MSK( pACE );
2437 dwAccessGroup = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2438 0 : *GET_MSK( pACE );
2445 ( *_get_prot_func ) ( dwAccessAdmin ),
2446 ( *_get_prot_func ) ( dwAccessOwner ),
2447 ( *_get_prot_func ) ( dwAccessGroup ),
2448 ( *_get_prot_func ) ( dwAccessWorld )
2458 leave: ; // added for VisualAge
2463 } // end _osd_wnt_sd_to_protection
2465 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2471 static OSD_SingleProtection __fastcall _get_protection ( DWORD mask ) {
2473 OSD_SingleProtection retVal;
2477 case FILE_GENERIC_READ:
2483 case FILE_GENERIC_WRITE:
2489 case FILE_GENERIC_READ | FILE_GENERIC_WRITE:
2495 case FILE_GENERIC_EXECUTE:
2501 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE:
2507 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2513 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2525 case FILE_GENERIC_READ | DELETE:
2531 case FILE_GENERIC_WRITE | DELETE:
2537 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE:
2543 case FILE_GENERIC_EXECUTE | DELETE:
2549 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE:
2555 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2561 case FILE_ALL_ACCESS:
2562 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2577 } // end _get_protection
2579 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD mask ) {
2581 OSD_SingleProtection retVal;
2597 case GENERIC_READ | GENERIC_WRITE:
2603 case GENERIC_EXECUTE:
2609 case GENERIC_READ | GENERIC_EXECUTE:
2615 case GENERIC_WRITE | GENERIC_EXECUTE:
2621 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE:
2633 case GENERIC_READ | DELETE:
2639 case GENERIC_WRITE | DELETE:
2645 case GENERIC_READ | GENERIC_WRITE | DELETE:
2651 case GENERIC_EXECUTE | DELETE:
2657 case GENERIC_READ | GENERIC_EXECUTE | DELETE:
2663 case GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2669 case FILE_ALL_ACCESS:
2670 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2685 } // end _get_protection_dir
2687 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2690 #define __leave return fOK
2693 BOOL __fastcall _osd_print (const Standard_PCharacter pName, const wchar_t* fName ) {
2696 HANDLE hPrinter = NULL;
2697 BYTE jobInfo[ MAX_PATH + sizeof ( DWORD ) ];
2698 DWORD dwNeeded, dwCode = 0;
2704 if ( !OpenPrinter ( Standard_PCharacter(pName), &hPrinter, NULL ) ) {
2712 hPrinter, 1, jobInfo, MAX_PATH + sizeof ( DWORD ), &dwNeeded
2719 fName, (LPWSTR) ( ( ADDJOB_INFO_1* )jobInfo ) -> Path, FALSE
2724 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId
2737 DWORD dwBytesNeeded;
2739 dwCode = GetLastError ();
2741 if ( fJob && hPrinter != NULL ) {
2744 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId, 1,
2745 info, 1024, &dwBytesNeeded
2748 if ( fJob ) SetJob (
2750 ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId,
2751 1, info, JOB_CONTROL_CANCEL
2758 if ( hPrinter != NULL ) ClosePrinter ( hPrinter );
2763 leave: ; // added for VisualAge
2766 if ( !fOK ) SetLastError ( dwCode );
2772 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2778 Standard_Boolean OSD_File::IsReadable()
2780 TCollection_AsciiString FileName ;
2783 myPath.SystemName(FileName) ;
2784 Channel = _open_file(FileName.ToCString(), OSD_ReadOnly, OPEN_OLD) ;
2785 if (Channel == INVALID_HANDLE_VALUE)
2786 return Standard_False ;
2788 CloseHandle (Channel) ;
2789 return Standard_True ;
2794 Standard_Boolean OSD_File::IsWriteable()
2796 TCollection_AsciiString FileName ;
2799 myPath.SystemName(FileName) ;
2800 Channel = _open_file(FileName.ToCString(), OSD_ReadWrite, OPEN_OLD) ;
2801 if (Channel == INVALID_HANDLE_VALUE)
2802 return Standard_False ;
2804 CloseHandle (Channel) ;
2805 return Standard_True ;
2809 Standard_Boolean OSD_File::IsExecutable()
2811 return IsReadable() ;
2813 // if (_access(FileName.ToCString(),0))
2818 // ---------------------------------------------------------------------
2819 // Destructs a file object (unlocks and closes file if it is open)
2820 // ---------------------------------------------------------------------
2822 OSD_File::~OSD_File()
2832 // ---------------------------------------------------------------------
2833 // Read lines in a file while it is increasing.
2834 // Each line is terminated with a <nl>.
2835 // ---------------------------------------------------------------------
2839 Standard_Boolean OSD_File::ReadLastLine(TCollection_AsciiString& aLine,const Standard_Integer aDelay,const Standard_Integer aNbTries)
2841 static Standard_Integer MaxLength = 1000 ;
2842 Standard_Integer Len ;
2843 Standard_Integer Count = aNbTries ;
2846 return Standard_False ;
2848 ReadLine(aLine, MaxLength, Len) ;
2849 if (!aLine.IsEmpty())
2850 return Standard_True ;
2852 return Standard_False ;
2853 OSD::SecSleep(aDelay) ;
2858 Standard_Boolean OSD_File::Edit()
2860 cout << "Function OSD_File::Edit() not yet implemented." << endl;
2861 return Standard_False ;