You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

878 lines
24 KiB

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