]>
git.saurik.com Git - apt.git/blob - apt-pkg/contrib/fileutl.cc
d5e7192e3d4a854ed3319848602d5218736434ad
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: fileutl.cc,v 1.42 2002/09/14 05:29:22 jgg Exp $
4 /* ######################################################################
8 CopyFile - Buffered copy of a single file
9 GetLock - dpkg compatible lock file manipulation (fcntl)
11 Most of this source is placed in the Public Domain, do with it what
13 It was originally written by Jason Gunthorpe <jgg@debian.org>.
14 FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
16 The exception is RunScripts() it is under the GPLv2
18 ##################################################################### */
20 // Include Files /*{{{*/
23 #include <apt-pkg/fileutl.h>
24 #include <apt-pkg/strutl.h>
25 #include <apt-pkg/error.h>
26 #include <apt-pkg/sptr.h>
27 #include <apt-pkg/configuration.h>
37 #include <sys/types.h>
46 #ifdef WORDS_BIGENDIAN
55 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
56 // ---------------------------------------------------------------------
58 bool RunScripts(const char *Cnf
)
60 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
61 if (Opts
== 0 || Opts
->Child
== 0)
65 // Fork for running the system calls
66 pid_t Child
= ExecFork();
71 if (_config
->FindDir("DPkg::Chroot-Directory","/") != "/")
73 std::cerr
<< "Chrooting into "
74 << _config
->FindDir("DPkg::Chroot-Directory")
76 if (chroot(_config
->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
80 if (chdir("/tmp/") != 0)
83 unsigned int Count
= 1;
84 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
86 if (Opts
->Value
.empty() == true)
89 if (system(Opts
->Value
.c_str()) != 0)
97 while (waitpid(Child
,&Status
,0) != Child
)
101 return _error
->Errno("waitpid","Couldn't wait for subprocess");
104 // Restore sig int/quit
105 signal(SIGQUIT
,SIG_DFL
);
106 signal(SIGINT
,SIG_DFL
);
108 // Check for an error code.
109 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
111 unsigned int Count
= WEXITSTATUS(Status
);
115 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
116 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
119 return _error
->Error("Sub-process returned an error code");
126 // CopyFile - Buffered copy of a file /*{{{*/
127 // ---------------------------------------------------------------------
128 /* The caller is expected to set things so that failure causes erasure */
129 bool CopyFile(FileFd
&From
,FileFd
&To
)
131 if (From
.IsOpen() == false || To
.IsOpen() == false)
134 // Buffered copy between fds
135 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
136 unsigned long long Size
= From
.Size();
139 unsigned long long ToRead
= Size
;
143 if (From
.Read(Buf
,ToRead
) == false ||
144 To
.Write(Buf
,ToRead
) == false)
153 // GetLock - Gets a lock file /*{{{*/
154 // ---------------------------------------------------------------------
155 /* This will create an empty file of the given name and lock it. Once this
156 is done all other calls to GetLock in any other process will fail with
157 -1. The return result is the fd of the file, the call should call
158 close at some time. */
159 int GetLock(string File
,bool Errors
)
161 // GetLock() is used in aptitude on directories with public-write access
162 // Use O_NOFOLLOW here to prevent symlink traversal attacks
163 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
166 // Read only .. cant have locking problems there.
169 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
170 return dup(0); // Need something for the caller to close
174 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
176 // Feh.. We do this to distinguish the lock vs open case..
180 SetCloseExec(FD
,true);
182 // Aquire a write lock
185 fl
.l_whence
= SEEK_SET
;
188 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
192 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
193 return dup(0); // Need something for the caller to close
196 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
207 // FileExists - Check if a file exists /*{{{*/
208 // ---------------------------------------------------------------------
209 /* Beware: Directories are also files! */
210 bool FileExists(string File
)
213 if (stat(File
.c_str(),&Buf
) != 0)
218 // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
219 // ---------------------------------------------------------------------
221 bool RealFileExists(string File
)
224 if (stat(File
.c_str(),&Buf
) != 0)
226 return ((Buf
.st_mode
& S_IFREG
) != 0);
229 // DirectoryExists - Check if a directory exists and is really one /*{{{*/
230 // ---------------------------------------------------------------------
232 bool DirectoryExists(string
const &Path
)
235 if (stat(Path
.c_str(),&Buf
) != 0)
237 return ((Buf
.st_mode
& S_IFDIR
) != 0);
240 // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
241 // ---------------------------------------------------------------------
242 /* This method will create all directories needed for path in good old
243 mkdir -p style but refuses to do this if Parent is not a prefix of
244 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
245 so it will create apt/archives if /var/cache exists - on the other
246 hand if the parent is /var/lib the creation will fail as this path
247 is not a parent of the path to be generated. */
248 bool CreateDirectory(string
const &Parent
, string
const &Path
)
250 if (Parent
.empty() == true || Path
.empty() == true)
253 if (DirectoryExists(Path
) == true)
256 if (DirectoryExists(Parent
) == false)
259 // we are not going to create directories "into the blue"
260 if (Path
.find(Parent
, 0) != 0)
263 vector
<string
> const dirs
= VectorizeString(Path
.substr(Parent
.size()), '/');
264 string progress
= Parent
;
265 for (vector
<string
>::const_iterator d
= dirs
.begin(); d
!= dirs
.end(); ++d
)
267 if (d
->empty() == true)
270 progress
.append("/").append(*d
);
271 if (DirectoryExists(progress
) == true)
274 if (mkdir(progress
.c_str(), 0755) != 0)
280 // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
281 // ---------------------------------------------------------------------
282 /* a small wrapper around CreateDirectory to check if it exists and to
283 remove the trailing "/apt/" from the parent directory if needed */
284 bool CreateAPTDirectoryIfNeeded(string
const &Parent
, string
const &Path
)
286 if (DirectoryExists(Path
) == true)
289 size_t const len
= Parent
.size();
290 if (len
> 5 && Parent
.find("/apt/", len
- 6, 5) == len
- 5)
292 if (CreateDirectory(Parent
.substr(0,len
-5), Path
) == true)
295 else if (CreateDirectory(Parent
, Path
) == true)
301 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
302 // ---------------------------------------------------------------------
303 /* If an extension is given only files with this extension are included
304 in the returned vector, otherwise every "normal" file is included. */
305 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
306 bool const &SortList
, bool const &AllowNoExt
)
308 std::vector
<string
> ext
;
310 if (Ext
.empty() == false)
312 if (AllowNoExt
== true && ext
.empty() == false)
314 return GetListOfFilesInDir(Dir
, ext
, SortList
);
316 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, std::vector
<string
> const &Ext
,
317 bool const &SortList
)
319 // Attention debuggers: need to be set with the environment config file!
320 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
323 std::clog
<< "Accept in " << Dir
<< " only files with the following " << Ext
.size() << " extensions:" << std::endl
;
324 if (Ext
.empty() == true)
325 std::clog
<< "\tNO extension" << std::endl
;
327 for (std::vector
<string
>::const_iterator e
= Ext
.begin();
329 std::clog
<< '\t' << (e
->empty() == true ? "NO" : *e
) << " extension" << std::endl
;
332 std::vector
<string
> List
;
334 if (DirectoryExists(Dir
.c_str()) == false)
336 _error
->Error(_("List of files can't be created as '%s' is not a directory"), Dir
.c_str());
340 Configuration::MatchAgainstConfig
SilentIgnore("Dir::Ignore-Files-Silently");
341 DIR *D
= opendir(Dir
.c_str());
344 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
348 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
350 // skip "hidden" files
351 if (Ent
->d_name
[0] == '.')
354 // Make sure it is a file and not something else
355 string
const File
= flCombine(Dir
,Ent
->d_name
);
356 #ifdef _DIRENT_HAVE_D_TYPE
357 if (Ent
->d_type
!= DT_REG
)
360 if (RealFileExists(File
.c_str()) == false)
362 if (SilentIgnore
.Match(Ent
->d_name
) == false)
363 _error
->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent
->d_name
, Dir
.c_str());
368 // check for accepted extension:
369 // no extension given -> periods are bad as hell!
370 // extensions given -> "" extension allows no extension
371 if (Ext
.empty() == false)
373 string d_ext
= flExtension(Ent
->d_name
);
374 if (d_ext
== Ent
->d_name
) // no extension
376 if (std::find(Ext
.begin(), Ext
.end(), "") == Ext
.end())
379 std::clog
<< "Bad file: " << Ent
->d_name
<< " → no extension" << std::endl
;
380 if (SilentIgnore
.Match(Ent
->d_name
) == false)
381 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent
->d_name
, Dir
.c_str());
385 else if (std::find(Ext
.begin(), Ext
.end(), d_ext
) == Ext
.end())
388 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad extension »" << flExtension(Ent
->d_name
) << "«" << std::endl
;
389 if (SilentIgnore
.Match(Ent
->d_name
) == false)
390 _error
->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent
->d_name
, Dir
.c_str());
395 // Skip bad filenames ala run-parts
396 const char *C
= Ent
->d_name
;
398 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
399 && *C
!= '_' && *C
!= '-') {
400 // no required extension -> dot is a bad character
401 if (*C
== '.' && Ext
.empty() == false)
406 // we don't reach the end of the name -> bad character included
410 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »"
411 << *C
<< "« in filename (period allowed: " << (Ext
.empty() ? "no" : "yes") << ")" << std::endl
;
415 // skip filenames which end with a period. These are never valid
419 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
424 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
425 List
.push_back(File
);
429 if (SortList
== true)
430 std::sort(List
.begin(),List
.end());
434 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
435 // ---------------------------------------------------------------------
436 /* We return / on failure. */
439 // Stash the current dir.
442 if (getcwd(S
,sizeof(S
)-2) == 0)
444 unsigned int Len
= strlen(S
);
450 // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
451 // ---------------------------------------------------------------------
452 /* We return / on failure. */
453 time_t GetModificationTime(string
const &Path
)
456 if (stat(Path
.c_str(), &St
) < 0)
461 // flNotDir - Strip the directory from the filename /*{{{*/
462 // ---------------------------------------------------------------------
464 string
flNotDir(string File
)
466 string::size_type Res
= File
.rfind('/');
467 if (Res
== string::npos
)
470 return string(File
,Res
,Res
- File
.length());
473 // flNotFile - Strip the file from the directory name /*{{{*/
474 // ---------------------------------------------------------------------
475 /* Result ends in a / */
476 string
flNotFile(string File
)
478 string::size_type Res
= File
.rfind('/');
479 if (Res
== string::npos
)
482 return string(File
,0,Res
);
485 // flExtension - Return the extension for the file /*{{{*/
486 // ---------------------------------------------------------------------
488 string
flExtension(string File
)
490 string::size_type Res
= File
.rfind('.');
491 if (Res
== string::npos
)
494 return string(File
,Res
,Res
- File
.length());
497 // flNoLink - If file is a symlink then deref it /*{{{*/
498 // ---------------------------------------------------------------------
499 /* If the name is not a link then the returned path is the input. */
500 string
flNoLink(string File
)
503 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
505 if (stat(File
.c_str(),&St
) != 0)
508 /* Loop resolving the link. There is no need to limit the number of
509 loops because the stat call above ensures that the symlink is not
517 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
518 (unsigned)Res
>= sizeof(Buffer
))
521 // Append or replace the previous path
523 if (Buffer
[0] == '/')
526 NFile
= flNotFile(NFile
) + Buffer
;
528 // See if we are done
529 if (lstat(NFile
.c_str(),&St
) != 0)
531 if (S_ISLNK(St
.st_mode
) == 0)
536 // flCombine - Combine a file and a directory /*{{{*/
537 // ---------------------------------------------------------------------
538 /* If the file is an absolute path then it is just returned, otherwise
539 the directory is pre-pended to it. */
540 string
flCombine(string Dir
,string File
)
542 if (File
.empty() == true)
545 if (File
[0] == '/' || Dir
.empty() == true)
547 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
549 if (Dir
[Dir
.length()-1] == '/')
551 return Dir
+ '/' + File
;
554 // SetCloseExec - Set the close on exec flag /*{{{*/
555 // ---------------------------------------------------------------------
557 void SetCloseExec(int Fd
,bool Close
)
559 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
561 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
566 // SetNonBlock - Set the nonblocking flag /*{{{*/
567 // ---------------------------------------------------------------------
569 void SetNonBlock(int Fd
,bool Block
)
571 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
572 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
574 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
579 // WaitFd - Wait for a FD to become readable /*{{{*/
580 // ---------------------------------------------------------------------
581 /* This waits for a FD to become readable using select. It is useful for
582 applications making use of non-blocking sockets. The timeout is
584 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
597 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
599 while (Res
< 0 && errno
== EINTR
);
609 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
611 while (Res
< 0 && errno
== EINTR
);
620 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
621 // ---------------------------------------------------------------------
622 /* This is used if you want to cleanse the environment for the forked
623 child, it fixes up the important signals and nukes all of the fds,
624 otherwise acts like normal fork. */
627 // Fork off the process
628 pid_t Process
= fork();
631 cerr
<< "FATAL -> Failed to fork." << endl
;
635 // Spawn the subprocess
639 signal(SIGPIPE
,SIG_DFL
);
640 signal(SIGQUIT
,SIG_DFL
);
641 signal(SIGINT
,SIG_DFL
);
642 signal(SIGWINCH
,SIG_DFL
);
643 signal(SIGCONT
,SIG_DFL
);
644 signal(SIGTSTP
,SIG_DFL
);
647 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
648 if (Opts
!= 0 && Opts
->Child
!= 0)
651 for (; Opts
!= 0; Opts
= Opts
->Next
)
653 if (Opts
->Value
.empty() == true)
655 int fd
= atoi(Opts
->Value
.c_str());
660 // Close all of our FDs - just in case
661 for (int K
= 3; K
!= 40; K
++)
663 if(KeepFDs
.find(K
) == KeepFDs
.end())
664 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
671 // ExecWait - Fancy waitpid /*{{{*/
672 // ---------------------------------------------------------------------
673 /* Waits for the given sub process. If Reap is set then no errors are
674 generated. Otherwise a failed subprocess will generate a proper descriptive
676 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
681 // Wait and collect the error code
683 while (waitpid(Pid
,&Status
,0) != Pid
)
691 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
695 // Check for an error code.
696 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
700 if (WIFSIGNALED(Status
) != 0)
702 if( WTERMSIG(Status
) == SIGSEGV
)
703 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
705 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
708 if (WIFEXITED(Status
) != 0)
709 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
711 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
718 // FileFd::Open - Open a file /*{{{*/
719 // ---------------------------------------------------------------------
720 /* The most commonly used open mode combinations are given with Mode */
721 bool FileFd::Open(string FileName
,OpenMode Mode
,CompressMode Compress
, unsigned long Perms
)
723 if (Mode
== ReadOnlyGzip
)
724 return Open(FileName
, ReadOnly
, Gzip
, Perms
);
729 #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
730 if_FLAGGED_SET(ReadWrite
, O_RDWR
);
731 else if_FLAGGED_SET(ReadOnly
, O_RDONLY
);
732 else if_FLAGGED_SET(WriteOnly
, O_WRONLY
);
733 else return _error
->Error("No openmode provided in FileFd::Open for %s", FileName
.c_str());
735 if_FLAGGED_SET(Create
, O_CREAT
);
736 if_FLAGGED_SET(Exclusive
, O_EXCL
);
737 else if_FLAGGED_SET(Atomic
, O_EXCL
);
738 if_FLAGGED_SET(Empty
, O_TRUNC
);
739 #undef if_FLAGGED_SET
741 if ((Mode
& Atomic
) == Atomic
)
744 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
745 TemporaryFileName
= string(mktemp(name
));
748 else if ((Mode
& (Exclusive
| Create
)) == (Exclusive
| Create
))
750 // for atomic, this will be done by rename in Close()
751 unlink(FileName
.c_str());
753 if ((Mode
& Empty
) == Empty
)
756 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
757 unlink(FileName
.c_str());
760 if (TemporaryFileName
.empty() == false)
761 iFd
= open(TemporaryFileName
.c_str(), fileflags
, Perms
);
763 iFd
= open(FileName
.c_str(), fileflags
, Perms
);
765 if (iFd
!= -1 && Compress
== Gzip
)
767 gz
= gzdopen (iFd
, "r");
776 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
778 this->FileName
= FileName
;
779 SetCloseExec(iFd
,true);
783 // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
784 // ---------------------------------------------------------------------
786 bool FileFd::OpenDescriptor(int Fd
, OpenMode Mode
, CompressMode Compress
, bool AutoClose
)
789 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
791 if (Mode
== ReadOnlyGzip
) {
792 gz
= gzdopen (iFd
, "r");
796 return _error
->Errno("gzdopen",_("Could not open file descriptor %d"),
804 // FileFd::~File - Closes the file /*{{{*/
805 // ---------------------------------------------------------------------
806 /* If the proper modes are selected then we close the Fd and possibly
807 unlink the file on error. */
813 // FileFd::Read - Read a bit of the file /*{{{*/
814 // ---------------------------------------------------------------------
815 /* We are carefull to handle interruption by a signal while reading
817 bool FileFd::Read(void *To
,unsigned long long Size
,unsigned long long *Actual
)
827 Res
= gzread(gz
,To
,Size
);
829 Res
= read(iFd
,To
,Size
);
830 if (Res
< 0 && errno
== EINTR
)
835 return _error
->Errno("read",_("Read error"));
838 To
= (char *)To
+ Res
;
843 while (Res
> 0 && Size
> 0);
856 return _error
->Error(_("read, still have %llu to read but none left"), Size
);
859 // FileFd::Write - Write to the file /*{{{*/
860 // ---------------------------------------------------------------------
862 bool FileFd::Write(const void *From
,unsigned long long Size
)
869 Res
= gzwrite(gz
,From
,Size
);
871 Res
= write(iFd
,From
,Size
);
872 if (Res
< 0 && errno
== EINTR
)
877 return _error
->Errno("write",_("Write error"));
880 From
= (char *)From
+ Res
;
883 while (Res
> 0 && Size
> 0);
889 return _error
->Error(_("write, still have %llu to write but couldn't"), Size
);
892 // FileFd::Seek - Seek in the file /*{{{*/
893 // ---------------------------------------------------------------------
895 bool FileFd::Seek(unsigned long long To
)
899 res
= gzseek(gz
,To
,SEEK_SET
);
901 res
= lseek(iFd
,To
,SEEK_SET
);
902 if (res
!= (signed)To
)
905 return _error
->Error("Unable to seek to %llu", To
);
911 // FileFd::Skip - Seek in the file /*{{{*/
912 // ---------------------------------------------------------------------
914 bool FileFd::Skip(unsigned long long Over
)
918 res
= gzseek(gz
,Over
,SEEK_CUR
);
920 res
= lseek(iFd
,Over
,SEEK_CUR
);
924 return _error
->Error("Unable to seek ahead %llu",Over
);
930 // FileFd::Truncate - Truncate the file /*{{{*/
931 // ---------------------------------------------------------------------
933 bool FileFd::Truncate(unsigned long long To
)
938 return _error
->Error("Truncating gzipped files is not implemented (%s)", FileName
.c_str());
940 if (ftruncate(iFd
,To
) != 0)
943 return _error
->Error("Unable to truncate to %llu",To
);
949 // FileFd::Tell - Current seek position /*{{{*/
950 // ---------------------------------------------------------------------
952 unsigned long long FileFd::Tell()
958 Res
= lseek(iFd
,0,SEEK_CUR
);
959 if (Res
== (off_t
)-1)
960 _error
->Errno("lseek","Failed to determine the current file position");
964 // FileFd::FileSize - Return the size of the file /*{{{*/
965 // ---------------------------------------------------------------------
967 unsigned long long FileFd::FileSize()
971 if (fstat(iFd
,&Buf
) != 0)
972 return _error
->Errno("fstat","Unable to determine the file size");
976 // FileFd::Size - Return the size of the content in the file /*{{{*/
977 // ---------------------------------------------------------------------
979 unsigned long long FileFd::Size()
981 unsigned long long size
= FileSize();
983 // only check gzsize if we are actually a gzip file, just checking for
984 // "gz" is not sufficient as uncompressed files will be opened with
985 // gzopen in "direct" mode as well
986 if (gz
&& !gzdirect(gz
) && size
> 0)
988 /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
989 * this ourselves; the original (uncompressed) file size is the last 32
990 * bits of the file */
991 // FIXME: Size for gz-files is limited by 32bit… no largefile support
992 off_t orig_pos
= lseek(iFd
, 0, SEEK_CUR
);
993 if (lseek(iFd
, -4, SEEK_END
) < 0)
994 return _error
->Errno("lseek","Unable to seek to end of gzipped file");
996 if (read(iFd
, &size
, 4) != 4)
997 return _error
->Errno("read","Unable to read original size of gzipped file");
999 #ifdef WORDS_BIGENDIAN
1000 uint32_t tmp_size
= size
;
1001 uint8_t const * const p
= (uint8_t const * const) &tmp_size
;
1002 tmp_size
= (p
[3] << 24) | (p
[2] << 16) | (p
[1] << 8) | p
[0];
1006 if (lseek(iFd
, orig_pos
, SEEK_SET
) < 0)
1007 return _error
->Errno("lseek","Unable to seek in gzipped file");
1014 // FileFd::Close - Close the file if the close flag is set /*{{{*/
1015 // ---------------------------------------------------------------------
1017 bool FileFd::Close()
1020 if ((Flags
& AutoClose
) == AutoClose
)
1023 int const e
= gzclose(gz
);
1024 // gzdopen() on empty files always fails with "buffer error" here, ignore that
1025 if (e
!= 0 && e
!= Z_BUF_ERROR
)
1026 Res
&= _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
1028 if (iFd
> 0 && close(iFd
) != 0)
1029 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
1032 if ((Flags
& Replace
) == Replace
&& iFd
>= 0) {
1033 if (rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
1034 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
1036 FileName
= TemporaryFileName
; // for the unlink() below.
1037 TemporaryFileName
.clear();
1043 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
1044 FileName
.empty() == false)
1045 if (unlink(FileName
.c_str()) != 0)
1046 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file %s"), FileName
.c_str());
1052 // FileFd::Sync - Sync the file /*{{{*/
1053 // ---------------------------------------------------------------------
1057 #ifdef _POSIX_SYNCHRONIZED_IO
1058 if (fsync(iFd
) != 0)
1059 return _error
->Errno("sync",_("Problem syncing the file"));