fileutl.cc 18 KB

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