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.
 
 
 
 
 
 

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