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());
757 // --------------------------------------------------------------------------
758 // Test if a file is open
759 // --------------------------------------------------------------------------
761 Standard_Boolean OSD_File::IsOpen()const{
762 return (myFileChannel != -1);
766 Standard_Boolean OSD_File::IsLocked(){
767 return(myLock != OSD_NoLock);
770 Standard_Boolean OSD_File::IsReadable()
772 TCollection_AsciiString FileName ;
774 myPath.SystemName(FileName) ;
776 if (access(FileName.ToCString(),F_OK|R_OK))
777 return Standard_False;
779 return Standard_True;
782 Standard_Boolean OSD_File::IsWriteable()
784 TCollection_AsciiString FileName ;
786 myPath.SystemName(FileName) ;
788 if (access(FileName.ToCString(),F_OK|R_OK|W_OK))
789 return Standard_False;
791 return Standard_True;
794 Standard_Boolean OSD_File::IsExecutable()
796 TCollection_AsciiString FileName ;
798 myPath.SystemName(FileName) ;
800 if (access(FileName.ToCString(),F_OK|X_OK))
801 return Standard_False;
803 return Standard_True;
808 //------------------------------------------------------------------------
809 //------------------- Windows NT sources for OSD_File -------------------
810 //------------------------------------------------------------------------
814 #include <OSD_File.hxx>
815 #include <OSD_Protection.hxx>
816 #include <OSD_Printer.hxx>
817 #include <Standard_ProgramError.hxx>
819 #include <OSD_WNT_1.hxx>
823 #include <Standard_PCharacter.hxx>
824 #include <TCollection_ExtendedString.hxx>
830 #if defined(__CYGWIN32__) || defined(__MINGW32__)
835 #pragma comment( lib, "WSOCK32.LIB" )
836 #pragma comment( lib, "WINSPOOL.LIB" )
838 #define ACE_HEADER_SIZE ( sizeof ( ACCESS_ALLOWED_ACE ) - sizeof ( DWORD ) )
840 #define RAISE( arg ) Standard_ProgramError :: Raise ( ( arg ) )
841 #define TEST_RAISE( arg ) _test_raise ( myFileHandle, ( arg ) )
845 #define OPEN_APPEND 2
847 void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
848 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd ( const OSD_Protection&, BOOL, wchar_t* = NULL );
849 BOOL __fastcall _osd_wnt_sd_to_protection (
850 PSECURITY_DESCRIPTOR, OSD_Protection&, BOOL
852 BOOL __fastcall _osd_print (const Standard_PCharacter, const wchar_t* );
854 static void __fastcall _test_raise ( HANDLE, Standard_CString );
855 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos);
856 static int __fastcall _get_buffer ( HANDLE, Standard_PCharacter&, DWORD, BOOL, BOOL );
857 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection );
858 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt );
859 static HANDLE __fastcall _open_file ( Standard_CString, OSD_OpenMode, DWORD, LPBOOL = NULL );
861 static OSD_SingleProtection __fastcall _get_protection ( DWORD );
862 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD );
864 typedef OSD_SingleProtection ( __fastcall *GET_PROT_FUNC ) ( DWORD );
866 Standard_Integer __fastcall _get_file_type ( Standard_CString, HANDLE );
868 // ---------------------------------------------------------------------
869 // Create an empty file object
870 // ---------------------------------------------------------------------
872 OSD_File :: OSD_File ()
874 ImperativeFlag = Standard_False;
878 myFileHandle = INVALID_HANDLE_VALUE;
879 } // end constructor ( 1 )
881 // ---------------------------------------------------------------------
882 // Create and initialize a file object
883 // ---------------------------------------------------------------------
885 OSD_File :: OSD_File ( const OSD_Path& Name ) : OSD_FileNode ( Name )
887 ImperativeFlag = Standard_False;
892 myFileHandle = INVALID_HANDLE_VALUE;
893 } // end constructor ( 2 )
895 // protect against occasional use of myFileHande in Windows code
896 #define myFileChannel myFileChannel_is_only_for_Linux
898 // ---------------------------------------------------------------------
899 // Build a file if it doesn't exist or create again if it already exists
900 // ---------------------------------------------------------------------
902 void OSD_File :: Build (
903 const OSD_OpenMode Mode, const OSD_Protection& Protect
906 TCollection_AsciiString fName;
908 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
909 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
912 if (myFileHandle != INVALID_HANDLE_VALUE)
914 RAISE( "OSD_File :: Build (): incorrect call - file already opened" );
917 myPath.SystemName ( fName );
919 if ( fName.IsEmpty () )
921 RAISE( "OSD_File :: Build (): incorrent call - no filename given" );
923 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_NEW );
925 if (myFileHandle == INVALID_HANDLE_VALUE)
927 _osd_wnt_set_error ( myError, OSD_WFile );
931 SetProtection ( Protect );
936 } // end OSD_File :: Build
940 // ---------------------------------------------------------------------
942 // ---------------------------------------------------------------------
944 void OSD_File :: Open (const OSD_OpenMode Mode, const OSD_Protection& /*Protect*/)
947 TCollection_AsciiString fName;
950 if (myFileHandle != INVALID_HANDLE_VALUE)
952 RAISE( "OSD_File :: Open (): incorrect call - file already opened" );
955 myPath.SystemName ( fName );
957 if ( fName.IsEmpty () )
959 RAISE( "OSD_File :: Open (): incorrent call - no filename given" );
961 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_OLD );
963 if (myFileHandle == INVALID_HANDLE_VALUE) {
965 _osd_wnt_set_error ( myError, OSD_WFile );
969 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
971 } // end OSD_File :: Open
973 // ---------------------------------------------------------------------
974 // Append to an existing file
975 // ---------------------------------------------------------------------
977 void OSD_File :: Append (
978 const OSD_OpenMode Mode, const OSD_Protection& Protect
982 TCollection_AsciiString fName;
984 if (myFileHandle != INVALID_HANDLE_VALUE)
986 RAISE( "OSD_File :: Append (): incorrect call - file already opened" );
989 myPath.SystemName ( fName );
991 if ( fName.IsEmpty () )
993 RAISE( "OSD_File :: Append (): incorrent call - no filename given" );
995 myFileHandle = _open_file ( fName.ToCString (), Mode, OPEN_APPEND, &fNew );
997 if (myFileHandle == INVALID_HANDLE_VALUE)
999 _osd_wnt_set_error ( myError, OSD_WFile );
1005 myIO |= _get_file_type ( fName.ToCString (), myFileHandle );
1006 Seek ( 0, OSD_FromEnd );
1010 SetProtection ( Protect );
1017 } // end OSD_File :: Append
1019 // ---------------------------------------------------------------------
1020 // Read content of a file
1021 // ---------------------------------------------------------------------
1023 void OSD_File :: Read (
1024 TCollection_AsciiString& Buffer, const Standard_Integer Nbyte
1027 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1029 cout << " OSD_File::Read : it is a directory " << endl;
1032 // Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1035 Standard_Integer NbyteRead;
1036 Standard_Address buff;
1038 TEST_RAISE( "Read" );
1040 buff = ( Standard_Address )new Standard_Character[ Nbyte + 1 ];
1042 Read ( buff, Nbyte, NbyteRead );
1044 ( ( Standard_PCharacter )buff )[ NbyteRead ] = 0;
1046 if ( NbyteRead != 0 )
1048 Buffer = ( Standard_PCharacter )buff;
1056 } // end OSD_File :: Read
1058 // ---------------------------------------------------------------------
1059 // Read a line from a file
1060 // ---------------------------------------------------------------------
1062 // Modified so that we have <nl> at end of line if we have read <nl> or <cr>
1064 // by LD 17 dec 98 for B4.4
1066 void OSD_File :: ReadLine (
1067 TCollection_AsciiString& Buffer,
1068 const Standard_Integer NByte, Standard_Integer& NbyteRead
1073 Standard_Character peekChar;
1074 Standard_PCharacter ppeekChar;
1075 Standard_PCharacter cBuffer;
1078 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1079 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1082 TEST_RAISE( "ReadLine" );
1084 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1086 RAISE( "OSD_File :: ReadLine (): attempt to read from write only pipe" );
1088 // +----> leave space for end-of-string
1089 // | plus <CR><LF> sequence
1092 ppeekChar=&peekChar;
1093 cBuffer = new Standard_Character[ NByte + 3 ];
1095 if ( myIO & FLAG_FILE ) {
1097 if (!ReadFile (myFileHandle, cBuffer, NByte, &dwBytesRead, NULL)) { // an error occured
1099 _osd_wnt_set_error ( myError, OSD_WFile );
1103 } else if ( dwBytesRead == 0 ) { // end-of-file reached
1110 myIO &= ~FLAG_EOF ; // if the file increased since last read (LD)
1111 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1113 if ( NbyteRead == -1 ) // last character in the buffer is <CR> -
1114 { // peek next character to see if it is a <LF>
1115 if (!ReadFile (myFileHandle, ppeekChar, 1, &dwDummy, NULL)) {
1117 _osd_wnt_set_error ( myError, OSD_WFile );
1119 } else if ( dwDummy != 0 ) { // end-of-file reached ?
1121 if ( peekChar != '\n' ) // if we did not get a <CR><LF> sequence
1123 // adjust file position
1125 SetFilePointer (myFileHandle, -1, NULL, FILE_CURRENT);
1130 NbyteRead = dwBytesRead;
1132 } else if ( aSeekPos != 0 )
1134 SetFilePointer (myFileHandle, aSeekPos, NULL, FILE_CURRENT);
1139 } else if ( myIO & FLAG_SOCKET || myIO & FLAG_PIPE || myIO & FLAG_NAMED_PIPE ) {
1141 dwBytesRead = (DWORD)_get_buffer (myFileHandle, cBuffer,
1142 (DWORD)NByte, TRUE, myIO & FLAG_SOCKET);
1144 if ( ( int )dwBytesRead == -1 ) { // an error occured
1146 _osd_wnt_set_error ( myError, OSD_WFile );
1150 } else if ( dwBytesRead == 0 ) { // connection closed - set end-of-file flag
1158 NbyteRead = _get_line (cBuffer, dwBytesRead, aSeekPos);
1160 if (NbyteRead == -1) // last character in the buffer is <CR> -
1161 { // peek next character to see if it is a <LF>
1162 NbyteRead = dwBytesRead; // (LD) always fits this case.
1164 dwDummy = _get_buffer (myFileHandle, ppeekChar, 1, TRUE, myIO & FLAG_SOCKET);
1165 if ( ( int )dwDummy == -1 ) { // an error occured
1167 _osd_wnt_set_error ( myError, OSD_WFile );
1169 } else if ( dwDummy != 0 ) { // connection closed ?
1171 if ( peekChar == '\n' ) // we got a <CR><LF> sequence
1173 dwBytesRead++ ; // (LD) we have to jump <LF>
1178 } else if (aSeekPos != 0)
1180 dwBytesRead = dwBytesRead + aSeekPos;
1183 // Don't rewrite datas in cBuffer.
1185 Standard_PCharacter cDummyBuffer = new Standard_Character[ NByte + 3 ];
1187 // remove pending input
1188 _get_buffer (myFileHandle, cDummyBuffer, dwBytesRead, FALSE, myIO & FLAG_SOCKET);
1189 delete [] cDummyBuffer ;
1195 RAISE( "OSD_File :: ReadLine (): incorrect call - file is a directory" );
1197 if ( !Failed () && !IsAtEnd () )
1201 delete [] (Standard_PCharacter)cBuffer;
1203 } // end OSD_File :: ReadLine
1205 // --------------------------------------------------------------------------
1206 // Read content of a file
1207 // --------------------------------------------------------------------------
1209 void OSD_File :: Read (
1210 Standard_Address& Buffer,
1211 const Standard_Integer Nbyte, Standard_Integer& Readbyte
1216 if ( OSD_File::KindOfFile ( ) == OSD_DIRECTORY ) {
1217 Standard_ProgramError::Raise("OSD_File::Read : it is a directory");
1220 TEST_RAISE( "Read" );
1222 if ( myIO & FLAG_PIPE && !( myIO & FLAG_READ_PIPE ) )
1224 RAISE( "OSD_File :: Read (): attempt to read from write only pipe" );
1226 if (!ReadFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesRead, NULL)) {
1228 _osd_wnt_set_error ( myError, OSD_WFile );
1231 } else if ( dwBytesRead == 0 )
1239 Readbyte = ( Standard_Integer )dwBytesRead;
1241 } // end OSD_File :: Read
1243 void OSD_File :: Write (
1244 const TCollection_AsciiString& Buffer,
1245 const Standard_Integer Nbyte
1248 Write ( ( Standard_Address )Buffer.ToCString (), Nbyte );
1250 } // end OSD_File :: Write
1252 // --------------------------------------------------------------------------
1253 // Write content of a file
1254 // --------------------------------------------------------------------------
1256 void OSD_File :: Write (
1257 const Standard_Address Buffer,
1258 const Standard_Integer Nbyte
1261 DWORD dwBytesWritten;
1263 TEST_RAISE( "Write" );
1265 if ( myIO & FLAG_PIPE && myIO & FLAG_READ_PIPE )
1267 RAISE( "OSD_File :: Write (): attempt to write to read only pipe" );
1269 if (!WriteFile (myFileHandle, Buffer, (DWORD)Nbyte, &dwBytesWritten, NULL) ||
1270 dwBytesWritten != (DWORD)Nbyte)
1272 _osd_wnt_set_error ( myError, OSD_WFile );
1274 } // end OSD_File :: Write
1276 void OSD_File :: Seek (
1277 const Standard_Integer Offset, const OSD_FromWhere Whence
1280 DWORD dwMoveMethod = 0;
1282 TEST_RAISE( "Seek" );
1284 if ( myIO & FLAG_FILE || myIO & FLAG_DIRECTORY ) {
1288 case OSD_FromBeginning:
1290 dwMoveMethod = FILE_BEGIN;
1296 dwMoveMethod = FILE_CURRENT;
1302 dwMoveMethod = FILE_END;
1308 RAISE( "OSD_File :: Seek (): invalid parameter" );
1312 if (SetFilePointer (myFileHandle, (LONG)Offset, NULL, dwMoveMethod) == 0xFFFFFFFF)
1314 _osd_wnt_set_error ( myError, OSD_WFile );
1320 } // end OSD_File :: Seek
1322 // --------------------------------------------------------------------------
1324 // --------------------------------------------------------------------------
1326 void OSD_File :: Close () {
1328 TEST_RAISE( "Close" );
1330 CloseHandle (myFileHandle);
1332 myFileHandle = INVALID_HANDLE_VALUE;
1335 } // end OSD_File :: Close
1337 // --------------------------------------------------------------------------
1338 // Test if at end of file
1339 // --------------------------------------------------------------------------
1341 Standard_Boolean OSD_File :: IsAtEnd () {
1343 TEST_RAISE( "IsAtEnd" );
1345 if (myIO & FLAG_EOF)
1346 return Standard_True ;
1347 return Standard_False ;
1349 } // end OSD_File :: IsAtEnd
1351 OSD_KindFile OSD_File :: KindOfFile () const {
1353 OSD_KindFile retVal;
1354 Standard_Integer flags;
1356 if (myFileHandle == INVALID_HANDLE_VALUE) {
1358 TCollection_AsciiString fName;
1360 myPath.SystemName ( fName );
1362 if ( fName.IsEmpty () )
1364 RAISE( "OSD_File :: KindOfFile (): incorrent call - no filename given" );
1366 flags = _get_file_type (fName.ToCString(), INVALID_HANDLE_VALUE);
1372 switch ( flags & FLAG_TYPE ) {
1380 case FLAG_DIRECTORY:
1382 retVal = OSD_DIRECTORY;
1388 retVal = OSD_SOCKET;
1394 retVal = OSD_UNKNOWN;
1400 } // end OSD_File :: KindOfFile
1403 char tmpbuf [MAX_PATH];
1404 if (GetTempPath (MAX_PATH, tmpbuf) == 0)
1406 perror ("ERROR in GetTempPath");
1409 char tmpbuf2 [MAX_PATH];
1410 if (GetTempFileName (tmpbuf, NULL, 0, tmpbuf2) == 0)
1412 perror ("ERROR in GetTempFileName");
1415 TCollection_AsciiString fileName ( tmpbuf2 );
1417 TCollection_AsciiString fileName ( _ttmpnam ( NULL ) );
1421 //-------------------------------------------------debutpri???980424
1423 typedef struct _osd_wnt_key {
1431 OSD_File OSD_File :: BuildTemporary () {
1436 TCHAR tmpPath[ MAX_PATH ];
1438 OSD_WNT_KEY regKey[ 2 ] = {
1440 { HKEY_LOCAL_MACHINE,
1441 "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"
1444 ".DEFAULT\\Environment"
1449 for ( int i = 0; i < 2; ++i ) {
1452 regKey[ i ].hKey, regKey[ i ].keyPath, 0, KEY_QUERY_VALUE, &hKey
1459 if ( RegQueryValueEx (
1460 hKey, "TEMP", NULL, &dwType, NULL, &dwSize
1464 LPTSTR kVal = ( LPTSTR )HeapAlloc (
1465 GetProcessHeap (), HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS,
1466 dwSize + sizeof ( TCHAR )
1469 RegQueryValueEx ( hKey, "TEMP", NULL, &dwType, ( LPBYTE )kVal, &dwSize );
1471 if ( dwType == REG_EXPAND_SZ )
1473 ExpandEnvironmentStrings ( kVal, tmpPath, MAX_PATH );
1477 lstrcpy ( tmpPath, kVal );
1479 HeapFree ( GetProcessHeap (), 0, ( LPVOID )kVal );
1484 RegCloseKey ( hKey );
1492 if ( !fOK ) lstrcpy ( tmpPath, "./" );
1494 GetTempFileName ( tmpPath, "CSF", 0, tmpPath );
1496 retVal.SetPath ( OSD_Path ( tmpPath ) );
1497 retVal.Build ( OSD_ReadWrite, prt );
1501 } // end OSD_File :: BuildTemporary
1503 //-------------------------------------------------finpri???980424
1505 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1508 #define __leave return
1511 void OSD_File :: SetLock ( const OSD_LockType Lock ) {
1516 TEST_RAISE( "SetLock" );
1518 ZeroMemory ( &ovlp, sizeof ( OVERLAPPED ) );
1522 if ( ( myLock = Lock ) == OSD_NoLock ) {
1527 } else if ( myLock == OSD_ReadLock || myLock == OSD_ExclusiveLock ) {
1529 dwFlags = LOCKFILE_EXCLUSIVE_LOCK;
1535 LARGE_INTEGER aSize;
1536 aSize.QuadPart = Size();
1537 if (!LockFileEx (myFileHandle, dwFlags, 0, aSize.LowPart, aSize.HighPart, &ovlp)) {
1539 _osd_wnt_set_error ( myError, OSD_WFile );
1544 ImperativeFlag = Standard_True;
1551 leave: ; // added for VisualAge
1553 } // end OSD_File :: SetLock
1555 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1561 void OSD_File :: UnLock () {
1563 TEST_RAISE( "Unlock" );
1565 if ( ImperativeFlag ) {
1567 LARGE_INTEGER aSize;
1568 aSize.QuadPart = Size();
1569 if (!UnlockFile (myFileHandle, 0, 0, aSize.LowPart, aSize.HighPart))
1571 _osd_wnt_set_error ( myError, OSD_WFile );
1573 ImperativeFlag = Standard_False;
1577 } // end OSD_File :: UnLock
1579 OSD_LockType OSD_File :: GetLock () {
1583 } // end OSD_File :: GetLock
1585 Standard_Boolean OSD_File :: IsLocked () {
1587 TEST_RAISE( "IsLocked" );
1589 return ImperativeFlag;
1591 } // end OSD_File :: IsLocked
1594 // --------------------------------------------------------------------------
1595 // Return size of a file
1596 // --------------------------------------------------------------------------
1598 Standard_Size OSD_File :: Size () {
1600 Standard_Integer retVal;
1602 TEST_RAISE( "Size" );
1604 LARGE_INTEGER aSize;
1606 retVal = GetFileSizeEx (myFileHandle, &aSize);
1610 _osd_wnt_set_error ( myError, OSD_WFile );
1612 return (Standard_Size)aSize.QuadPart;
1614 } // end OSD_File :: Size
1616 // --------------------------------------------------------------------------
1617 // Print contains of a file
1618 // --------------------------------------------------------------------------
1620 void OSD_File :: Print ( const OSD_Printer& WhichPrinter ) {
1622 if (myFileHandle != INVALID_HANDLE_VALUE)
1624 RAISE( "OSD_File :: Print (): incorrect call - file opened" );
1626 TCollection_AsciiString pName, fName;
1628 WhichPrinter.Name ( pName );
1629 myPath.SystemName ( fName );
1630 TCollection_ExtendedString fNameW(fName);
1632 if ( !_osd_print ( (Standard_PCharacter)pName.ToCString (),
1633 (const wchar_t*)fNameW.ToExtString () ) )
1635 _osd_wnt_set_error ( myError, OSD_WFile );
1637 } // end OSD_File :: Print
1639 // --------------------------------------------------------------------------
1640 // Test if a file is open
1641 // --------------------------------------------------------------------------
1643 Standard_Boolean OSD_File :: IsOpen () const {
1645 return myFileHandle != INVALID_HANDLE_VALUE;
1647 } // end OSD_File :: IsOpen
1649 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1652 #define __leave return retVal
1655 PSECURITY_DESCRIPTOR __fastcall _osd_wnt_protection_to_sd (
1656 const OSD_Protection& prot, BOOL fDir, wchar_t* fName
1662 HANDLE hProcess = NULL;
1667 DWORD dwAccessAdmin;
1668 DWORD dwAccessGroup;
1669 DWORD dwAccessOwner;
1670 DWORD dwAccessWorld;
1671 DWORD dwAccessAdminDir;
1672 DWORD dwAccessGroupDir;
1673 DWORD dwAccessOwnerDir;
1674 DWORD dwAccessWorldDir;
1675 DWORD dwACLsize = sizeof ( ACL );
1677 PTOKEN_OWNER pTkOwner = NULL;
1678 PTOKEN_GROUPS pTkGroups = NULL;
1679 PTOKEN_PRIMARY_GROUP pTkPrimaryGroup = NULL;
1680 PSECURITY_DESCRIPTOR retVal = NULL;
1681 PSECURITY_DESCRIPTOR pfSD = NULL;
1689 if ( !OpenProcessToken (
1690 GetCurrentProcess (), TOKEN_QUERY, &hProcess
1694 if ( ( pTkGroups = ( PTOKEN_GROUPS )GetTokenInformationEx (
1695 hProcess, TokenGroups
1700 if ( ( pTkOwner = ( PTOKEN_OWNER )GetTokenInformationEx (
1701 hProcess, TokenOwner
1706 if ( ( pTkPrimaryGroup = ( PTOKEN_PRIMARY_GROUP )GetTokenInformationEx (
1707 hProcess, TokenPrimaryGroup
1714 if ( fName == NULL )
1716 pSIDowner = pTkOwner -> Owner;
1720 pfSD = GetFileSecurityEx ( fName, OWNER_SECURITY_INFORMATION );
1722 if ( pfSD == NULL || !GetSecurityDescriptorOwner ( pfSD, &pSIDowner, &fDummy ) ) {
1731 pSIDadmin = AdminSid ();
1732 pSIDworld = WorldSid ();
1734 dwAccessAdmin = _get_access_mask ( prot.System () );
1735 dwAccessGroup = _get_access_mask ( prot.Group () );
1736 dwAccessOwner = _get_access_mask ( prot.User () );
1737 dwAccessWorld = _get_access_mask ( prot.World () );
1739 dwAccessAdminDir = _get_dir_access_mask ( prot.System () );
1740 dwAccessGroupDir = _get_dir_access_mask ( prot.Group () );
1741 dwAccessOwnerDir = _get_dir_access_mask ( prot.User () );
1742 dwAccessWorldDir = _get_dir_access_mask ( prot.World () );
1744 if ( dwAccessGroup != 0 ) {
1746 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1748 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1750 if ( !NtPredefinedSid ( pSIDtemp ) &&
1751 !EqualSid ( pSIDtemp, pSIDworld ) &&
1752 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1753 IsValidSid ( pSIDtemp )
1756 dwACLsize += ( ( GetLengthSid ( pSIDtemp ) + ACE_HEADER_SIZE ) << j );
1762 dwACLsize += ( ( ( GetLengthSid ( pSIDowner ) + ACE_HEADER_SIZE ) << j ) +
1763 ( ( GetLengthSid ( pSIDadmin ) + ACE_HEADER_SIZE ) << j ) +
1764 ( ( GetLengthSid ( pSIDworld ) + ACE_HEADER_SIZE ) << j )
1767 if ( ( pACL = CreateAcl ( dwACLsize ) ) == NULL ) __leave;
1769 if ( dwAccessAdmin != 0 )
1771 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1778 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1782 pFileACE -> dwMask = dwAccessAdminDir;
1783 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1784 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1788 FreeAce ( pFileACE );
1792 if ( dwAccessOwner != 0 )
1794 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1795 dwAccessOwner, 0, pSIDowner
1800 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1804 pFileACE -> dwMask = dwAccessOwnerDir;
1805 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1806 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1810 FreeAce ( pFileACE );
1814 if ( dwAccessWorld != 0 )
1816 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1817 dwAccessWorld, 0, pSIDworld
1822 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1826 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1827 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1831 FreeAce ( pFileACE );
1835 if ( dwAccessGroup != 0 ) {
1837 for ( i = 0; i < ( int )pTkGroups -> GroupCount; ++i ) {
1839 pSIDtemp = pTkGroups -> Groups[ i ].Sid;
1841 if ( !NtPredefinedSid ( pSIDtemp ) &&
1842 !EqualSid ( pSIDtemp, pSIDworld ) &&
1843 !EqualSid ( pSIDtemp, pTkPrimaryGroup -> PrimaryGroup ) &&
1844 IsValidSid ( pSIDtemp )
1847 if ( dwAccessGroup != 0 )
1849 if ( ( pFileACE = ( PFILE_ACE )AllocAccessAllowedAce (
1850 dwAccessGroup, 0, pSIDtemp
1855 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1859 pFileACE -> header.AceFlags = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE;
1860 AddAce ( pACL, ACL_REVISION, dwIndex++, pFileACE, pFileACE -> header.AceSize );
1864 FreeAce ( pFileACE );
1874 if ( ( retVal = AllocSD () ) == NULL ) __leave;
1876 if ( !SetSecurityDescriptorDacl ( retVal, TRUE, pACL, TRUE ) ) __leave;
1886 if ( retVal != NULL )
1890 else if ( pACL != NULL )
1898 if ( hProcess != NULL ) CloseHandle ( hProcess );
1899 if ( pTkOwner != NULL ) FreeTokenInformation ( pTkOwner );
1900 if ( pTkGroups != NULL ) FreeTokenInformation ( pTkGroups );
1901 if ( pTkPrimaryGroup != NULL ) FreeTokenInformation ( pTkPrimaryGroup );
1902 if ( pfSD != NULL ) FreeFileSecurity ( pfSD );
1907 leave: ; // added for VisualAge
1912 } // end _osd_wnt_protection_to_sd */
1914 #if defined(__CYGWIN32__) || defined(__MINGW32__)
1920 static void __fastcall _test_raise ( HANDLE hFile, Standard_CString str ) {
1922 Standard_Character buff[ 64 ];
1924 if (hFile == INVALID_HANDLE_VALUE) {
1926 strcpy ( buff, "OSD_File :: " );
1927 strcat ( buff, str );
1928 strcat ( buff, " (): wrong access" );
1930 Standard_ProgramError :: Raise ( buff );
1934 } // end _test_raise
1936 // Returns number of bytes in the string (including end \n, but excluding \r);
1938 static Standard_Integer __fastcall _get_line (Standard_PCharacter& buffer, DWORD dwBuffSize, LONG& theSeekPos)
1941 Standard_PCharacter ptr;
1943 buffer[ dwBuffSize ] = 0;
1946 while ( *ptr != 0 ) {
1950 ptr++ ; // jump newline char.
1952 theSeekPos = (LONG)(ptr - buffer - dwBuffSize);
1953 return (Standard_Integer)(ptr - buffer);
1955 else if ( *ptr == '\r' && ptr[ 1 ] == '\n' )
1957 *(ptr++) = '\n' ; // Substitue carriage return by newline.
1959 theSeekPos = (LONG)(ptr + 1 - buffer - dwBuffSize);
1960 return (Standard_Integer)(ptr - buffer);
1962 else if ( *ptr == '\r' && ptr[ 1 ] == 0 ) {
1963 *ptr = '\n' ; // Substitue carriage return by newline
1974 static int __fastcall _get_buffer (
1976 Standard_PCharacter& buffer,
1978 BOOL fPeek, BOOL fSocket
1988 flags = fPeek ? MSG_PEEK : 0;
1990 retVal = recv ( ( SOCKET )hChannel, buffer, ( int )dwSize, flags );
1992 if ( retVal == SOCKET_ERROR ) retVal = -1;
1998 if ( !PeekNamedPipe (
1999 hChannel, buffer, dwSize, &dwBytesRead, &dwDummy, &dwDummy
2000 ) && GetLastError () != ERROR_BROKEN_PIPE
2007 retVal = ( int )dwBytesRead;
2011 if ( !ReadFile ( hChannel, buffer, dwSize, &dwBytesRead, NULL ) )
2017 retVal = ( int )dwBytesRead;
2025 } // end _get_buffer
2028 static DWORD __fastcall _get_access_mask ( OSD_SingleProtection prt ) {
2042 retVal = FILE_GENERIC_READ;
2048 retVal = FILE_GENERIC_WRITE;
2054 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
2060 retVal = FILE_GENERIC_EXECUTE;
2066 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
2072 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2078 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
2090 retVal = FILE_GENERIC_READ | DELETE;
2096 retVal = FILE_GENERIC_WRITE | DELETE;
2102 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE;
2108 retVal = FILE_GENERIC_EXECUTE | DELETE;
2114 retVal = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE;
2120 retVal = FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2126 retVal = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
2132 RAISE( "_get_access_mask (): incorrect parameter" );
2138 } // end _get_access_mask
2140 static DWORD __fastcall _get_dir_access_mask ( OSD_SingleProtection prt ) {
2154 retVal = GENERIC_READ;
2160 retVal = GENERIC_WRITE;
2166 retVal = GENERIC_READ | GENERIC_WRITE;
2172 retVal = GENERIC_EXECUTE;
2178 retVal = GENERIC_READ | GENERIC_EXECUTE;
2184 retVal = GENERIC_WRITE | GENERIC_EXECUTE;
2190 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
2202 retVal = GENERIC_READ | DELETE;
2208 retVal = GENERIC_WRITE | DELETE;
2214 retVal = GENERIC_READ | GENERIC_WRITE | DELETE;
2220 retVal = GENERIC_EXECUTE | DELETE;
2226 retVal = GENERIC_READ | GENERIC_EXECUTE | DELETE;
2232 retVal = GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2238 retVal = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE;
2244 RAISE( "_get_dir_access_mask (): incorrect parameter" );
2250 } // end _get_dir_access_mask
2252 static HANDLE __fastcall _open_file (
2253 Standard_CString fName,
2255 DWORD dwOptions, LPBOOL fNew
2258 HANDLE retVal = INVALID_HANDLE_VALUE;
2259 DWORD dwDesiredAccess = 0;
2260 DWORD dwCreationDistribution;
2266 dwDesiredAccess = GENERIC_READ;
2272 dwDesiredAccess = GENERIC_WRITE;
2278 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
2284 RAISE( "_open_file (): incorrect parameter" );
2288 dwCreationDistribution = ( dwOptions != OPEN_NEW ) ? OPEN_EXISTING : CREATE_ALWAYS;
2290 // make wide character string from UTF-8
2291 TCollection_ExtendedString fNameW(fName, Standard_True);
2292 retVal = CreateFileW (
2293 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2294 FILE_SHARE_READ | FILE_SHARE_WRITE,
2295 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2298 if ( retVal == INVALID_HANDLE_VALUE &&
2299 dwOptions == OPEN_APPEND &&
2300 GetLastError () == ERROR_FILE_NOT_FOUND
2304 dwCreationDistribution = CREATE_ALWAYS;
2306 retVal = CreateFileW (
2307 (const wchar_t*) fNameW.ToExtString(), dwDesiredAccess,
2308 FILE_SHARE_READ | FILE_SHARE_WRITE,
2309 NULL, dwCreationDistribution, FILE_ATTRIBUTE_NORMAL, NULL
2320 Standard_Integer __fastcall _get_file_type (
2321 Standard_CString fName, HANDLE fileHandle
2324 Standard_Integer retVal = 0;
2328 fileType = (fileHandle == INVALID_HANDLE_VALUE ?
2329 FILE_TYPE_DISK : GetFileType (fileHandle));
2331 switch ( fileType ) {
2333 case FILE_TYPE_UNKNOWN:
2335 retVal = FLAG_SOCKET;
2339 case FILE_TYPE_DISK:
2341 // make wide character string from UTF-8
2342 TCollection_ExtendedString fNameW(fName, Standard_True);
2343 dwType = GetFileAttributesW ( (const wchar_t*) fNameW.ToExtString() );
2344 if ( dwType != 0xFFFFFFFF )
2346 retVal = dwType & FILE_ATTRIBUTE_DIRECTORY ? FLAG_DIRECTORY : FLAG_FILE;
2350 retVal = 0x80000000;
2354 case FILE_TYPE_CHAR:
2356 retVal = FLAG_DEVICE;
2360 case FILE_TYPE_PIPE:
2370 } // end _get_file_type
2372 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2375 #define __leave return retVal
2378 BOOL __fastcall _osd_wnt_sd_to_protection (
2379 PSECURITY_DESCRIPTOR pSD, OSD_Protection& prot, BOOL fDir
2390 DWORD dwAccessOwner = 0;
2391 DWORD dwAccessGroup = 0;
2392 DWORD dwAccessAdmin = 0;
2393 DWORD dwAccessWorld = 0;
2394 BOOL retVal = FALSE;
2395 GET_PROT_FUNC _get_prot_func = fDir ? &_get_protection_dir : &_get_protection;
2399 if ( !GetSecurityDescriptorOwner ( pSD, &pSIDowner, &fDefaulted ) ) __leave;
2401 if ( !GetSecurityDescriptorDacl ( pSD, &fPresent, &pACL, &fDefaulted ) ||
2405 if ( pSIDowner == NULL || pACL == NULL ) {
2407 SetLastError ( ERROR_NO_SECURITY_ON_OBJECT );
2412 pSIDadmin = AdminSid ();
2413 pSIDworld = WorldSid ();
2415 for ( i = 0; i < ( int )pACL -> AceCount; ++i ) {
2417 if ( GetAce ( pACL, i, &pACE ) ) {
2419 if ( EqualSid ( pSIDowner, GET_SID( pACE ) ) )
2421 dwAccessOwner = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2422 0 : *GET_MSK( pACE );
2424 else if ( EqualSid ( pSIDadmin, GET_SID( pACE ) ) )
2426 dwAccessAdmin = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2427 0 : *GET_MSK( pACE );
2429 else if ( EqualSid ( pSIDworld, GET_SID( pACE ) ) )
2431 dwAccessWorld = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2432 0 : *GET_MSK( pACE );
2436 dwAccessGroup = ( ( PACE_HEADER )pACE ) -> AceType == ACCESS_DENIED_ACE_TYPE ?
2437 0 : *GET_MSK( pACE );
2444 ( *_get_prot_func ) ( dwAccessAdmin ),
2445 ( *_get_prot_func ) ( dwAccessOwner ),
2446 ( *_get_prot_func ) ( dwAccessGroup ),
2447 ( *_get_prot_func ) ( dwAccessWorld )
2457 leave: ; // added for VisualAge
2462 } // end _osd_wnt_sd_to_protection
2464 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2470 static OSD_SingleProtection __fastcall _get_protection ( DWORD mask ) {
2472 OSD_SingleProtection retVal;
2476 case FILE_GENERIC_READ:
2482 case FILE_GENERIC_WRITE:
2488 case FILE_GENERIC_READ | FILE_GENERIC_WRITE:
2494 case FILE_GENERIC_EXECUTE:
2500 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE:
2506 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2512 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE:
2524 case FILE_GENERIC_READ | DELETE:
2530 case FILE_GENERIC_WRITE | DELETE:
2536 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | DELETE:
2542 case FILE_GENERIC_EXECUTE | DELETE:
2548 case FILE_GENERIC_READ | FILE_GENERIC_EXECUTE | DELETE:
2554 case FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2560 case FILE_ALL_ACCESS:
2561 case FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE:
2576 } // end _get_protection
2578 static OSD_SingleProtection __fastcall _get_protection_dir ( DWORD mask ) {
2580 OSD_SingleProtection retVal;
2596 case GENERIC_READ | GENERIC_WRITE:
2602 case GENERIC_EXECUTE:
2608 case GENERIC_READ | GENERIC_EXECUTE:
2614 case GENERIC_WRITE | GENERIC_EXECUTE:
2620 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE:
2632 case GENERIC_READ | DELETE:
2638 case GENERIC_WRITE | DELETE:
2644 case GENERIC_READ | GENERIC_WRITE | DELETE:
2650 case GENERIC_EXECUTE | DELETE:
2656 case GENERIC_READ | GENERIC_EXECUTE | DELETE:
2662 case GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2668 case FILE_ALL_ACCESS:
2669 case GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | DELETE:
2684 } // end _get_protection_dir
2686 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2689 #define __leave return fOK
2692 BOOL __fastcall _osd_print (const Standard_PCharacter pName, const wchar_t* fName ) {
2695 HANDLE hPrinter = NULL;
2696 BYTE jobInfo[ MAX_PATH + sizeof ( DWORD ) ];
2697 DWORD dwNeeded, dwCode = 0;
2703 if ( !OpenPrinter ( Standard_PCharacter(pName), &hPrinter, NULL ) ) {
2711 hPrinter, 1, jobInfo, MAX_PATH + sizeof ( DWORD ), &dwNeeded
2718 fName, (LPWSTR) ( ( ADDJOB_INFO_1* )jobInfo ) -> Path, FALSE
2723 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId
2736 DWORD dwBytesNeeded;
2738 dwCode = GetLastError ();
2740 if ( fJob && hPrinter != NULL ) {
2743 hPrinter, ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId, 1,
2744 info, 1024, &dwBytesNeeded
2747 if ( fJob ) SetJob (
2749 ( ( ADDJOB_INFO_1* )jobInfo ) -> JobId,
2750 1, info, JOB_CONTROL_CANCEL
2757 if ( hPrinter != NULL ) ClosePrinter ( hPrinter );
2762 leave: ; // added for VisualAge
2765 if ( !fOK ) SetLastError ( dwCode );
2771 #if defined(__CYGWIN32__) || defined(__MINGW32__)
2777 Standard_Boolean OSD_File::IsReadable()
2779 TCollection_AsciiString FileName ;
2782 myPath.SystemName(FileName) ;
2783 Channel = _open_file(FileName.ToCString(), OSD_ReadOnly, OPEN_OLD) ;
2784 if (Channel == INVALID_HANDLE_VALUE)
2785 return Standard_False ;
2787 CloseHandle (Channel) ;
2788 return Standard_True ;
2793 Standard_Boolean OSD_File::IsWriteable()
2795 TCollection_AsciiString FileName ;
2798 myPath.SystemName(FileName) ;
2799 Channel = _open_file(FileName.ToCString(), OSD_ReadWrite, OPEN_OLD) ;
2800 if (Channel == INVALID_HANDLE_VALUE)
2801 return Standard_False ;
2803 CloseHandle (Channel) ;
2804 return Standard_True ;
2808 Standard_Boolean OSD_File::IsExecutable()
2810 return IsReadable() ;
2812 // if (_access(FileName.ToCString(),0))
2817 // ---------------------------------------------------------------------
2818 // Destructs a file object (unlocks and closes file if it is open)
2819 // ---------------------------------------------------------------------
2821 OSD_File::~OSD_File()
2831 // ---------------------------------------------------------------------
2832 // Read lines in a file while it is increasing.
2833 // Each line is terminated with a <nl>.
2834 // ---------------------------------------------------------------------
2838 Standard_Boolean OSD_File::ReadLastLine(TCollection_AsciiString& aLine,const Standard_Integer aDelay,const Standard_Integer aNbTries)
2840 static Standard_Integer MaxLength = 1000 ;
2841 Standard_Integer Len ;
2842 Standard_Integer Count = aNbTries ;
2845 return Standard_False ;
2847 ReadLine(aLine, MaxLength, Len) ;
2848 if (!aLine.IsEmpty())
2849 return Standard_True ;
2851 return Standard_False ;
2852 OSD::SecSleep(aDelay) ;
2857 Standard_Boolean OSD_File::Edit()
2859 cout << "Function OSD_File::Edit() not yet implemented." << endl;
2860 return Standard_False ;