switch from std::set to std::vector as it is way more simple, a bit
[ntk/apt.git] / apt-pkg / contrib / fileutl.cc
CommitLineData
578bfd0a
AL
1// -*- mode: cpp; mode: fold -*-
2// Description /*{{{*/
7da2b375 3// $Id: fileutl.cc,v 1.42 2002/09/14 05:29:22 jgg Exp $
578bfd0a
AL
4/* ######################################################################
5
6 File Utilities
7
8 CopyFile - Buffered copy of a single file
9 GetLock - dpkg compatible lock file manipulation (fcntl)
10
614adaa0
MV
11 Most of this source is placed in the Public Domain, do with it what
12 you will
7da2b375 13 It was originally written by Jason Gunthorpe <jgg@debian.org>.
578bfd0a 14
614adaa0
MV
15 The exception is RunScripts() it is under the GPLv2
16
578bfd0a
AL
17 ##################################################################### */
18 /*}}}*/
19// Include Files /*{{{*/
094a497d 20#include <apt-pkg/fileutl.h>
1cd1c398 21#include <apt-pkg/strutl.h>
094a497d 22#include <apt-pkg/error.h>
b2e465d6 23#include <apt-pkg/sptr.h>
75ef8f14 24#include <apt-pkg/configuration.h>
b2e465d6
AL
25
26#include <apti18n.h>
578bfd0a 27
152ab79e 28#include <cstdlib>
4f333a8b 29#include <cstring>
3010fb0e 30#include <cstdio>
4f333a8b 31
4d055c05 32#include <iostream>
578bfd0a 33#include <unistd.h>
2c206aa4 34#include <fcntl.h>
578bfd0a 35#include <sys/stat.h>
578bfd0a 36#include <sys/types.h>
cc2313b7 37#include <sys/time.h>
1ae93c94 38#include <sys/wait.h>
46e39c8e 39#include <dirent.h>
54676e1a 40#include <signal.h>
65a1e968 41#include <errno.h>
75ef8f14 42#include <set>
46e39c8e 43#include <algorithm>
578bfd0a
AL
44 /*}}}*/
45
4d055c05
AL
46using namespace std;
47
614adaa0
MV
48// RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
49// ---------------------------------------------------------------------
50/* */
51bool RunScripts(const char *Cnf)
52{
53 Configuration::Item const *Opts = _config->Tree(Cnf);
54 if (Opts == 0 || Opts->Child == 0)
55 return true;
56 Opts = Opts->Child;
57
58 // Fork for running the system calls
59 pid_t Child = ExecFork();
60
61 // This is the child
62 if (Child == 0)
63 {
64 if (chdir("/tmp/") != 0)
65 _exit(100);
66
67 unsigned int Count = 1;
68 for (; Opts != 0; Opts = Opts->Next, Count++)
69 {
70 if (Opts->Value.empty() == true)
71 continue;
72
73 if (system(Opts->Value.c_str()) != 0)
74 _exit(100+Count);
75 }
76 _exit(0);
77 }
78
79 // Wait for the child
80 int Status = 0;
81 while (waitpid(Child,&Status,0) != Child)
82 {
83 if (errno == EINTR)
84 continue;
85 return _error->Errno("waitpid","Couldn't wait for subprocess");
86 }
87
88 // Restore sig int/quit
89 signal(SIGQUIT,SIG_DFL);
90 signal(SIGINT,SIG_DFL);
91
92 // Check for an error code.
93 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
94 {
95 unsigned int Count = WEXITSTATUS(Status);
96 if (Count > 100)
97 {
98 Count -= 100;
99 for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
100 _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
101 }
102
103 return _error->Error("Sub-process returned an error code");
104 }
105
106 return true;
107}
108 /*}}}*/
109
578bfd0a
AL
110// CopyFile - Buffered copy of a file /*{{{*/
111// ---------------------------------------------------------------------
112/* The caller is expected to set things so that failure causes erasure */
8b89e57f 113bool CopyFile(FileFd &From,FileFd &To)
578bfd0a
AL
114{
115 if (From.IsOpen() == false || To.IsOpen() == false)
116 return false;
117
118 // Buffered copy between fds
b2e465d6 119 SPtrArray<unsigned char> Buf = new unsigned char[64000];
b0db36b1
AL
120 unsigned long Size = From.Size();
121 while (Size != 0)
578bfd0a 122 {
b0db36b1
AL
123 unsigned long ToRead = Size;
124 if (Size > 64000)
125 ToRead = 64000;
126
4a6d5862 127 if (From.Read(Buf,ToRead) == false ||
b0db36b1 128 To.Write(Buf,ToRead) == false)
578bfd0a 129 return false;
b0db36b1
AL
130
131 Size -= ToRead;
578bfd0a
AL
132 }
133
578bfd0a
AL
134 return true;
135}
136 /*}}}*/
137// GetLock - Gets a lock file /*{{{*/
138// ---------------------------------------------------------------------
139/* This will create an empty file of the given name and lock it. Once this
140 is done all other calls to GetLock in any other process will fail with
141 -1. The return result is the fd of the file, the call should call
142 close at some time. */
143int GetLock(string File,bool Errors)
144{
f659b39a
OS
145 // GetLock() is used in aptitude on directories with public-write access
146 // Use O_NOFOLLOW here to prevent symlink traversal attacks
147 int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
578bfd0a
AL
148 if (FD < 0)
149 {
b2e465d6
AL
150 // Read only .. cant have locking problems there.
151 if (errno == EROFS)
152 {
153 _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
154 return dup(0); // Need something for the caller to close
155 }
156
578bfd0a 157 if (Errors == true)
b2e465d6
AL
158 _error->Errno("open",_("Could not open lock file %s"),File.c_str());
159
160 // Feh.. We do this to distinguish the lock vs open case..
161 errno = EPERM;
578bfd0a
AL
162 return -1;
163 }
b2e465d6
AL
164 SetCloseExec(FD,true);
165
578bfd0a
AL
166 // Aquire a write lock
167 struct flock fl;
c71bc556
AL
168 fl.l_type = F_WRLCK;
169 fl.l_whence = SEEK_SET;
170 fl.l_start = 0;
171 fl.l_len = 0;
578bfd0a
AL
172 if (fcntl(FD,F_SETLK,&fl) == -1)
173 {
d89df07a
AL
174 if (errno == ENOLCK)
175 {
b2e465d6
AL
176 _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
177 return dup(0); // Need something for the caller to close
d89df07a 178 }
578bfd0a 179 if (Errors == true)
b2e465d6
AL
180 _error->Errno("open",_("Could not get lock %s"),File.c_str());
181
182 int Tmp = errno;
578bfd0a 183 close(FD);
b2e465d6 184 errno = Tmp;
578bfd0a
AL
185 return -1;
186 }
187
188 return FD;
189}
190 /*}}}*/
191// FileExists - Check if a file exists /*{{{*/
192// ---------------------------------------------------------------------
193/* */
194bool FileExists(string File)
195{
196 struct stat Buf;
197 if (stat(File.c_str(),&Buf) != 0)
198 return false;
199 return true;
200}
201 /*}}}*/
1cd1c398
DK
202// DirectoryExists - Check if a directory exists and is really one /*{{{*/
203// ---------------------------------------------------------------------
204/* */
205bool DirectoryExists(string const &Path)
206{
207 struct stat Buf;
208 if (stat(Path.c_str(),&Buf) != 0)
209 return false;
210 return ((Buf.st_mode & S_IFDIR) != 0);
211}
212 /*}}}*/
213// CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
214// ---------------------------------------------------------------------
215/* This method will create all directories needed for path in good old
216 mkdir -p style but refuses to do this if Parent is not a prefix of
217 this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
218 so it will create apt/archives if /var/cache exists - on the other
219 hand if the parent is /var/lib the creation will fail as this path
220 is not a parent of the path to be generated. */
221bool CreateDirectory(string const &Parent, string const &Path)
222{
223 if (Parent.empty() == true || Path.empty() == true)
224 return false;
225
226 if (DirectoryExists(Path) == true)
227 return true;
228
229 if (DirectoryExists(Parent) == false)
230 return false;
231
232 // we are not going to create directories "into the blue"
233 if (Path.find(Parent, 0) != 0)
234 return false;
235
236 vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
237 string progress = Parent;
238 for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
239 {
240 if (d->empty() == true)
241 continue;
242
243 progress.append("/").append(*d);
244 if (DirectoryExists(progress) == true)
245 continue;
246
247 if (mkdir(progress.c_str(), 0755) != 0)
248 return false;
249 }
250 return true;
251}
252 /*}}}*/
46e39c8e
MV
253// GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
254// ---------------------------------------------------------------------
255/* If an extension is given only files with this extension are included
256 in the returned vector, otherwise every "normal" file is included. */
b39c1859
MV
257std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
258 bool const &SortList, bool const &AllowNoExt)
259{
260 std::vector<string> ext;
261 ext.reserve(2);
262 if (Ext.empty() == false)
263 ext.push_back(Ext);
264 if (AllowNoExt == true && ext.empty() == false)
265 ext.push_back("");
266 return GetListOfFilesInDir(Dir, ext, SortList);
267}
268std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
269 bool const &SortList)
270{
271 // Attention debuggers: need to be set with the environment config file!
272 bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
273 if (Debug == true)
274 {
275 std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
276 if (Ext.empty() == true)
277 std::clog << "\tNO extension" << std::endl;
278 else
279 for (std::vector<string>::const_iterator e = Ext.begin();
280 e != Ext.end(); ++e)
281 std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
282 }
283
46e39c8e 284 std::vector<string> List;
1408e219 285 Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
46e39c8e
MV
286 DIR *D = opendir(Dir.c_str());
287 if (D == 0)
288 {
289 _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
290 return List;
291 }
292
293 for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
294 {
b39c1859 295 // skip "hidden" files
46e39c8e
MV
296 if (Ent->d_name[0] == '.')
297 continue;
298
b39c1859
MV
299 // check for accepted extension:
300 // no extension given -> periods are bad as hell!
301 // extensions given -> "" extension allows no extension
302 if (Ext.empty() == false)
303 {
304 string d_ext = flExtension(Ent->d_name);
305 if (d_ext == Ent->d_name) // no extension
306 {
307 if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
308 {
309 if (Debug == true)
310 std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
1408e219 311 _error->Notice("Ignoring file '%s' in directory '%s' as it has no filename extension", Ent->d_name, Dir.c_str());
b39c1859
MV
312 continue;
313 }
314 }
315 else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
316 {
317 if (Debug == true)
318 std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
1408e219
DK
319 if (SilentIgnore.Match(Ent->d_name) == false)
320 _error->Notice("Ignoring file '%s' in directory '%s' as it has an invalid filename extension", Ent->d_name, Dir.c_str());
b39c1859
MV
321 continue;
322 }
323 }
46e39c8e 324
b39c1859 325 // Skip bad filenames ala run-parts
46e39c8e
MV
326 const char *C = Ent->d_name;
327 for (; *C != 0; ++C)
328 if (isalpha(*C) == 0 && isdigit(*C) == 0
b39c1859
MV
329 && *C != '_' && *C != '-') {
330 // no required extension -> dot is a bad character
331 if (*C == '.' && Ext.empty() == false)
332 continue;
46e39c8e 333 break;
b39c1859 334 }
46e39c8e 335
b39c1859 336 // we don't reach the end of the name -> bad character included
46e39c8e 337 if (*C != 0)
b39c1859
MV
338 {
339 if (Debug == true)
340 std::clog << "Bad file: " << Ent->d_name << " → bad character »"
341 << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
342 continue;
343 }
344
345 // skip filenames which end with a period. These are never valid
346 if (*(C - 1) == '.')
347 {
348 if (Debug == true)
349 std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
46e39c8e 350 continue;
b39c1859 351 }
46e39c8e
MV
352
353 // Make sure it is a file and not something else
354 string const File = flCombine(Dir,Ent->d_name);
355 struct stat St;
356 if (stat(File.c_str(),&St) != 0 || S_ISREG(St.st_mode) == 0)
b39c1859
MV
357 {
358 if (Debug == true)
359 std::clog << "Bad file: " << Ent->d_name << " → stat says not a good file" << std::endl;
46e39c8e 360 continue;
b39c1859 361 }
46e39c8e 362
b39c1859
MV
363 if (Debug == true)
364 std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
46e39c8e
MV
365 List.push_back(File);
366 }
367 closedir(D);
368
369 if (SortList == true)
370 std::sort(List.begin(),List.end());
371 return List;
372}
373 /*}}}*/
578bfd0a
AL
374// SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
375// ---------------------------------------------------------------------
376/* We return / on failure. */
377string SafeGetCWD()
378{
379 // Stash the current dir.
380 char S[300];
381 S[0] = 0;
7f25bdff 382 if (getcwd(S,sizeof(S)-2) == 0)
578bfd0a 383 return "/";
7f25bdff
AL
384 unsigned int Len = strlen(S);
385 S[Len] = '/';
386 S[Len+1] = 0;
578bfd0a
AL
387 return S;
388}
389 /*}}}*/
8ce4327b
AL
390// flNotDir - Strip the directory from the filename /*{{{*/
391// ---------------------------------------------------------------------
392/* */
393string flNotDir(string File)
394{
395 string::size_type Res = File.rfind('/');
396 if (Res == string::npos)
397 return File;
398 Res++;
399 return string(File,Res,Res - File.length());
400}
401 /*}}}*/
d38b7b3d
AL
402// flNotFile - Strip the file from the directory name /*{{{*/
403// ---------------------------------------------------------------------
171c45bc 404/* Result ends in a / */
d38b7b3d
AL
405string flNotFile(string File)
406{
407 string::size_type Res = File.rfind('/');
408 if (Res == string::npos)
171c45bc 409 return "./";
d38b7b3d
AL
410 Res++;
411 return string(File,0,Res);
412}
413 /*}}}*/
b2e465d6
AL
414// flExtension - Return the extension for the file /*{{{*/
415// ---------------------------------------------------------------------
416/* */
417string flExtension(string File)
418{
419 string::size_type Res = File.rfind('.');
420 if (Res == string::npos)
421 return File;
422 Res++;
423 return string(File,Res,Res - File.length());
424}
425 /*}}}*/
421c8d10
AL
426// flNoLink - If file is a symlink then deref it /*{{{*/
427// ---------------------------------------------------------------------
428/* If the name is not a link then the returned path is the input. */
429string flNoLink(string File)
430{
431 struct stat St;
432 if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
433 return File;
434 if (stat(File.c_str(),&St) != 0)
435 return File;
436
437 /* Loop resolving the link. There is no need to limit the number of
438 loops because the stat call above ensures that the symlink is not
439 circular */
440 char Buffer[1024];
441 string NFile = File;
442 while (1)
443 {
444 // Read the link
445 int Res;
446 if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
447 (unsigned)Res >= sizeof(Buffer))
448 return File;
449
450 // Append or replace the previous path
451 Buffer[Res] = 0;
452 if (Buffer[0] == '/')
453 NFile = Buffer;
454 else
455 NFile = flNotFile(NFile) + Buffer;
456
457 // See if we are done
458 if (lstat(NFile.c_str(),&St) != 0)
459 return File;
460 if (S_ISLNK(St.st_mode) == 0)
461 return NFile;
462 }
463}
464 /*}}}*/
b2e465d6
AL
465// flCombine - Combine a file and a directory /*{{{*/
466// ---------------------------------------------------------------------
467/* If the file is an absolute path then it is just returned, otherwise
468 the directory is pre-pended to it. */
469string flCombine(string Dir,string File)
470{
471 if (File.empty() == true)
472 return string();
473
474 if (File[0] == '/' || Dir.empty() == true)
475 return File;
476 if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
477 return File;
478 if (Dir[Dir.length()-1] == '/')
479 return Dir + File;
480 return Dir + '/' + File;
481}
482 /*}}}*/
3b5421b4
AL
483// SetCloseExec - Set the close on exec flag /*{{{*/
484// ---------------------------------------------------------------------
485/* */
486void SetCloseExec(int Fd,bool Close)
487{
488 if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
489 {
490 cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
491 exit(100);
492 }
493}
494 /*}}}*/
495// SetNonBlock - Set the nonblocking flag /*{{{*/
496// ---------------------------------------------------------------------
497/* */
498void SetNonBlock(int Fd,bool Block)
499{
0a8a80e5
AL
500 int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
501 if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
3b5421b4
AL
502 {
503 cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
504 exit(100);
505 }
506}
507 /*}}}*/
508// WaitFd - Wait for a FD to become readable /*{{{*/
509// ---------------------------------------------------------------------
b2e465d6 510/* This waits for a FD to become readable using select. It is useful for
6d5dd02a
AL
511 applications making use of non-blocking sockets. The timeout is
512 in seconds. */
1084d58a 513bool WaitFd(int Fd,bool write,unsigned long timeout)
3b5421b4
AL
514{
515 fd_set Set;
cc2313b7 516 struct timeval tv;
3b5421b4
AL
517 FD_ZERO(&Set);
518 FD_SET(Fd,&Set);
6d5dd02a
AL
519 tv.tv_sec = timeout;
520 tv.tv_usec = 0;
1084d58a 521 if (write == true)
b0db36b1
AL
522 {
523 int Res;
524 do
525 {
526 Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
527 }
528 while (Res < 0 && errno == EINTR);
529
530 if (Res <= 0)
531 return false;
1084d58a
AL
532 }
533 else
534 {
b0db36b1
AL
535 int Res;
536 do
537 {
538 Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
539 }
540 while (Res < 0 && errno == EINTR);
541
542 if (Res <= 0)
543 return false;
cc2313b7 544 }
1084d58a 545
3b5421b4
AL
546 return true;
547}
548 /*}}}*/
54676e1a
AL
549// ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
550// ---------------------------------------------------------------------
551/* This is used if you want to cleanse the environment for the forked
552 child, it fixes up the important signals and nukes all of the fds,
553 otherwise acts like normal fork. */
75ef8f14 554pid_t ExecFork()
54676e1a
AL
555{
556 // Fork off the process
557 pid_t Process = fork();
558 if (Process < 0)
559 {
560 cerr << "FATAL -> Failed to fork." << endl;
561 exit(100);
562 }
563
564 // Spawn the subprocess
565 if (Process == 0)
566 {
567 // Setup the signals
568 signal(SIGPIPE,SIG_DFL);
569 signal(SIGQUIT,SIG_DFL);
570 signal(SIGINT,SIG_DFL);
571 signal(SIGWINCH,SIG_DFL);
572 signal(SIGCONT,SIG_DFL);
573 signal(SIGTSTP,SIG_DFL);
75ef8f14
MV
574
575 set<int> KeepFDs;
576 Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
577 if (Opts != 0 && Opts->Child != 0)
578 {
579 Opts = Opts->Child;
580 for (; Opts != 0; Opts = Opts->Next)
581 {
582 if (Opts->Value.empty() == true)
583 continue;
584 int fd = atoi(Opts->Value.c_str());
585 KeepFDs.insert(fd);
586 }
587 }
588
54676e1a
AL
589 // Close all of our FDs - just in case
590 for (int K = 3; K != 40; K++)
75ef8f14
MV
591 {
592 if(KeepFDs.find(K) == KeepFDs.end())
007dc9e0 593 fcntl(K,F_SETFD,FD_CLOEXEC);
75ef8f14 594 }
54676e1a
AL
595 }
596
597 return Process;
598}
599 /*}}}*/
ddc1d8d0
AL
600// ExecWait - Fancy waitpid /*{{{*/
601// ---------------------------------------------------------------------
2c9a72d1 602/* Waits for the given sub process. If Reap is set then no errors are
ddc1d8d0
AL
603 generated. Otherwise a failed subprocess will generate a proper descriptive
604 message */
3826564e 605bool ExecWait(pid_t Pid,const char *Name,bool Reap)
ddc1d8d0
AL
606{
607 if (Pid <= 1)
608 return true;
609
610 // Wait and collect the error code
611 int Status;
612 while (waitpid(Pid,&Status,0) != Pid)
613 {
614 if (errno == EINTR)
615 continue;
616
617 if (Reap == true)
618 return false;
619
db0db9fe 620 return _error->Error(_("Waited for %s but it wasn't there"),Name);
ddc1d8d0
AL
621 }
622
623
624 // Check for an error code.
625 if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
626 {
627 if (Reap == true)
628 return false;
ab7f4d7c 629 if (WIFSIGNALED(Status) != 0)
40e7fe0e 630 {
ab7f4d7c
MV
631 if( WTERMSIG(Status) == SIGSEGV)
632 return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
633 else
634 return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
40e7fe0e 635 }
ddc1d8d0
AL
636
637 if (WIFEXITED(Status) != 0)
b2e465d6 638 return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
ddc1d8d0 639
b2e465d6 640 return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
ddc1d8d0
AL
641 }
642
643 return true;
644}
645 /*}}}*/
578bfd0a 646
13d87e2e 647// FileFd::Open - Open a file /*{{{*/
578bfd0a
AL
648// ---------------------------------------------------------------------
649/* The most commonly used open mode combinations are given with Mode */
13d87e2e 650bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms)
578bfd0a 651{
13d87e2e 652 Close();
1164783d 653 Flags = AutoClose;
578bfd0a
AL
654 switch (Mode)
655 {
656 case ReadOnly:
657 iFd = open(FileName.c_str(),O_RDONLY);
658 break;
659
660 case WriteEmpty:
50b513a1 661 {
3010fb0e
JAK
662 Flags |= Replace;
663 char *name = strdup((FileName + ".XXXXXX").c_str());
664 TemporaryFileName = string(mktemp(name));
665 iFd = open(TemporaryFileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
666 free(name);
50b513a1
AL
667 break;
668 }
578bfd0a
AL
669
670 case WriteExists:
671 iFd = open(FileName.c_str(),O_RDWR);
672 break;
0a8e3465
AL
673
674 case WriteAny:
675 iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
d38b7b3d 676 break;
f08fcf34
AL
677
678 case WriteTemp:
4decd43c
AL
679 unlink(FileName.c_str());
680 iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
f08fcf34 681 break;
578bfd0a
AL
682 }
683
684 if (iFd < 0)
b2e465d6 685 return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
13d87e2e
AL
686
687 this->FileName = FileName;
688 SetCloseExec(iFd,true);
689 return true;
578bfd0a
AL
690}
691 /*}}}*/
8e06abb2 692// FileFd::~File - Closes the file /*{{{*/
578bfd0a
AL
693// ---------------------------------------------------------------------
694/* If the proper modes are selected then we close the Fd and possibly
695 unlink the file on error. */
8e06abb2 696FileFd::~FileFd()
578bfd0a
AL
697{
698 Close();
699}
700 /*}}}*/
8e06abb2 701// FileFd::Read - Read a bit of the file /*{{{*/
578bfd0a 702// ---------------------------------------------------------------------
b0db36b1
AL
703/* We are carefull to handle interruption by a signal while reading
704 gracefully. */
f604cf55 705bool FileFd::Read(void *To,unsigned long Size,unsigned long *Actual)
578bfd0a 706{
b0db36b1
AL
707 int Res;
708 errno = 0;
f604cf55
AL
709 if (Actual != 0)
710 *Actual = 0;
711
b0db36b1 712 do
578bfd0a 713 {
b0db36b1
AL
714 Res = read(iFd,To,Size);
715 if (Res < 0 && errno == EINTR)
716 continue;
717 if (Res < 0)
718 {
719 Flags |= Fail;
b2e465d6 720 return _error->Errno("read",_("Read error"));
b0db36b1 721 }
578bfd0a 722
b0db36b1
AL
723 To = (char *)To + Res;
724 Size -= Res;
f604cf55
AL
725 if (Actual != 0)
726 *Actual += Res;
b0db36b1
AL
727 }
728 while (Res > 0 && Size > 0);
729
730 if (Size == 0)
731 return true;
732
ddc1d8d0 733 // Eof handling
f604cf55 734 if (Actual != 0)
ddc1d8d0
AL
735 {
736 Flags |= HitEof;
737 return true;
738 }
739
b0db36b1 740 Flags |= Fail;
b2e465d6 741 return _error->Error(_("read, still have %lu to read but none left"),Size);
578bfd0a
AL
742}
743 /*}}}*/
8e06abb2 744// FileFd::Write - Write to the file /*{{{*/
578bfd0a
AL
745// ---------------------------------------------------------------------
746/* */
a05599f1 747bool FileFd::Write(const void *From,unsigned long Size)
578bfd0a 748{
b0db36b1
AL
749 int Res;
750 errno = 0;
751 do
578bfd0a 752 {
b0db36b1
AL
753 Res = write(iFd,From,Size);
754 if (Res < 0 && errno == EINTR)
755 continue;
756 if (Res < 0)
757 {
758 Flags |= Fail;
b2e465d6 759 return _error->Errno("write",_("Write error"));
b0db36b1
AL
760 }
761
762 From = (char *)From + Res;
763 Size -= Res;
578bfd0a 764 }
b0db36b1 765 while (Res > 0 && Size > 0);
578bfd0a 766
b0db36b1
AL
767 if (Size == 0)
768 return true;
769
770 Flags |= Fail;
b2e465d6 771 return _error->Error(_("write, still have %lu to write but couldn't"),Size);
578bfd0a
AL
772}
773 /*}}}*/
8e06abb2 774// FileFd::Seek - Seek in the file /*{{{*/
578bfd0a
AL
775// ---------------------------------------------------------------------
776/* */
8e06abb2 777bool FileFd::Seek(unsigned long To)
578bfd0a
AL
778{
779 if (lseek(iFd,To,SEEK_SET) != (signed)To)
780 {
781 Flags |= Fail;
b2e465d6 782 return _error->Error("Unable to seek to %lu",To);
578bfd0a
AL
783 }
784
727f18af
AL
785 return true;
786}
787 /*}}}*/
788// FileFd::Skip - Seek in the file /*{{{*/
789// ---------------------------------------------------------------------
790/* */
791bool FileFd::Skip(unsigned long Over)
792{
793 if (lseek(iFd,Over,SEEK_CUR) < 0)
794 {
795 Flags |= Fail;
b2e465d6 796 return _error->Error("Unable to seek ahead %lu",Over);
727f18af
AL
797 }
798
6d5dd02a
AL
799 return true;
800}
801 /*}}}*/
802// FileFd::Truncate - Truncate the file /*{{{*/
803// ---------------------------------------------------------------------
804/* */
805bool FileFd::Truncate(unsigned long To)
806{
807 if (ftruncate(iFd,To) != 0)
808 {
809 Flags |= Fail;
b2e465d6 810 return _error->Error("Unable to truncate to %lu",To);
6d5dd02a
AL
811 }
812
578bfd0a
AL
813 return true;
814}
815 /*}}}*/
7f25bdff
AL
816// FileFd::Tell - Current seek position /*{{{*/
817// ---------------------------------------------------------------------
818/* */
819unsigned long FileFd::Tell()
820{
821 off_t Res = lseek(iFd,0,SEEK_CUR);
822 if (Res == (off_t)-1)
823 _error->Errno("lseek","Failed to determine the current file position");
824 return Res;
825}
826 /*}}}*/
8e06abb2 827// FileFd::Size - Return the size of the file /*{{{*/
578bfd0a
AL
828// ---------------------------------------------------------------------
829/* */
8e06abb2 830unsigned long FileFd::Size()
578bfd0a
AL
831{
832 struct stat Buf;
833 if (fstat(iFd,&Buf) != 0)
834 return _error->Errno("fstat","Unable to determine the file size");
835 return Buf.st_size;
836}
837 /*}}}*/
8e06abb2 838// FileFd::Close - Close the file if the close flag is set /*{{{*/
578bfd0a
AL
839// ---------------------------------------------------------------------
840/* */
8e06abb2 841bool FileFd::Close()
578bfd0a
AL
842{
843 bool Res = true;
844 if ((Flags & AutoClose) == AutoClose)
1164783d 845 if (iFd >= 0 && close(iFd) != 0)
b2e465d6 846 Res &= _error->Errno("close",_("Problem closing the file"));
1164783d 847 iFd = -1;
3010fb0e
JAK
848
849 if ((Flags & Replace) == Replace) {
3010fb0e
JAK
850 if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
851 Res &= _error->Errno("rename",_("Problem renaming the file"));
fd3b761e 852 FileName = TemporaryFileName; // for the unlink() below.
3010fb0e
JAK
853 }
854
578bfd0a
AL
855 if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
856 FileName.empty() == false)
857 if (unlink(FileName.c_str()) != 0)
b2e465d6 858 Res &= _error->WarningE("unlnk",_("Problem unlinking the file"));
3010fb0e
JAK
859
860
578bfd0a
AL
861 return Res;
862}
863 /*}}}*/
b2e465d6
AL
864// FileFd::Sync - Sync the file /*{{{*/
865// ---------------------------------------------------------------------
866/* */
867bool FileFd::Sync()
868{
869#ifdef _POSIX_SYNCHRONIZED_IO
870 if (fsync(iFd) != 0)
871 return _error->Errno("sync",_("Problem syncing the file"));
872#endif
873 return true;
874}
875 /*}}}*/