]>
git.saurik.com Git - apt.git/blob - apt-pkg/contrib/fileutl.cc
1 // -*- mode: cpp; mode: fold -*-
3 // $Id: fileutl.cc,v 1.35 2001/02/20 07:03:17 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.
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>
29 #include <sys/types.h>
36 // CopyFile - Buffered copy of a file /*{{{*/
37 // ---------------------------------------------------------------------
38 /* The caller is expected to set things so that failure causes erasure */
39 bool CopyFile(FileFd
&From
,FileFd
&To
)
41 if (From
.IsOpen() == false || To
.IsOpen() == false)
44 // Buffered copy between fds
45 SPtrArray
<unsigned char> Buf
= new unsigned char[64000];
46 unsigned long Size
= From
.Size();
49 unsigned long ToRead
= Size
;
53 if (From
.Read(Buf
,ToRead
) == false ||
54 To
.Write(Buf
,ToRead
) == false)
63 // GetLock - Gets a lock file /*{{{*/
64 // ---------------------------------------------------------------------
65 /* This will create an empty file of the given name and lock it. Once this
66 is done all other calls to GetLock in any other process will fail with
67 -1. The return result is the fd of the file, the call should call
68 close at some time. */
69 int GetLock(string File
,bool Errors
)
71 int FD
= open(File
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,0640);
74 // Read only .. cant have locking problems there.
77 _error
->Warning(_("Not using locking for read only lock file %s"),File
.c_str());
78 return dup(0); // Need something for the caller to close
82 _error
->Errno("open",_("Could not open lock file %s"),File
.c_str());
84 // Feh.. We do this to distinguish the lock vs open case..
88 SetCloseExec(FD
,true);
90 // Aquire a write lock
93 fl
.l_whence
= SEEK_SET
;
96 if (fcntl(FD
,F_SETLK
,&fl
) == -1)
100 _error
->Warning(_("Not using locking for nfs mounted lock file %s"),File
.c_str());
101 return dup(0); // Need something for the caller to close
104 _error
->Errno("open",_("Could not get lock %s"),File
.c_str());
115 // FileExists - Check if a file exists /*{{{*/
116 // ---------------------------------------------------------------------
118 bool FileExists(string File
)
121 if (stat(File
.c_str(),&Buf
) != 0)
126 // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
127 // ---------------------------------------------------------------------
128 /* We return / on failure. */
131 // Stash the current dir.
134 if (getcwd(S
,sizeof(S
)-2) == 0)
136 unsigned int Len
= strlen(S
);
142 // flNotDir - Strip the directory from the filename /*{{{*/
143 // ---------------------------------------------------------------------
145 string
flNotDir(string File
)
147 string::size_type Res
= File
.rfind('/');
148 if (Res
== string::npos
)
151 return string(File
,Res
,Res
- File
.length());
154 // flNotFile - Strip the file from the directory name /*{{{*/
155 // ---------------------------------------------------------------------
157 string
flNotFile(string File
)
159 string::size_type Res
= File
.rfind('/');
160 if (Res
== string::npos
)
163 return string(File
,0,Res
);
166 // flExtension - Return the extension for the file /*{{{*/
167 // ---------------------------------------------------------------------
169 string
flExtension(string File
)
171 string::size_type Res
= File
.rfind('.');
172 if (Res
== string::npos
)
175 return string(File
,Res
,Res
- File
.length());
178 // flNoLink - If file is a symlink then deref it /*{{{*/
179 // ---------------------------------------------------------------------
180 /* If the name is not a link then the returned path is the input. */
181 string
flNoLink(string File
)
184 if (lstat(File
.c_str(),&St
) != 0 || S_ISLNK(St
.st_mode
) == 0)
186 if (stat(File
.c_str(),&St
) != 0)
189 /* Loop resolving the link. There is no need to limit the number of
190 loops because the stat call above ensures that the symlink is not
198 if ((Res
= readlink(NFile
.c_str(),Buffer
,sizeof(Buffer
))) <= 0 ||
199 (unsigned)Res
>= sizeof(Buffer
))
202 // Append or replace the previous path
204 if (Buffer
[0] == '/')
207 NFile
= flNotFile(NFile
) + Buffer
;
209 // See if we are done
210 if (lstat(NFile
.c_str(),&St
) != 0)
212 if (S_ISLNK(St
.st_mode
) == 0)
217 // flCombine - Combine a file and a directory /*{{{*/
218 // ---------------------------------------------------------------------
219 /* If the file is an absolute path then it is just returned, otherwise
220 the directory is pre-pended to it. */
221 string
flCombine(string Dir
,string File
)
223 if (File
.empty() == true)
226 if (File
[0] == '/' || Dir
.empty() == true)
228 if (File
.length() >= 2 && File
[0] == '.' && File
[1] == '/')
230 if (Dir
[Dir
.length()-1] == '/')
232 return Dir
+ '/' + File
;
235 // SetCloseExec - Set the close on exec flag /*{{{*/
236 // ---------------------------------------------------------------------
238 void SetCloseExec(int Fd
,bool Close
)
240 if (fcntl(Fd
,F_SETFD
,(Close
== false)?0:FD_CLOEXEC
) != 0)
242 cerr
<< "FATAL -> Could not set close on exec " << strerror(errno
) << endl
;
247 // SetNonBlock - Set the nonblocking flag /*{{{*/
248 // ---------------------------------------------------------------------
250 void SetNonBlock(int Fd
,bool Block
)
252 int Flags
= fcntl(Fd
,F_GETFL
) & (~O_NONBLOCK
);
253 if (fcntl(Fd
,F_SETFL
,Flags
| ((Block
== false)?0:O_NONBLOCK
)) != 0)
255 cerr
<< "FATAL -> Could not set non-blocking flag " << strerror(errno
) << endl
;
260 // WaitFd - Wait for a FD to become readable /*{{{*/
261 // ---------------------------------------------------------------------
262 /* This waits for a FD to become readable using select. It is useful for
263 applications making use of non-blocking sockets. The timeout is
265 bool WaitFd(int Fd
,bool write
,unsigned long timeout
)
278 Res
= select(Fd
+1,0,&Set
,0,(timeout
!= 0?&tv
:0));
280 while (Res
< 0 && errno
== EINTR
);
290 Res
= select(Fd
+1,&Set
,0,0,(timeout
!= 0?&tv
:0));
292 while (Res
< 0 && errno
== EINTR
);
301 // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
302 // ---------------------------------------------------------------------
303 /* This is used if you want to cleanse the environment for the forked
304 child, it fixes up the important signals and nukes all of the fds,
305 otherwise acts like normal fork. */
308 // Fork off the process
309 pid_t Process
= fork();
312 cerr
<< "FATAL -> Failed to fork." << endl
;
316 // Spawn the subprocess
320 signal(SIGPIPE
,SIG_DFL
);
321 signal(SIGQUIT
,SIG_DFL
);
322 signal(SIGINT
,SIG_DFL
);
323 signal(SIGWINCH
,SIG_DFL
);
324 signal(SIGCONT
,SIG_DFL
);
325 signal(SIGTSTP
,SIG_DFL
);
327 // Close all of our FDs - just in case
328 for (int K
= 3; K
!= 40; K
++)
329 fcntl(K
,F_SETFD
,FD_CLOEXEC
);
335 // ExecWait - Fancy waitpid /*{{{*/
336 // ---------------------------------------------------------------------
337 /* Waits for the given sub process. If Reap is set the no errors are
338 generated. Otherwise a failed subprocess will generate a proper descriptive
340 bool ExecWait(int Pid
,const char *Name
,bool Reap
)
345 // Wait and collect the error code
347 while (waitpid(Pid
,&Status
,0) != Pid
)
355 return _error
->Error(_("Waited, for %s but it wasn't there"),Name
);
359 // Check for an error code.
360 if (WIFEXITED(Status
) == 0 || WEXITSTATUS(Status
) != 0)
364 if (WIFSIGNALED(Status
) != 0 && WTERMSIG(Status
) == SIGSEGV
)
365 return _error
->Error(_("Sub-process %s received a segmentation fault."),Name
);
367 if (WIFEXITED(Status
) != 0)
368 return _error
->Error(_("Sub-process %s returned an error code (%u)"),Name
,WEXITSTATUS(Status
));
370 return _error
->Error(_("Sub-process %s exited unexpectedly"),Name
);
377 // FileFd::Open - Open a file /*{{{*/
378 // ---------------------------------------------------------------------
379 /* The most commonly used open mode combinations are given with Mode */
380 bool FileFd::Open(string FileName
,OpenMode Mode
, unsigned long Perms
)
387 iFd
= open(FileName
.c_str(),O_RDONLY
);
393 if (lstat(FileName
.c_str(),&Buf
) == 0 && S_ISLNK(Buf
.st_mode
))
394 unlink(FileName
.c_str());
395 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
| O_TRUNC
,Perms
);
400 iFd
= open(FileName
.c_str(),O_RDWR
);
404 iFd
= open(FileName
.c_str(),O_RDWR
| O_CREAT
,Perms
);
409 return _error
->Errno("open",_("Could not open file %s"),FileName
.c_str());
411 this->FileName
= FileName
;
412 SetCloseExec(iFd
,true);
416 // FileFd::~File - Closes the file /*{{{*/
417 // ---------------------------------------------------------------------
418 /* If the proper modes are selected then we close the Fd and possibly
419 unlink the file on error. */
425 // FileFd::Read - Read a bit of the file /*{{{*/
426 // ---------------------------------------------------------------------
427 /* We are carefull to handle interruption by a signal while reading
429 bool FileFd::Read(void *To
,unsigned long Size
,bool AllowEof
)
435 Res
= read(iFd
,To
,Size
);
436 if (Res
< 0 && errno
== EINTR
)
441 return _error
->Errno("read",_("Read error"));
444 To
= (char *)To
+ Res
;
447 while (Res
> 0 && Size
> 0);
453 if (AllowEof
== true)
460 return _error
->Error(_("read, still have %lu to read but none left"),Size
);
463 // FileFd::Write - Write to the file /*{{{*/
464 // ---------------------------------------------------------------------
466 bool FileFd::Write(const void *From
,unsigned long Size
)
472 Res
= write(iFd
,From
,Size
);
473 if (Res
< 0 && errno
== EINTR
)
478 return _error
->Errno("write",_("Write error"));
481 From
= (char *)From
+ Res
;
484 while (Res
> 0 && Size
> 0);
490 return _error
->Error(_("write, still have %lu to write but couldn't"),Size
);
493 // FileFd::Seek - Seek in the file /*{{{*/
494 // ---------------------------------------------------------------------
496 bool FileFd::Seek(unsigned long To
)
498 if (lseek(iFd
,To
,SEEK_SET
) != (signed)To
)
501 return _error
->Error("Unable to seek to %lu",To
);
507 // FileFd::Skip - Seek in the file /*{{{*/
508 // ---------------------------------------------------------------------
510 bool FileFd::Skip(unsigned long Over
)
512 if (lseek(iFd
,Over
,SEEK_CUR
) < 0)
515 return _error
->Error("Unable to seek ahead %lu",Over
);
521 // FileFd::Truncate - Truncate the file /*{{{*/
522 // ---------------------------------------------------------------------
524 bool FileFd::Truncate(unsigned long To
)
526 if (ftruncate(iFd
,To
) != 0)
529 return _error
->Error("Unable to truncate to %lu",To
);
535 // FileFd::Tell - Current seek position /*{{{*/
536 // ---------------------------------------------------------------------
538 unsigned long FileFd::Tell()
540 off_t Res
= lseek(iFd
,0,SEEK_CUR
);
541 if (Res
== (off_t
)-1)
542 _error
->Errno("lseek","Failed to determine the current file position");
546 // FileFd::Size - Return the size of the file /*{{{*/
547 // ---------------------------------------------------------------------
549 unsigned long FileFd::Size()
552 if (fstat(iFd
,&Buf
) != 0)
553 return _error
->Errno("fstat","Unable to determine the file size");
557 // FileFd::Close - Close the file if the close flag is set /*{{{*/
558 // ---------------------------------------------------------------------
563 if ((Flags
& AutoClose
) == AutoClose
)
564 if (iFd
>= 0 && close(iFd
) != 0)
565 Res
&= _error
->Errno("close",_("Problem closing the file"));
568 if ((Flags
& Fail
) == Fail
&& (Flags
& DelOnFail
) == DelOnFail
&&
569 FileName
.empty() == false)
570 if (unlink(FileName
.c_str()) != 0)
571 Res
&= _error
->WarningE("unlnk",_("Problem unlinking the file"));
575 // FileFd::Sync - Sync the file /*{{{*/
576 // ---------------------------------------------------------------------
580 #ifdef _POSIX_SYNCHRONIZED_IO
582 return _error
->Errno("sync",_("Problem syncing the file"));