fileutl.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. This source is placed in the Public Domain, do with it what you will
  9. It was originally written by Jason Gunthorpe <jgg@debian.org>.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #ifdef __GNUG__
  14. #pragma implementation "apt-pkg/fileutl.h"
  15. #endif
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/error.h>
  18. #include <apt-pkg/sptr.h>
  19. #include <apti18n.h>
  20. #include <iostream>
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #include <sys/stat.h>
  24. #include <sys/types.h>
  25. #include <sys/time.h>
  26. #include <sys/wait.h>
  27. #include <signal.h>
  28. #include <errno.h>
  29. /*}}}*/
  30. using namespace std;
  31. // CopyFile - Buffered copy of a file /*{{{*/
  32. // ---------------------------------------------------------------------
  33. /* The caller is expected to set things so that failure causes erasure */
  34. bool CopyFile(FileFd &From,FileFd &To)
  35. {
  36. if (From.IsOpen() == false || To.IsOpen() == false)
  37. return false;
  38. // Buffered copy between fds
  39. SPtrArray<unsigned char> Buf = new unsigned char[64000];
  40. unsigned long Size = From.Size();
  41. while (Size != 0)
  42. {
  43. unsigned long ToRead = Size;
  44. if (Size > 64000)
  45. ToRead = 64000;
  46. if (From.Read(Buf,ToRead) == false ||
  47. To.Write(Buf,ToRead) == false)
  48. return false;
  49. Size -= ToRead;
  50. }
  51. return true;
  52. }
  53. /*}}}*/
  54. // GetLock - Gets a lock file /*{{{*/
  55. // ---------------------------------------------------------------------
  56. /* This will create an empty file of the given name and lock it. Once this
  57. is done all other calls to GetLock in any other process will fail with
  58. -1. The return result is the fd of the file, the call should call
  59. close at some time. */
  60. int GetLock(string File,bool Errors)
  61. {
  62. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_TRUNC,0640);
  63. if (FD < 0)
  64. {
  65. // Read only .. cant have locking problems there.
  66. if (errno == EROFS)
  67. {
  68. _error->Warning(_("Not using locking for read only lock file %s"),File.c_str());
  69. return dup(0); // Need something for the caller to close
  70. }
  71. if (Errors == true)
  72. _error->Errno("open",_("Could not open lock file %s"),File.c_str());
  73. // Feh.. We do this to distinguish the lock vs open case..
  74. errno = EPERM;
  75. return -1;
  76. }
  77. SetCloseExec(FD,true);
  78. // Aquire a write lock
  79. struct flock fl;
  80. fl.l_type = F_WRLCK;
  81. fl.l_whence = SEEK_SET;
  82. fl.l_start = 0;
  83. fl.l_len = 0;
  84. if (fcntl(FD,F_SETLK,&fl) == -1)
  85. {
  86. if (errno == ENOLCK)
  87. {
  88. _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
  89. return dup(0); // Need something for the caller to close
  90. }
  91. if (Errors == true)
  92. _error->Errno("open",_("Could not get lock %s"),File.c_str());
  93. int Tmp = errno;
  94. close(FD);
  95. errno = Tmp;
  96. return -1;
  97. }
  98. return FD;
  99. }
  100. /*}}}*/
  101. // FileExists - Check if a file exists /*{{{*/
  102. // ---------------------------------------------------------------------
  103. /* */
  104. bool FileExists(string File)
  105. {
  106. struct stat Buf;
  107. if (stat(File.c_str(),&Buf) != 0)
  108. return false;
  109. return true;
  110. }
  111. /*}}}*/
  112. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  113. // ---------------------------------------------------------------------
  114. /* We return / on failure. */
  115. string SafeGetCWD()
  116. {
  117. // Stash the current dir.
  118. char S[300];
  119. S[0] = 0;
  120. if (getcwd(S,sizeof(S)-2) == 0)
  121. return "/";
  122. unsigned int Len = strlen(S);
  123. S[Len] = '/';
  124. S[Len+1] = 0;
  125. return S;
  126. }
  127. /*}}}*/
  128. // flNotDir - Strip the directory from the filename /*{{{*/
  129. // ---------------------------------------------------------------------
  130. /* */
  131. string flNotDir(string File)
  132. {
  133. string::size_type Res = File.rfind('/');
  134. if (Res == string::npos)
  135. return File;
  136. Res++;
  137. return string(File,Res,Res - File.length());
  138. }
  139. /*}}}*/
  140. // flNotFile - Strip the file from the directory name /*{{{*/
  141. // ---------------------------------------------------------------------
  142. /* Result ends in a / */
  143. string flNotFile(string File)
  144. {
  145. string::size_type Res = File.rfind('/');
  146. if (Res == string::npos)
  147. return "./";
  148. Res++;
  149. return string(File,0,Res);
  150. }
  151. /*}}}*/
  152. // flExtension - Return the extension for the file /*{{{*/
  153. // ---------------------------------------------------------------------
  154. /* */
  155. string flExtension(string File)
  156. {
  157. string::size_type Res = File.rfind('.');
  158. if (Res == string::npos)
  159. return File;
  160. Res++;
  161. return string(File,Res,Res - File.length());
  162. }
  163. /*}}}*/
  164. // flNoLink - If file is a symlink then deref it /*{{{*/
  165. // ---------------------------------------------------------------------
  166. /* If the name is not a link then the returned path is the input. */
  167. string flNoLink(string File)
  168. {
  169. struct stat St;
  170. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  171. return File;
  172. if (stat(File.c_str(),&St) != 0)
  173. return File;
  174. /* Loop resolving the link. There is no need to limit the number of
  175. loops because the stat call above ensures that the symlink is not
  176. circular */
  177. char Buffer[1024];
  178. string NFile = File;
  179. while (1)
  180. {
  181. // Read the link
  182. int Res;
  183. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  184. (unsigned)Res >= sizeof(Buffer))
  185. return File;
  186. // Append or replace the previous path
  187. Buffer[Res] = 0;
  188. if (Buffer[0] == '/')
  189. NFile = Buffer;
  190. else
  191. NFile = flNotFile(NFile) + Buffer;
  192. // See if we are done
  193. if (lstat(NFile.c_str(),&St) != 0)
  194. return File;
  195. if (S_ISLNK(St.st_mode) == 0)
  196. return NFile;
  197. }
  198. }
  199. /*}}}*/
  200. // flCombine - Combine a file and a directory /*{{{*/
  201. // ---------------------------------------------------------------------
  202. /* If the file is an absolute path then it is just returned, otherwise
  203. the directory is pre-pended to it. */
  204. string flCombine(string Dir,string File)
  205. {
  206. if (File.empty() == true)
  207. return string();
  208. if (File[0] == '/' || Dir.empty() == true)
  209. return File;
  210. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  211. return File;
  212. if (Dir[Dir.length()-1] == '/')
  213. return Dir + File;
  214. return Dir + '/' + File;
  215. }
  216. /*}}}*/
  217. // SetCloseExec - Set the close on exec flag /*{{{*/
  218. // ---------------------------------------------------------------------
  219. /* */
  220. void SetCloseExec(int Fd,bool Close)
  221. {
  222. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  223. {
  224. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  225. exit(100);
  226. }
  227. }
  228. /*}}}*/
  229. // SetNonBlock - Set the nonblocking flag /*{{{*/
  230. // ---------------------------------------------------------------------
  231. /* */
  232. void SetNonBlock(int Fd,bool Block)
  233. {
  234. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  235. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  236. {
  237. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  238. exit(100);
  239. }
  240. }
  241. /*}}}*/
  242. // WaitFd - Wait for a FD to become readable /*{{{*/
  243. // ---------------------------------------------------------------------
  244. /* This waits for a FD to become readable using select. It is useful for
  245. applications making use of non-blocking sockets. The timeout is
  246. in seconds. */
  247. bool WaitFd(int Fd,bool write,unsigned long timeout)
  248. {
  249. fd_set Set;
  250. struct timeval tv;
  251. FD_ZERO(&Set);
  252. FD_SET(Fd,&Set);
  253. tv.tv_sec = timeout;
  254. tv.tv_usec = 0;
  255. if (write == true)
  256. {
  257. int Res;
  258. do
  259. {
  260. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  261. }
  262. while (Res < 0 && errno == EINTR);
  263. if (Res <= 0)
  264. return false;
  265. }
  266. else
  267. {
  268. int Res;
  269. do
  270. {
  271. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  272. }
  273. while (Res < 0 && errno == EINTR);
  274. if (Res <= 0)
  275. return false;
  276. }
  277. return true;
  278. }
  279. /*}}}*/
  280. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  281. // ---------------------------------------------------------------------
  282. /* This is used if you want to cleanse the environment for the forked
  283. child, it fixes up the important signals and nukes all of the fds,
  284. otherwise acts like normal fork. */
  285. pid_t ExecFork()
  286. {
  287. // Fork off the process
  288. pid_t Process = fork();
  289. if (Process < 0)
  290. {
  291. cerr << "FATAL -> Failed to fork." << endl;
  292. exit(100);
  293. }
  294. // Spawn the subprocess
  295. if (Process == 0)
  296. {
  297. // Setup the signals
  298. signal(SIGPIPE,SIG_DFL);
  299. signal(SIGQUIT,SIG_DFL);
  300. signal(SIGINT,SIG_DFL);
  301. signal(SIGWINCH,SIG_DFL);
  302. signal(SIGCONT,SIG_DFL);
  303. signal(SIGTSTP,SIG_DFL);
  304. // Close all of our FDs - just in case
  305. for (int K = 3; K != 40; K++)
  306. fcntl(K,F_SETFD,FD_CLOEXEC);
  307. }
  308. return Process;
  309. }
  310. /*}}}*/
  311. // ExecWait - Fancy waitpid /*{{{*/
  312. // ---------------------------------------------------------------------
  313. /* Waits for the given sub process. If Reap is set then no errors are
  314. generated. Otherwise a failed subprocess will generate a proper descriptive
  315. message */
  316. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  317. {
  318. if (Pid <= 1)
  319. return true;
  320. // Wait and collect the error code
  321. int Status;
  322. while (waitpid(Pid,&Status,0) != Pid)
  323. {
  324. if (errno == EINTR)
  325. continue;
  326. if (Reap == true)
  327. return false;
  328. return _error->Error(_("Waited, for %s but it wasn't there"),Name);
  329. }
  330. // Check for an error code.
  331. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  332. {
  333. if (Reap == true)
  334. return false;
  335. if (WIFSIGNALED(Status) != 0 && WTERMSIG(Status) == SIGSEGV)
  336. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  337. if (WIFEXITED(Status) != 0)
  338. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  339. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  340. }
  341. return true;
  342. }
  343. /*}}}*/
  344. // FileFd::Open - Open a file /*{{{*/
  345. // ---------------------------------------------------------------------
  346. /* The most commonly used open mode combinations are given with Mode */
  347. bool FileFd::Open(string FileName,OpenMode Mode, unsigned long Perms)
  348. {
  349. Close();
  350. Flags = AutoClose;
  351. switch (Mode)
  352. {
  353. case ReadOnly:
  354. iFd = open(FileName.c_str(),O_RDONLY);
  355. break;
  356. case WriteEmpty:
  357. {
  358. struct stat Buf;
  359. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  360. unlink(FileName.c_str());
  361. iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_TRUNC,Perms);
  362. break;
  363. }
  364. case WriteExists:
  365. iFd = open(FileName.c_str(),O_RDWR);
  366. break;
  367. case WriteAny:
  368. iFd = open(FileName.c_str(),O_RDWR | O_CREAT,Perms);
  369. break;
  370. case WriteTemp:
  371. unlink(FileName.c_str());
  372. iFd = open(FileName.c_str(),O_RDWR | O_CREAT | O_EXCL,Perms);
  373. break;
  374. }
  375. if (iFd < 0)
  376. return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
  377. this->FileName = FileName;
  378. SetCloseExec(iFd,true);
  379. return true;
  380. }
  381. /*}}}*/
  382. // FileFd::~File - Closes the file /*{{{*/
  383. // ---------------------------------------------------------------------
  384. /* If the proper modes are selected then we close the Fd and possibly
  385. unlink the file on error. */
  386. FileFd::~FileFd()
  387. {
  388. Close();
  389. }
  390. /*}}}*/
  391. // FileFd::Read - Read a bit of the file /*{{{*/
  392. // ---------------------------------------------------------------------
  393. /* We are carefull to handle interruption by a signal while reading
  394. gracefully. */
  395. bool FileFd::Read(void *To,unsigned long Size,unsigned long *Actual)
  396. {
  397. int Res;
  398. errno = 0;
  399. if (Actual != 0)
  400. *Actual = 0;
  401. do
  402. {
  403. Res = read(iFd,To,Size);
  404. if (Res < 0 && errno == EINTR)
  405. continue;
  406. if (Res < 0)
  407. {
  408. Flags |= Fail;
  409. return _error->Errno("read",_("Read error"));
  410. }
  411. To = (char *)To + Res;
  412. Size -= Res;
  413. if (Actual != 0)
  414. *Actual += Res;
  415. }
  416. while (Res > 0 && Size > 0);
  417. if (Size == 0)
  418. return true;
  419. // Eof handling
  420. if (Actual != 0)
  421. {
  422. Flags |= HitEof;
  423. return true;
  424. }
  425. Flags |= Fail;
  426. return _error->Error(_("read, still have %lu to read but none left"),Size);
  427. }
  428. /*}}}*/
  429. // FileFd::Write - Write to the file /*{{{*/
  430. // ---------------------------------------------------------------------
  431. /* */
  432. bool FileFd::Write(const void *From,unsigned long Size)
  433. {
  434. int Res;
  435. errno = 0;
  436. do
  437. {
  438. Res = write(iFd,From,Size);
  439. if (Res < 0 && errno == EINTR)
  440. continue;
  441. if (Res < 0)
  442. {
  443. Flags |= Fail;
  444. return _error->Errno("write",_("Write error"));
  445. }
  446. From = (char *)From + Res;
  447. Size -= Res;
  448. }
  449. while (Res > 0 && Size > 0);
  450. if (Size == 0)
  451. return true;
  452. Flags |= Fail;
  453. return _error->Error(_("write, still have %lu to write but couldn't"),Size);
  454. }
  455. /*}}}*/
  456. // FileFd::Seek - Seek in the file /*{{{*/
  457. // ---------------------------------------------------------------------
  458. /* */
  459. bool FileFd::Seek(unsigned long To)
  460. {
  461. if (lseek(iFd,To,SEEK_SET) != (signed)To)
  462. {
  463. Flags |= Fail;
  464. return _error->Error("Unable to seek to %lu",To);
  465. }
  466. return true;
  467. }
  468. /*}}}*/
  469. // FileFd::Skip - Seek in the file /*{{{*/
  470. // ---------------------------------------------------------------------
  471. /* */
  472. bool FileFd::Skip(unsigned long Over)
  473. {
  474. if (lseek(iFd,Over,SEEK_CUR) < 0)
  475. {
  476. Flags |= Fail;
  477. return _error->Error("Unable to seek ahead %lu",Over);
  478. }
  479. return true;
  480. }
  481. /*}}}*/
  482. // FileFd::Truncate - Truncate the file /*{{{*/
  483. // ---------------------------------------------------------------------
  484. /* */
  485. bool FileFd::Truncate(unsigned long To)
  486. {
  487. if (ftruncate(iFd,To) != 0)
  488. {
  489. Flags |= Fail;
  490. return _error->Error("Unable to truncate to %lu",To);
  491. }
  492. return true;
  493. }
  494. /*}}}*/
  495. // FileFd::Tell - Current seek position /*{{{*/
  496. // ---------------------------------------------------------------------
  497. /* */
  498. unsigned long FileFd::Tell()
  499. {
  500. off_t Res = lseek(iFd,0,SEEK_CUR);
  501. if (Res == (off_t)-1)
  502. _error->Errno("lseek","Failed to determine the current file position");
  503. return Res;
  504. }
  505. /*}}}*/
  506. // FileFd::Size - Return the size of the file /*{{{*/
  507. // ---------------------------------------------------------------------
  508. /* */
  509. unsigned long FileFd::Size()
  510. {
  511. struct stat Buf;
  512. if (fstat(iFd,&Buf) != 0)
  513. return _error->Errno("fstat","Unable to determine the file size");
  514. return Buf.st_size;
  515. }
  516. /*}}}*/
  517. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  518. // ---------------------------------------------------------------------
  519. /* */
  520. bool FileFd::Close()
  521. {
  522. bool Res = true;
  523. if ((Flags & AutoClose) == AutoClose)
  524. if (iFd >= 0 && close(iFd) != 0)
  525. Res &= _error->Errno("close",_("Problem closing the file"));
  526. iFd = -1;
  527. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  528. FileName.empty() == false)
  529. if (unlink(FileName.c_str()) != 0)
  530. Res &= _error->WarningE("unlnk",_("Problem unlinking the file"));
  531. return Res;
  532. }
  533. /*}}}*/
  534. // FileFd::Sync - Sync the file /*{{{*/
  535. // ---------------------------------------------------------------------
  536. /* */
  537. bool FileFd::Sync()
  538. {
  539. #ifdef _POSIX_SYNCHRONIZED_IO
  540. if (fsync(iFd) != 0)
  541. return _error->Errno("sync",_("Problem syncing the file"));
  542. #endif
  543. return true;
  544. }
  545. /*}}}*/