]>
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>.
15 The exception is RunScripts() it is under the GPLv2
17 ##################################################################### */
19 // Include Files /*{{{*/
20 #include <apt-pkg/fileutl.h>
21 #include <apt-pkg/error.h>
22 #include <apt-pkg/sptr.h>
23 #include <apt-pkg/configuration.h>
34 #include <sys/types.h>
46 // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
47 // ---------------------------------------------------------------------
49 bool RunScripts(const char *Cnf
)
51 Configuration::Item
const *Opts
= _config
->Tree(Cnf
);
52 if (Opts
== 0 || Opts
->Child
== 0)
56 // Fork for running the system calls
57 pid_t Child
= ExecFork();
62 if (chdir("/tmp/") != 0)
65 unsigned int Count
= 1;
66 for (; Opts
!= 0; Opts
= Opts
->Next
, Count
++)
68 if (Opts
->Value
.empty() == true)
71 if (system(Opts
->Value
.c_str()) != 0)
79 while (waitpid(Child
,&Status
,0) != Child
)
83 return _error
->Errno("waitpid","Couldn't wait for subprocess");
86 // Restore sig int/quit
87 signal(SIGQUIT
,SIG_DFL
);
88 signal(SIGINT
,SIG_DFL
);
90 // Check for an error code.
91 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
93 unsigned int Count
= WEXITSTATUS(Status
);
97 for (; Opts
!= 0 && Count
!= 1; Opts
= Opts
->Next
, Count
--);
98 _error
->Error("Problem executing scripts %s '%s'",Cnf
,Opts
->Value
.c_str());
101 return _error
->Error("Sub-process returned an error code");
108 // CopyFile - Buffered copy of a file /*{{{*/
109 // ---------------------------------------------------------------------
110 /* The caller is expected to set things so that failure causes erasure */
111 bool CopyFile(FileFd
&From
,FileFd
&To
)
113 if (From
.IsOpen() == false || To
.IsOpen() == false)
116 // Buffered copy between fds
117 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
118 unsigned long Size
= From
.Size();
121 unsigned long ToRead
= Size
;
125 if (From
.Read(Buf
,ToRead
) == false ||
126 To
.Write(Buf
,ToRead
) == false)
135 // GetLock - Gets a lock file /*{{{*/
136 // ---------------------------------------------------------------------
137 /* This will create an empty file of the given name and lock it. Once this
138 is done all other calls to GetLock in any other process will fail with
139 -1. The return result is the fd of the file, the call should call
140 close at some time. */
141 int GetLock(string File
,bool Errors
)
143 // GetLock() is used in aptitude on directories with public-write access
144 // Use O_NOFOLLOW here to prevent symlink traversal attacks
145 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_NOFOLLOW
,0640);
148 // Read only .. cant have locking problems there.
151 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
152 return dup(0); // Need something for the caller to close
156 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
158 // Feh.. We do this to distinguish the lock vs open case..
162 SetCloseExec(FD
,true);
164 // Aquire a write lock
167 fl
.l_whence
= SEEK_SET
;
170 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
174 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
175 return dup(0); // Need something for the caller to close
178 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
189 // FileExists - Check if a file exists /*{{{*/
190 // ---------------------------------------------------------------------
192 bool FileExists(string File
)
195 if (stat(File
.c_str(),&Buf
) != 0)
200 // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
201 // ---------------------------------------------------------------------
202 /* If an extension is given only files with this extension are included
203 in the returned vector, otherwise every "normal" file is included. */
204 std::vector
<string
> GetListOfFilesInDir(string
const &Dir
, string
const &Ext
,
205 bool const &SortList
) {
206 std::vector
<string
> List
;
207 DIR *D
= opendir(Dir
.c_str());
209 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
213 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
)) {
214 if (Ent
->d_name
[0] == '.')
217 if (Ext
.empty() == false && flExtension(Ent
->d_name
) != Ext
)
220 // Skip bad file names ala run-parts
221 const char *C
= Ent
->d_name
;
223 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
224 && *C
!= '_' && *C
!= '-' && *C
!= '.')
230 // Make sure it is a file and not something else
231 string
const File
= flCombine(Dir
,Ent
->d_name
);
233 if (stat(File
.c_str(),&St
) != 0 || S_ISREG(St
.st_mode
) == 0)
236 List
.push_back(File
);
240 if (SortList
== true)
241 std::sort(List
.begin(),List
.end());
245 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
246 // ---------------------------------------------------------------------
247 /* We return / on failure. */
250 // Stash the current dir.
253 if (getcwd(S
,sizeof(S
)-2) == 0)
255 unsigned int Len
= strlen(S
);
261 // flNotDir - Strip the directory from the filename /*{{{*/
262 // ---------------------------------------------------------------------
264 string
flNotDir(string File
)
266 string::size_type Res
= File
.rfind('/');
267 if (Res
== string::npos
)
270 return string(File
,Res
,Res
- File
.length());
273 // flNotFile - Strip the file from the directory name /*{{{*/
274 // ---------------------------------------------------------------------
275 /* Result ends in a / */
276 string
flNotFile(string File
)
278 string::size_type Res
= File
.rfind('/');
279 if (Res
== string::npos
)
282 return string(File
,0,Res
);
285 // flExtension - Return the extension for the file /*{{{*/
286 // ---------------------------------------------------------------------
288 string
flExtension(string File
)
290 string::size_type Res
= File
.rfind('.');
291 if (Res
== string::npos
)
294 return string(File
,Res
,Res
- File
.length());
297 // flNoLink - If file is a symlink then deref it /*{{{*/
298 // ---------------------------------------------------------------------
299 /* If the name is not a link then the returned path is the input. */
300 string
flNoLink(string File
)
303 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
305 if (stat(File
.c_str(),&St
) != 0)
308 /* Loop resolving the link. There is no need to limit the number of
309 loops because the stat call above ensures that the symlink is not
317 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
318 (unsigned)Res
>= sizeof(Buffer
))
321 // Append or replace the previous path
323 if (Buffer
[0] == '/')
326 NFile
= flNotFile(NFile
) + Buffer
;
328 // See if we are done
329 if (lstat(NFile
.c_str(),&St
) != 0)
331 if (S_ISLNK(St
.st_mode
) == 0)
336 // flCombine - Combine a file and a directory /*{{{*/
337 // ---------------------------------------------------------------------
338 /* If the file is an absolute path then it is just returned, otherwise
339 the directory is pre-pended to it. */
340 string
flCombine(string Dir
,string File
)
342 if (File
.empty() == true)
345 if (File
[0] == '/' || Dir
.empty() == true)
347 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
349 if (Dir
[Dir
.length()-1] == '/')
351 return Dir
+ '/' + File
;
354 // SetCloseExec - Set the close on exec flag /*{{{*/
355 // ---------------------------------------------------------------------
357 void SetCloseExec(int Fd
,bool Close
)
359 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
361 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
366 // SetNonBlock - Set the nonblocking flag /*{{{*/
367 // ---------------------------------------------------------------------
369 void SetNonBlock(int Fd
,bool Block
)
371 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
372 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
374 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
379 // WaitFd - Wait for a FD to become readable /*{{{*/
380 // ---------------------------------------------------------------------
381 /* This waits for a FD to become readable using select. It is useful for
382 applications making use of non-blocking sockets. The timeout is
384 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
397 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
399 while (Res
< 0 && errno
== EINTR
);
409 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
411 while (Res
< 0 && errno
== EINTR
);
420 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
421 // ---------------------------------------------------------------------
422 /* This is used if you want to cleanse the environment for the forked
423 child, it fixes up the important signals and nukes all of the fds,
424 otherwise acts like normal fork. */
427 // Fork off the process
428 pid_t Process
= fork();
431 cerr
<< "FATAL -> Failed to fork." << endl
;
435 // Spawn the subprocess
439 signal(SIGPIPE
,SIG_DFL
);
440 signal(SIGQUIT
,SIG_DFL
);
441 signal(SIGINT
,SIG_DFL
);
442 signal(SIGWINCH
,SIG_DFL
);
443 signal(SIGCONT
,SIG_DFL
);
444 signal(SIGTSTP
,SIG_DFL
);
447 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
448 if (Opts
!= 0 && Opts
->Child
!= 0)
451 for (; Opts
!= 0; Opts
= Opts
->Next
)
453 if (Opts
->Value
.empty() == true)
455 int fd
= atoi(Opts
->Value
.c_str());
460 // Close all of our FDs - just in case
461 for (int K
= 3; K
!= 40; K
++)
463 if(KeepFDs
.find(K
) == KeepFDs
.end())
464 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
471 // ExecWait - Fancy waitpid /*{{{*/
472 // ---------------------------------------------------------------------
473 /* Waits for the given sub process. If Reap is set then no errors are
474 generated. Otherwise a failed subprocess will generate a proper descriptive
476 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
481 // Wait and collect the error code
483 while (waitpid(Pid
,&Status
,0) != Pid
)
491 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
495 // Check for an error code.
496 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
500 if (WIFSIGNALED(Status
) != 0)
502 if( WTERMSIG(Status
) == SIGSEGV
)
503 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
505 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
508 if (WIFEXITED(Status
) != 0)
509 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
511 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
518 // FileFd::Open - Open a file /*{{{*/
519 // ---------------------------------------------------------------------
520 /* The most commonly used open mode combinations are given with Mode */
521 bool FileFd::Open(string FileName
,OpenMode Mode
, unsigned long Perms
)
528 iFd
= open(FileName
.c_str(),O_RDONLY
);
534 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
535 unlink(FileName
.c_str());
536 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,Perms
);
541 iFd
= open(FileName
.c_str(),O_RDWR
);
545 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
,Perms
);
549 unlink(FileName
.c_str());
550 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_EXCL
,Perms
);
555 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
557 this->FileName
= FileName
;
558 SetCloseExec(iFd
,true);
562 // FileFd::~File - Closes the file /*{{{*/
563 // ---------------------------------------------------------------------
564 /* If the proper modes are selected then we close the Fd and possibly
565 unlink the file on error. */
571 // FileFd::Read - Read a bit of the file /*{{{*/
572 // ---------------------------------------------------------------------
573 /* We are carefull to handle interruption by a signal while reading
575 bool FileFd::Read(void *To
,unsigned long Size
,unsigned long *Actual
)
584 Res
= read(iFd
,To
,Size
);
585 if (Res
< 0 && errno
== EINTR
)
590 return _error
->Errno("read",_("Read error"));
593 To
= (char *)To
+ Res
;
598 while (Res
> 0 && Size
> 0);
611 return _error
->Error(_("read, still have %lu to read but none left"),Size
);
614 // FileFd::Write - Write to the file /*{{{*/
615 // ---------------------------------------------------------------------
617 bool FileFd::Write(const void *From
,unsigned long Size
)
623 Res
= write(iFd
,From
,Size
);
624 if (Res
< 0 && errno
== EINTR
)
629 return _error
->Errno("write",_("Write error"));
632 From
= (char *)From
+ Res
;
635 while (Res
> 0 && Size
> 0);
641 return _error
->Error(_("write, still have %lu to write but couldn't"),Size
);
644 // FileFd::Seek - Seek in the file /*{{{*/
645 // ---------------------------------------------------------------------
647 bool FileFd::Seek(unsigned long To
)
649 if (lseek(iFd
,To
,SEEK_SET
) != (signed)To
)
652 return _error
->Error("Unable to seek to %lu",To
);
658 // FileFd::Skip - Seek in the file /*{{{*/
659 // ---------------------------------------------------------------------
661 bool FileFd::Skip(unsigned long Over
)
663 if (lseek(iFd
,Over
,SEEK_CUR
) < 0)
666 return _error
->Error("Unable to seek ahead %lu",Over
);
672 // FileFd::Truncate - Truncate the file /*{{{*/
673 // ---------------------------------------------------------------------
675 bool FileFd::Truncate(unsigned long To
)
677 if (ftruncate(iFd
,To
) != 0)
680 return _error
->Error("Unable to truncate to %lu",To
);
686 // FileFd::Tell - Current seek position /*{{{*/
687 // ---------------------------------------------------------------------
689 unsigned long FileFd::Tell()
691 off_t Res
= lseek(iFd
,0,SEEK_CUR
);
692 if (Res
== (off_t
)-1)
693 _error
->Errno("lseek","Failed to determine the current file position");
697 // FileFd::Size - Return the size of the file /*{{{*/
698 // ---------------------------------------------------------------------
700 unsigned long FileFd::Size()
703 if (fstat(iFd
,&Buf
) != 0)
704 return _error
->Errno("fstat","Unable to determine the file size");
708 // FileFd::Close - Close the file if the close flag is set /*{{{*/
709 // ---------------------------------------------------------------------
714 if ((Flags
& AutoClose
) == AutoClose
)
715 if (iFd
>= 0 && close(iFd
) != 0)
716 Res
&= _error
->Errno("close",_("Problem closing the file"));
719 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
720 FileName
.empty() == false)
721 if (unlink(FileName
.c_str()) != 0)
722 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file"));
726 // FileFd::Sync - Sync the file /*{{{*/
727 // ---------------------------------------------------------------------
731 #ifdef _POSIX_SYNCHRONIZED_IO
733 return _error
->Errno("sync",_("Problem syncing the file"));