]>
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
)
207 std::vector
<string
> List
;
208 DIR *D
= opendir(Dir
.c_str());
211 _error
->Errno("opendir",_("Unable to read %s"),Dir
.c_str());
215 for (struct dirent
*Ent
= readdir(D
); Ent
!= 0; Ent
= readdir(D
))
217 if (Ent
->d_name
[0] == '.')
220 if (Ext
.empty() == false && flExtension(Ent
->d_name
) != Ext
)
223 // Skip bad file names ala run-parts
224 const char *C
= Ent
->d_name
;
226 if (isalpha(*C
) == 0 && isdigit(*C
) == 0
227 && *C
!= '_' && *C
!= '-' && *C
!= '.')
233 // Make sure it is a file and not something else
234 string
const File
= flCombine(Dir
,Ent
->d_name
);
236 if (stat(File
.c_str(),&St
) != 0 || S_ISREG(St
.st_mode
) == 0)
239 List
.push_back(File
);
243 if (SortList
== true)
244 std::sort(List
.begin(),List
.end());
248 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
249 // ---------------------------------------------------------------------
250 /* We return / on failure. */
253 // Stash the current dir.
256 if (getcwd(S
,sizeof(S
)-2) == 0)
258 unsigned int Len
= strlen(S
);
264 // flNotDir - Strip the directory from the filename /*{{{*/
265 // ---------------------------------------------------------------------
267 string
flNotDir(string File
)
269 string::size_type Res
= File
.rfind('/');
270 if (Res
== string::npos
)
273 return string(File
,Res
,Res
- File
.length());
276 // flNotFile - Strip the file from the directory name /*{{{*/
277 // ---------------------------------------------------------------------
278 /* Result ends in a / */
279 string
flNotFile(string File
)
281 string::size_type Res
= File
.rfind('/');
282 if (Res
== string::npos
)
285 return string(File
,0,Res
);
288 // flExtension - Return the extension for the file /*{{{*/
289 // ---------------------------------------------------------------------
291 string
flExtension(string File
)
293 string::size_type Res
= File
.rfind('.');
294 if (Res
== string::npos
)
297 return string(File
,Res
,Res
- File
.length());
300 // flNoLink - If file is a symlink then deref it /*{{{*/
301 // ---------------------------------------------------------------------
302 /* If the name is not a link then the returned path is the input. */
303 string
flNoLink(string File
)
306 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
308 if (stat(File
.c_str(),&St
) != 0)
311 /* Loop resolving the link. There is no need to limit the number of
312 loops because the stat call above ensures that the symlink is not
320 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
321 (unsigned)Res
>= sizeof(Buffer
))
324 // Append or replace the previous path
326 if (Buffer
[0] == '/')
329 NFile
= flNotFile(NFile
) + Buffer
;
331 // See if we are done
332 if (lstat(NFile
.c_str(),&St
) != 0)
334 if (S_ISLNK(St
.st_mode
) == 0)
339 // flCombine - Combine a file and a directory /*{{{*/
340 // ---------------------------------------------------------------------
341 /* If the file is an absolute path then it is just returned, otherwise
342 the directory is pre-pended to it. */
343 string
flCombine(string Dir
,string File
)
345 if (File
.empty() == true)
348 if (File
[0] == '/' || Dir
.empty() == true)
350 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
352 if (Dir
[Dir
.length()-1] == '/')
354 return Dir
+ '/' + File
;
357 // SetCloseExec - Set the close on exec flag /*{{{*/
358 // ---------------------------------------------------------------------
360 void SetCloseExec(int Fd
,bool Close
)
362 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
364 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
369 // SetNonBlock - Set the nonblocking flag /*{{{*/
370 // ---------------------------------------------------------------------
372 void SetNonBlock(int Fd
,bool Block
)
374 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
375 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
377 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
382 // WaitFd - Wait for a FD to become readable /*{{{*/
383 // ---------------------------------------------------------------------
384 /* This waits for a FD to become readable using select. It is useful for
385 applications making use of non-blocking sockets. The timeout is
387 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
400 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
402 while (Res
< 0 && errno
== EINTR
);
412 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
414 while (Res
< 0 && errno
== EINTR
);
423 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
424 // ---------------------------------------------------------------------
425 /* This is used if you want to cleanse the environment for the forked
426 child, it fixes up the important signals and nukes all of the fds,
427 otherwise acts like normal fork. */
430 // Fork off the process
431 pid_t Process
= fork();
434 cerr
<< "FATAL -> Failed to fork." << endl
;
438 // Spawn the subprocess
442 signal(SIGPIPE
,SIG_DFL
);
443 signal(SIGQUIT
,SIG_DFL
);
444 signal(SIGINT
,SIG_DFL
);
445 signal(SIGWINCH
,SIG_DFL
);
446 signal(SIGCONT
,SIG_DFL
);
447 signal(SIGTSTP
,SIG_DFL
);
450 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
451 if (Opts
!= 0 && Opts
->Child
!= 0)
454 for (; Opts
!= 0; Opts
= Opts
->Next
)
456 if (Opts
->Value
.empty() == true)
458 int fd
= atoi(Opts
->Value
.c_str());
463 // Close all of our FDs - just in case
464 for (int K
= 3; K
!= 40; K
++)
466 if(KeepFDs
.find(K
) == KeepFDs
.end())
467 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
474 // ExecWait - Fancy waitpid /*{{{*/
475 // ---------------------------------------------------------------------
476 /* Waits for the given sub process. If Reap is set then no errors are
477 generated. Otherwise a failed subprocess will generate a proper descriptive
479 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
484 // Wait and collect the error code
486 while (waitpid(Pid
,&Status
,0) != Pid
)
494 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
498 // Check for an error code.
499 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
503 if (WIFSIGNALED(Status
) != 0)
505 if( WTERMSIG(Status
) == SIGSEGV
)
506 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
508 return _error
->Error(_("Sub-process %s received signal %u."),Name
, WTERMSIG(Status
));
511 if (WIFEXITED(Status
) != 0)
512 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
514 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
521 // FileFd::Open - Open a file /*{{{*/
522 // ---------------------------------------------------------------------
523 /* The most commonly used open mode combinations are given with Mode */
524 bool FileFd::Open(string FileName
,OpenMode Mode
, unsigned long Perms
)
531 iFd
= open(FileName
.c_str(),O_RDONLY
);
537 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
538 unlink(FileName
.c_str());
539 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,Perms
);
544 iFd
= open(FileName
.c_str(),O_RDWR
);
548 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
,Perms
);
552 unlink(FileName
.c_str());
553 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_EXCL
,Perms
);
558 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
560 this->FileName
= FileName
;
561 SetCloseExec(iFd
,true);
565 // FileFd::~File - Closes the file /*{{{*/
566 // ---------------------------------------------------------------------
567 /* If the proper modes are selected then we close the Fd and possibly
568 unlink the file on error. */
574 // FileFd::Read - Read a bit of the file /*{{{*/
575 // ---------------------------------------------------------------------
576 /* We are carefull to handle interruption by a signal while reading
578 bool FileFd::Read(void *To
,unsigned long Size
,unsigned long *Actual
)
587 Res
= read(iFd
,To
,Size
);
588 if (Res
< 0 && errno
== EINTR
)
593 return _error
->Errno("read",_("Read error"));
596 To
= (char *)To
+ Res
;
601 while (Res
> 0 && Size
> 0);
614 return _error
->Error(_("read, still have %lu to read but none left"),Size
);
617 // FileFd::Write - Write to the file /*{{{*/
618 // ---------------------------------------------------------------------
620 bool FileFd::Write(const void *From
,unsigned long Size
)
626 Res
= write(iFd
,From
,Size
);
627 if (Res
< 0 && errno
== EINTR
)
632 return _error
->Errno("write",_("Write error"));
635 From
= (char *)From
+ Res
;
638 while (Res
> 0 && Size
> 0);
644 return _error
->Error(_("write, still have %lu to write but couldn't"),Size
);
647 // FileFd::Seek - Seek in the file /*{{{*/
648 // ---------------------------------------------------------------------
650 bool FileFd::Seek(unsigned long To
)
652 if (lseek(iFd
,To
,SEEK_SET
) != (signed)To
)
655 return _error
->Error("Unable to seek to %lu",To
);
661 // FileFd::Skip - Seek in the file /*{{{*/
662 // ---------------------------------------------------------------------
664 bool FileFd::Skip(unsigned long Over
)
666 if (lseek(iFd
,Over
,SEEK_CUR
) < 0)
669 return _error
->Error("Unable to seek ahead %lu",Over
);
675 // FileFd::Truncate - Truncate the file /*{{{*/
676 // ---------------------------------------------------------------------
678 bool FileFd::Truncate(unsigned long To
)
680 if (ftruncate(iFd
,To
) != 0)
683 return _error
->Error("Unable to truncate to %lu",To
);
689 // FileFd::Tell - Current seek position /*{{{*/
690 // ---------------------------------------------------------------------
692 unsigned long FileFd::Tell()
694 off_t Res
= lseek(iFd
,0,SEEK_CUR
);
695 if (Res
== (off_t
)-1)
696 _error
->Errno("lseek","Failed to determine the current file position");
700 // FileFd::Size - Return the size of the file /*{{{*/
701 // ---------------------------------------------------------------------
703 unsigned long FileFd::Size()
706 if (fstat(iFd
,&Buf
) != 0)
707 return _error
->Errno("fstat","Unable to determine the file size");
711 // FileFd::Close - Close the file if the close flag is set /*{{{*/
712 // ---------------------------------------------------------------------
717 if ((Flags
& AutoClose
) == AutoClose
)
718 if (iFd
>= 0 && close(iFd
) != 0)
719 Res
&= _error
->Errno("close",_("Problem closing the file"));
722 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
723 FileName
.empty() == false)
724 if (unlink(FileName
.c_str()) != 0)
725 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file"));
729 // FileFd::Sync - Sync the file /*{{{*/
730 // ---------------------------------------------------------------------
734 #ifdef _POSIX_SYNCHRONIZED_IO
736 return _error
->Errno("sync",_("Problem syncing the file"));