fileutl.cc 22 KB

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