]>
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 This source is placed in the Public Domain, do with it what you will
12 It was originally written by Jason Gunthorpe <jgg@debian.org>.
14 ##################################################################### */
16 // Include Files /*{{{*/
18 #pragma implementation "apt-pkg/fileutl.h"
20 #include <apt-pkg/fileutl.h>
21 #include <apt-pkg/error.h>
22 #include <apt-pkg/sptr.h>
23 #include <apt-pkg/configuration.h>
32 #include <sys/types.h>
42 // CopyFile - Buffered copy of a file /*{{{*/
43 // ---------------------------------------------------------------------
44 /* The caller is expected to set things so that failure causes erasure */
45 bool CopyFile(FileFd
&From
,FileFd
&To
)
47 if (From
.IsOpen() == false || To
.IsOpen() == false)
50 // Buffered copy between fds
51 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
52 unsigned long Size
= From
.Size();
55 unsigned long ToRead
= Size
;
59 if (From
.Read(Buf
,ToRead
) == false ||
60 To
.Write(Buf
,ToRead
) == false)
69 // GetLock - Gets a lock file /*{{{*/
70 // ---------------------------------------------------------------------
71 /* This will create an empty file of the given name and lock it. Once this
72 is done all other calls to GetLock in any other process will fail with
73 -1. The return result is the fd of the file, the call should call
74 close at some time. */
75 int GetLock(string File
,bool Errors
)
77 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,0640);
80 // Read only .. cant have locking problems there.
83 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
84 return dup(0); // Need something for the caller to close
88 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
90 // Feh.. We do this to distinguish the lock vs open case..
94 SetCloseExec(FD
,true);
96 // Aquire a write lock
99 fl
.l_whence
= SEEK_SET
;
102 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
106 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
107 return dup(0); // Need something for the caller to close
110 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
121 // FileExists - Check if a file exists /*{{{*/
122 // ---------------------------------------------------------------------
124 bool FileExists(string File
)
127 if (stat(File
.c_str(),&Buf
) != 0)
132 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
133 // ---------------------------------------------------------------------
134 /* We return / on failure. */
137 // Stash the current dir.
140 if (getcwd(S
,sizeof(S
)-2) == 0)
142 unsigned int Len
= strlen(S
);
148 // flNotDir - Strip the directory from the filename /*{{{*/
149 // ---------------------------------------------------------------------
151 string
flNotDir(string File
)
153 string::size_type Res
= File
.rfind('/');
154 if (Res
== string::npos
)
157 return string(File
,Res
,Res
- File
.length());
160 // flNotFile - Strip the file from the directory name /*{{{*/
161 // ---------------------------------------------------------------------
162 /* Result ends in a / */
163 string
flNotFile(string File
)
165 string::size_type Res
= File
.rfind('/');
166 if (Res
== string::npos
)
169 return string(File
,0,Res
);
172 // flExtension - Return the extension for the file /*{{{*/
173 // ---------------------------------------------------------------------
175 string
flExtension(string File
)
177 string::size_type Res
= File
.rfind('.');
178 if (Res
== string::npos
)
181 return string(File
,Res
,Res
- File
.length());
184 // flNoLink - If file is a symlink then deref it /*{{{*/
185 // ---------------------------------------------------------------------
186 /* If the name is not a link then the returned path is the input. */
187 string
flNoLink(string File
)
190 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
192 if (stat(File
.c_str(),&St
) != 0)
195 /* Loop resolving the link. There is no need to limit the number of
196 loops because the stat call above ensures that the symlink is not
204 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
205 (unsigned)Res
>= sizeof(Buffer
))
208 // Append or replace the previous path
210 if (Buffer
[0] == '/')
213 NFile
= flNotFile(NFile
) + Buffer
;
215 // See if we are done
216 if (lstat(NFile
.c_str(),&St
) != 0)
218 if (S_ISLNK(St
.st_mode
) == 0)
223 // flCombine - Combine a file and a directory /*{{{*/
224 // ---------------------------------------------------------------------
225 /* If the file is an absolute path then it is just returned, otherwise
226 the directory is pre-pended to it. */
227 string
flCombine(string Dir
,string File
)
229 if (File
.empty() == true)
232 if (File
[0] == '/' || Dir
.empty() == true)
234 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
236 if (Dir
[Dir
.length()-1] == '/')
238 return Dir
+ '/' + File
;
241 // SetCloseExec - Set the close on exec flag /*{{{*/
242 // ---------------------------------------------------------------------
244 void SetCloseExec(int Fd
,bool Close
)
246 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
248 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
253 // SetNonBlock - Set the nonblocking flag /*{{{*/
254 // ---------------------------------------------------------------------
256 void SetNonBlock(int Fd
,bool Block
)
258 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
259 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
261 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
266 // WaitFd - Wait for a FD to become readable /*{{{*/
267 // ---------------------------------------------------------------------
268 /* This waits for a FD to become readable using select. It is useful for
269 applications making use of non-blocking sockets. The timeout is
271 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
284 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
286 while (Res
< 0 && errno
== EINTR
);
296 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
298 while (Res
< 0 && errno
== EINTR
);
307 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
308 // ---------------------------------------------------------------------
309 /* This is used if you want to cleanse the environment for the forked
310 child, it fixes up the important signals and nukes all of the fds,
311 otherwise acts like normal fork. */
314 // Fork off the process
315 pid_t Process
= fork();
318 cerr
<< "FATAL -> Failed to fork." << endl
;
322 // Spawn the subprocess
326 signal(SIGPIPE
,SIG_DFL
);
327 signal(SIGQUIT
,SIG_DFL
);
328 signal(SIGINT
,SIG_DFL
);
329 signal(SIGWINCH
,SIG_DFL
);
330 signal(SIGCONT
,SIG_DFL
);
331 signal(SIGTSTP
,SIG_DFL
);
334 Configuration::Item
const *Opts
= _config
->Tree("APT::Keep-Fds");
335 if (Opts
!= 0 && Opts
->Child
!= 0)
338 for (; Opts
!= 0; Opts
= Opts
->Next
)
340 if (Opts
->Value
.empty() == true)
342 int fd
= atoi(Opts
->Value
.c_str());
347 // Close all of our FDs - just in case
348 for (int K
= 3; K
!= 40; K
++)
350 if(KeepFDs
.find(K
) == KeepFDs
.end())
351 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
358 // ExecWait - Fancy waitpid /*{{{*/
359 // ---------------------------------------------------------------------
360 /* Waits for the given sub process. If Reap is set then no errors are
361 generated. Otherwise a failed subprocess will generate a proper descriptive
363 bool ExecWait(pid_t Pid
,const char *Name
,bool Reap
)
368 // Wait and collect the error code
370 while (waitpid(Pid
,&Status
,0) != Pid
)
378 return _error
->Error(_("Waited for %s but it wasn't there"),Name
);
382 // Check for an error code.
383 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
387 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
388 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
390 if (WIFEXITED(Status
) != 0)
391 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
393 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
400 // FileFd::Open - Open a file /*{{{*/
401 // ---------------------------------------------------------------------
402 /* The most commonly used open mode combinations are given with Mode */
403 bool FileFd::Open(string FileName
,OpenMode Mode
, unsigned long Perms
)
410 iFd
= open(FileName
.c_str(),O_RDONLY
);
416 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
417 unlink(FileName
.c_str());
418 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,Perms
);
423 iFd
= open(FileName
.c_str(),O_RDWR
);
427 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
,Perms
);
431 unlink(FileName
.c_str());
432 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_EXCL
,Perms
);
437 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
439 this->FileName
= FileName
;
440 SetCloseExec(iFd
,true);
444 // FileFd::~File - Closes the file /*{{{*/
445 // ---------------------------------------------------------------------
446 /* If the proper modes are selected then we close the Fd and possibly
447 unlink the file on error. */
453 // FileFd::Read - Read a bit of the file /*{{{*/
454 // ---------------------------------------------------------------------
455 /* We are carefull to handle interruption by a signal while reading
457 bool FileFd::Read(void *To
,unsigned long Size
,unsigned long *Actual
)
466 Res
= read(iFd
,To
,Size
);
467 if (Res
< 0 && errno
== EINTR
)
472 return _error
->Errno("read",_("Read error"));
475 To
= (char *)To
+ Res
;
480 while (Res
> 0 && Size
> 0);
493 return _error
->Error(_("read, still have %lu to read but none left"),Size
);
496 // FileFd::Write - Write to the file /*{{{*/
497 // ---------------------------------------------------------------------
499 bool FileFd::Write(const void *From
,unsigned long Size
)
505 Res
= write(iFd
,From
,Size
);
506 if (Res
< 0 && errno
== EINTR
)
511 return _error
->Errno("write",_("Write error"));
514 From
= (char *)From
+ Res
;
517 while (Res
> 0 && Size
> 0);
523 return _error
->Error(_("write, still have %lu to write but couldn't"),Size
);
526 // FileFd::Seek - Seek in the file /*{{{*/
527 // ---------------------------------------------------------------------
529 bool FileFd::Seek(unsigned long To
)
531 if (lseek(iFd
,To
,SEEK_SET
) != (signed)To
)
534 return _error
->Error("Unable to seek to %lu",To
);
540 // FileFd::Skip - Seek in the file /*{{{*/
541 // ---------------------------------------------------------------------
543 bool FileFd::Skip(unsigned long Over
)
545 if (lseek(iFd
,Over
,SEEK_CUR
) < 0)
548 return _error
->Error("Unable to seek ahead %lu",Over
);
554 // FileFd::Truncate - Truncate the file /*{{{*/
555 // ---------------------------------------------------------------------
557 bool FileFd::Truncate(unsigned long To
)
559 if (ftruncate(iFd
,To
) != 0)
562 return _error
->Error("Unable to truncate to %lu",To
);
568 // FileFd::Tell - Current seek position /*{{{*/
569 // ---------------------------------------------------------------------
571 unsigned long FileFd::Tell()
573 off_t Res
= lseek(iFd
,0,SEEK_CUR
);
574 if (Res
== (off_t
)-1)
575 _error
->Errno("lseek","Failed to determine the current file position");
579 // FileFd::Size - Return the size of the file /*{{{*/
580 // ---------------------------------------------------------------------
582 unsigned long FileFd::Size()
585 if (fstat(iFd
,&Buf
) != 0)
586 return _error
->Errno("fstat","Unable to determine the file size");
590 // FileFd::Close - Close the file if the close flag is set /*{{{*/
591 // ---------------------------------------------------------------------
596 if ((Flags
& AutoClose
) == AutoClose
)
597 if (iFd
>= 0 && close(iFd
) != 0)
598 Res
&= _error
->Errno("close",_("Problem closing the file"));
601 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
602 FileName
.empty() == false)
603 if (unlink(FileName
.c_str()) != 0)
604 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file"));
608 // FileFd::Sync - Sync the file /*{{{*/
609 // ---------------------------------------------------------------------
613 #ifdef _POSIX_SYNCHRONIZED_IO
615 return _error
->Errno("sync",_("Problem syncing the file"));