]>
git.saurik.com Git - apt.git/blob - apt-pkg/contrib/fileutl.cc
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 /*{{{*/
21 #include <apt-pkg/fileutl.h>
22 #include <apt-pkg/strutl.h>
23 #include <apt-pkg/error.h>
24 #include <apt-pkg/sptr.h>
25 #include <apt-pkg/configuration.h>
37 #include <sys/types.h>
49 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
50 // ---------------------------------------------------------------------
52 bool RunScripts(const char *Cnf
)
54 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
55 if (Opts
== 0 || Opts
->Child
== 0)
59 // Fork for running the system calls
60 pid_t Child
= ExecFork();
65 if (chdir("/tmp/") != 0)
68 unsigned int Count
= 1;
69 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
71 if (Opts
->Value
.empty() == true)
74 if (system(Opts
->Value
.c_str()) != 0)
82 while (waitpid(Child
,&Status
,0) != Child
)
86 return _error
->Errno("waitpid","Couldn't wait for subprocess");
89 // Restore sig int/quit
90 signal(SIGQUIT
,SIG_DFL
);
91 signal(SIGINT
,SIG_DFL
);
93 // Check for an error code.
94 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
96 unsigned int Count
= WEXITSTATUS(Status
);
100 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
101 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
104 return _error
->Error("Sub-process returned an error code");
111 // CopyFile - Buffered copy of a file /*{{{*/
112 // ---------------------------------------------------------------------
113 /* The caller is expected to set things so that failure causes erasure */
114 bool CopyFile(FileFd
&From
,FileFd
&To
)
116 if (From
.IsOpen() == false || To
.IsOpen() == false)
119 // Buffered copy between fds
120 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
121 unsigned long Size
= From
.Size();
124 unsigned long ToRead
= Size
;
128 if (From
.Read(Buf
,ToRead
) == false ||
129 To
.Write(Buf
,ToRead
) == false)
138 // GetLock - Gets a lock file /*{{{*/
139 // ---------------------------------------------------------------------
140 /* This will create an empty file of the given name and lock it. Once this
141 is done all other calls to GetLock in any other process will fail with
142 -1. The return result is the fd of the file, the call should call
143 close at some time. */
144 int GetLock(string File
,bool Errors
)
146 // GetLock() is used in aptitude on directories with public-write access
147 // Use O_NOFOLLOW here to prevent symlink traversal attacks
148 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
151 // Read only .. cant have locking problems there.
154 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
155 return dup(0); // Need something for the caller to close
159 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
161 // Feh.. We do this to distinguish the lock vs open case..
165 SetCloseExec(FD
,true);
167 // Aquire a write lock
170 fl
.l_whence
= SEEK_SET
;
173 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
177 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
178 return dup(0); // Need something for the caller to close
181 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
192 // FileExists - Check if a file exists /*{{{*/
193 // ---------------------------------------------------------------------
195 bool FileExists(string File
)
198 if (stat(File
.c_str(),&Buf
) != 0)
203 // DirectoryExists - Check if a directory exists and is really one /*{{{*/
204 // ---------------------------------------------------------------------
206 bool DirectoryExists(string
const &Path
)
209 if (stat(Path
.c_str(),&Buf
) != 0)
211 return ((Buf
.st_mode
& S_IFDIR
) != 0);
214 // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
215 // ---------------------------------------------------------------------
216 /* This method will create all directories needed for path in good old
217 mkdir -p style but refuses to do this if Parent is not a prefix of
218 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
219 so it will create apt/archives if /var/cache exists - on the other
220 hand if the parent is /var/lib the creation will fail as this path
221 is not a parent of the path to be generated. */
222 bool CreateDirectory(string
const &Parent
, string
const &Path
)
224 if (Parent
.empty() == true || Path
.empty() == true)
227 if (DirectoryExists(Path
) == true)
230 if (DirectoryExists(Parent
) == false)
233 // we are not going to create directories "into the blue"
234 if (Path
.find(Parent
, 0) != 0)
237 vector
<string
> const dirs
= VectorizeString(Path
.substr(Parent
.size()), '/');
238 string progress
= Parent
;
239 for (vector
<string
>::const_iterator d
= dirs
.begin(); d
!= dirs
.end(); ++d
)
241 if (d
->empty() == true)
244 progress
.append("/").append(*d
);
245 if (DirectoryExists(progress
) == true)
248 if (mkdir(progress
.c_str(), 0755) != 0)
254 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
255 // ---------------------------------------------------------------------
256 /* If an extension is given only files with this extension are included
257 in the returned vector, otherwise every "normal" file is included. */
258 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
259 bool const &SortList
, bool const &AllowNoExt
)
261 std::vector
<string
> ext
;
263 if (Ext
.empty() == false)
265 if (AllowNoExt
== true && ext
.empty() == false)
267 return GetListOfFilesInDir(Dir
, ext
, SortList
);
269 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, std::vector
<string
> const &Ext
,
270 bool const &SortList
)
272 // Attention debuggers: need to be set with the environment config file!
273 bool const Debug
= _config
->FindB("Debug::GetListOfFilesInDir", false);
276 std::clog
<< "Accept in " << Dir
<< " only files with the following " << Ext
.size() << " extensions:" << std::endl
;
277 if (Ext
.empty() == true)
278 std::clog
<< "\tNO extension" << std::endl
;
280 for (std::vector
<string
>::const_iterator e
= Ext
.begin();
282 std::clog
<< '\t' << (e
->empty() == true ? "NO" : *e
) << " extension" << std::endl
;
285 std::vector
<string
> List
;
286 Configuration::MatchAgainstConfig
SilentIgnore("Dir::Ignore-Files-Silently");
287 DIR *D
= opendir(Dir
.c_str());
290 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
294 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
296 // skip "hidden" files
297 if (Ent
->d_name
[0] == '.')
300 // check for accepted extension:
301 // no extension given -> periods are bad as hell!
302 // extensions given -> "" extension allows no extension
303 if (Ext
.empty() == false)
305 string d_ext
= flExtension(Ent
->d_name
);
306 if (d_ext
== Ent
->d_name
) // no extension
308 if (std::find(Ext
.begin(), Ext
.end(), "") == Ext
.end())
311 std::clog
<< "Bad file: " << Ent
->d_name
<< " → no extension" << std::endl
;
312 if (SilentIgnore
.Match(Ent
->d_name
) == false)
313 _error
->Notice("Ignoring file '%s' in directory '%s' as it has no filename extension", Ent
->d_name
, Dir
.c_str());
317 else if (std::find(Ext
.begin(), Ext
.end(), d_ext
) == Ext
.end())
320 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad extension »" << flExtension(Ent
->d_name
) << "«" << std::endl
;
321 if (SilentIgnore
.Match(Ent
->d_name
) == false)
322 _error
->Notice("Ignoring file '%s' in directory '%s' as it has an invalid filename extension", Ent
->d_name
, Dir
.c_str());
327 // Skip bad filenames ala run-parts
328 const char *C
= Ent
->d_name
;
330 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
331 && *C
!= '_' && *C
!= '-') {
332 // no required extension -> dot is a bad character
333 if (*C
== '.' && Ext
.empty() == false)
338 // we don't reach the end of the name -> bad character included
342 std::clog
<< "Bad file: " << Ent
->d_name
<< " → bad character »"
343 << *C
<< "« in filename (period allowed: " << (Ext
.empty() ? "no" : "yes") << ")" << std::endl
;
347 // skip filenames which end with a period. These are never valid
351 std::clog
<< "Bad file: " << Ent
->d_name
<< " → Period as last character" << std::endl
;
355 // Make sure it is a file and not something else
356 string
const File
= flCombine(Dir
,Ent
->d_name
);
358 if (stat(File
.c_str(),&St
) != 0 || S_ISREG(St
.st_mode
) == 0)
361 std::clog
<< "Bad file: " << Ent
->d_name
<< " → stat says not a good file" << std::endl
;
366 std::clog
<< "Accept file: " << Ent
->d_name
<< " in " << Dir
<< std::endl
;
367 List
.push_back(File
);
371 if (SortList
== true)
372 std::sort(List
.begin(),List
.end());
376 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
377 // ---------------------------------------------------------------------
378 /* We return / on failure. */
381 // Stash the current dir.
384 if (getcwd(S
,sizeof(S
)-2) == 0)
386 unsigned int Len
= strlen(S
);
392 // flNotDir - Strip the directory from the filename /*{{{*/
393 // ---------------------------------------------------------------------
395 string
flNotDir(string File
)
397 string::size_type Res
= File
.rfind('/');
398 if (Res
== string::npos
)
401 return string(File
,Res
,Res
- File
.length());
404 // flNotFile - Strip the file from the directory name /*{{{*/
405 // ---------------------------------------------------------------------
406 /* Result ends in a / */
407 string
flNotFile(string File
)
409 string::size_type Res
= File
.rfind('/');
410 if (Res
== string::npos
)
413 return string(File
,0,Res
);
416 // flExtension - Return the extension for the file /*{{{*/
417 // ---------------------------------------------------------------------
419 string
flExtension(string File
)
421 string::size_type Res
= File
.rfind('.');
422 if (Res
== string::npos
)
425 return string(File
,Res
,Res
- File
.length());
428 // flNoLink - If file is a symlink then deref it /*{{{*/
429 // ---------------------------------------------------------------------
430 /* If the name is not a link then the returned path is the input. */
431 string
flNoLink(string File
)
434 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
436 if (stat(File
.c_str(),&St
) != 0)
439 /* Loop resolving the link. There is no need to limit the number of
440 loops because the stat call above ensures that the symlink is not
448 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
449 (unsigned)Res
>= sizeof(Buffer
))
452 // Append or replace the previous path
454 if (Buffer
[0] == '/')
457 NFile
= flNotFile(NFile
) + Buffer
;
459 // See if we are done
460 if (lstat(NFile
.c_str(),&St
) != 0)
462 if (S_ISLNK(St
.st_mode
) == 0)
467 // flCombine - Combine a file and a directory /*{{{*/
468 // ---------------------------------------------------------------------
469 /* If the file is an absolute path then it is just returned, otherwise
470 the directory is pre-pended to it. */
471 string
flCombine(string Dir
,string File
)
473 if (File
.empty() == true)
476 if (File
[0] == '/' || Dir
.empty() == true)
478 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
480 if (Dir
[Dir
.length()-1] == '/')
482 return Dir
+ '/' + File
;
485 // SetCloseExec - Set the close on exec flag /*{{{*/
486 // ---------------------------------------------------------------------
488 void SetCloseExec(int Fd
,bool Close
)
490 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
492 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
497 // SetNonBlock - Set the nonblocking flag /*{{{*/
498 // ---------------------------------------------------------------------
500 void SetNonBlock(int Fd
,bool Block
)
502 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
503 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
505 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
510 // WaitFd - Wait for a FD to become readable /*{{{*/
511 // ---------------------------------------------------------------------
512 /* This waits for a FD to become readable using select. It is useful for
513 applications making use of non-blocking sockets. The timeout is
515 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
528 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
530 while (Res
< 0 && errno
== EINTR
);
540 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
542 while (Res
< 0 && errno
== EINTR
);
551 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
552 // ---------------------------------------------------------------------
553 /* This is used if you want to cleanse the environment for the forked
554 child, it fixes up the important signals and nukes all of the fds,
555 otherwise acts like normal fork. */
558 // Fork off the process
559 pid_t Process
= fork();
562 cerr
<< "FATAL -> Failed to fork." << endl
;
566 // Spawn the subprocess
570 signal(SIGPIPE
,SIG_DFL
);
571 signal(SIGQUIT
,SIG_DFL
);
572 signal(SIGINT
,SIG_DFL
);
573 signal(SIGWINCH
,SIG_DFL
);
574 signal(SIGCONT
,SIG_DFL
);
575 signal(SIGTSTP
,SIG_DFL
);
578 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
579 if (Opts
!= 0 && Opts
->Child
!= 0)
582 for (; Opts
!= 0; Opts
= Opts
->Next
)
584 if (Opts
->Value
.empty() == true)
586 int fd
= atoi(Opts
->Value
.c_str());
591 // Close all of our FDs - just in case
592 for (int K
= 3; K
!= 40; K
++)
594 if(KeepFDs
.find(K
) == KeepFDs
.end())
595 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
602 // ExecWait - Fancy waitpid /*{{{*/
603 // ---------------------------------------------------------------------
604 /* Waits for the given sub process. If Reap is set then no errors are
605 generated. Otherwise a failed subprocess will generate a proper descriptive
607 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
612 // Wait and collect the error code
614 while (waitpid(Pid
,&Status
,0) != Pid
)
622 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
626 // Check for an error code.
627 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
631 if (WIFSIGNALED(Status
) != 0)
633 if( WTERMSIG(Status
) == SIGSEGV
)
634 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
636 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
639 if (WIFEXITED(Status
) != 0)
640 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
642 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
649 // FileFd::Open - Open a file /*{{{*/
650 // ---------------------------------------------------------------------
651 /* The most commonly used open mode combinations are given with Mode */
652 bool FileFd::Open(string FileName
,OpenMode Mode
, unsigned long Perms
)
659 iFd
= open(FileName
.c_str(),O_RDONLY
);
663 iFd
= open(FileName
.c_str(),O_RDONLY
);
665 gz
= gzdopen (iFd
, "r");
676 char *name
= strdup((FileName
+ ".XXXXXX").c_str());
677 TemporaryFileName
= string(mktemp(name
));
678 iFd
= open(TemporaryFileName
.c_str(),O_RDWR
| O_CREAT
| O_EXCL
,Perms
);
686 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
687 unlink(FileName
.c_str());
688 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,Perms
);
693 iFd
= open(FileName
.c_str(),O_RDWR
);
697 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
,Perms
);
701 unlink(FileName
.c_str());
702 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_EXCL
,Perms
);
707 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
709 this->FileName
= FileName
;
710 SetCloseExec(iFd
,true);
714 bool FileFd::OpenDescriptor(int Fd
, OpenMode Mode
, bool AutoClose
)
717 Flags
= (AutoClose
) ? FileFd::AutoClose
: 0;
719 if (Mode
== ReadOnlyGzip
) {
720 gz
= gzdopen (iFd
, "r");
724 return _error
->Errno("gzdopen",_("Could not open file descriptor %d"),
732 // FileFd::~File - Closes the file /*{{{*/
733 // ---------------------------------------------------------------------
734 /* If the proper modes are selected then we close the Fd and possibly
735 unlink the file on error. */
741 // FileFd::Read - Read a bit of the file /*{{{*/
742 // ---------------------------------------------------------------------
743 /* We are carefull to handle interruption by a signal while reading
745 bool FileFd::Read(void *To
,unsigned long Size
,unsigned long *Actual
)
755 Res
= gzread(gz
,To
,Size
);
757 Res
= read(iFd
,To
,Size
);
758 if (Res
< 0 && errno
== EINTR
)
763 return _error
->Errno("read",_("Read error"));
766 To
= (char *)To
+ Res
;
771 while (Res
> 0 && Size
> 0);
784 return _error
->Error(_("read, still have %lu to read but none left"),Size
);
787 // FileFd::Write - Write to the file /*{{{*/
788 // ---------------------------------------------------------------------
790 bool FileFd::Write(const void *From
,unsigned long Size
)
797 Res
= gzwrite(gz
,From
,Size
);
799 Res
= write(iFd
,From
,Size
);
800 if (Res
< 0 && errno
== EINTR
)
805 return _error
->Errno("write",_("Write error"));
808 From
= (char *)From
+ Res
;
811 while (Res
> 0 && Size
> 0);
817 return _error
->Error(_("write, still have %lu to write but couldn't"),Size
);
820 // FileFd::Seek - Seek in the file /*{{{*/
821 // ---------------------------------------------------------------------
823 bool FileFd::Seek(unsigned long To
)
827 res
= gzseek(gz
,To
,SEEK_SET
);
829 res
= lseek(iFd
,To
,SEEK_SET
);
830 if (res
!= (signed)To
)
833 return _error
->Error("Unable to seek to %lu",To
);
839 // FileFd::Skip - Seek in the file /*{{{*/
840 // ---------------------------------------------------------------------
842 bool FileFd::Skip(unsigned long Over
)
846 res
= gzseek(gz
,Over
,SEEK_CUR
);
848 res
= lseek(iFd
,Over
,SEEK_CUR
);
852 return _error
->Error("Unable to seek ahead %lu",Over
);
858 // FileFd::Truncate - Truncate the file /*{{{*/
859 // ---------------------------------------------------------------------
861 bool FileFd::Truncate(unsigned long To
)
866 return _error
->Error("Truncating gzipped files is not implemented (%s)", FileName
.c_str());
868 if (ftruncate(iFd
,To
) != 0)
871 return _error
->Error("Unable to truncate to %lu",To
);
877 // FileFd::Tell - Current seek position /*{{{*/
878 // ---------------------------------------------------------------------
880 unsigned long FileFd::Tell()
886 Res
= lseek(iFd
,0,SEEK_CUR
);
887 if (Res
== (off_t
)-1)
888 _error
->Errno("lseek","Failed to determine the current file position");
892 // FileFd::Size - Return the size of the file /*{{{*/
893 // ---------------------------------------------------------------------
895 unsigned long FileFd::Size()
897 //TODO: For gz, do we need the actual file size here or the uncompressed length?
899 if (fstat(iFd
,&Buf
) != 0)
900 return _error
->Errno("fstat","Unable to determine the file size");
904 // FileFd::Close - Close the file if the close flag is set /*{{{*/
905 // ---------------------------------------------------------------------
910 if ((Flags
& AutoClose
) == AutoClose
)
913 int const e
= gzclose(gz
);
914 // gzdopen() on empty files always fails with "buffer error" here, ignore that
915 if (e
!= 0 && e
!= Z_BUF_ERROR
)
916 Res
&= _error
->Errno("close",_("Problem closing the gzip file %s"), FileName
.c_str());
918 if (iFd
> 0 && close(iFd
) != 0)
919 Res
&= _error
->Errno("close",_("Problem closing the file %s"), FileName
.c_str());
922 if ((Flags
& Replace
) == Replace
&& iFd
>= 0) {
923 if (rename(TemporaryFileName
.c_str(), FileName
.c_str()) != 0)
924 Res
&= _error
->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName
.c_str(), FileName
.c_str());
926 FileName
= TemporaryFileName
; // for the unlink() below.
932 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
933 FileName
.empty() == false)
934 if (unlink(FileName
.c_str()) != 0)
935 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file %s"), FileName
.c_str());
941 // FileFd::Sync - Sync the file /*{{{*/
942 // ---------------------------------------------------------------------
946 #ifdef _POSIX_SYNCHRONIZED_IO
948 return _error
->Errno("sync",_("Problem syncing the file"));