fileutl.cc 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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. FileFd gzip support added by Martin Pitt <martin.pitt@canonical.com>
  12. The exception is RunScripts() it is under the GPLv2
  13. ##################################################################### */
  14. /*}}}*/
  15. // Include Files /*{{{*/
  16. #include <config.h>
  17. #include <apt-pkg/fileutl.h>
  18. #include <apt-pkg/strutl.h>
  19. #include <apt-pkg/error.h>
  20. #include <apt-pkg/sptr.h>
  21. #include <apt-pkg/aptconfiguration.h>
  22. #include <apt-pkg/configuration.h>
  23. #include <cstdlib>
  24. #include <cstring>
  25. #include <cstdio>
  26. #include <iostream>
  27. #include <unistd.h>
  28. #include <fcntl.h>
  29. #include <sys/stat.h>
  30. #include <sys/types.h>
  31. #include <sys/time.h>
  32. #include <sys/wait.h>
  33. #include <dirent.h>
  34. #include <signal.h>
  35. #include <errno.h>
  36. #include <set>
  37. #include <algorithm>
  38. #include <zlib.h>
  39. #ifdef WORDS_BIGENDIAN
  40. #include <inttypes.h>
  41. #endif
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. class FileFdPrivate {
  46. public:
  47. gzFile gz;
  48. FileFdPrivate() : gz(NULL) {};
  49. };
  50. // RunScripts - Run a set of scripts from a configuration subtree /*{{{*/
  51. // ---------------------------------------------------------------------
  52. /* */
  53. bool RunScripts(const char *Cnf)
  54. {
  55. Configuration::Item const *Opts = _config->Tree(Cnf);
  56. if (Opts == 0 || Opts->Child == 0)
  57. return true;
  58. Opts = Opts->Child;
  59. // Fork for running the system calls
  60. pid_t Child = ExecFork();
  61. // This is the child
  62. if (Child == 0)
  63. {
  64. if (_config->FindDir("DPkg::Chroot-Directory","/") != "/")
  65. {
  66. std::cerr << "Chrooting into "
  67. << _config->FindDir("DPkg::Chroot-Directory")
  68. << std::endl;
  69. if (chroot(_config->FindDir("DPkg::Chroot-Directory","/").c_str()) != 0)
  70. _exit(100);
  71. }
  72. if (chdir("/tmp/") != 0)
  73. _exit(100);
  74. unsigned int Count = 1;
  75. for (; Opts != 0; Opts = Opts->Next, Count++)
  76. {
  77. if (Opts->Value.empty() == true)
  78. continue;
  79. if (system(Opts->Value.c_str()) != 0)
  80. _exit(100+Count);
  81. }
  82. _exit(0);
  83. }
  84. // Wait for the child
  85. int Status = 0;
  86. while (waitpid(Child,&Status,0) != Child)
  87. {
  88. if (errno == EINTR)
  89. continue;
  90. return _error->Errno("waitpid","Couldn't wait for subprocess");
  91. }
  92. // Restore sig int/quit
  93. signal(SIGQUIT,SIG_DFL);
  94. signal(SIGINT,SIG_DFL);
  95. // Check for an error code.
  96. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  97. {
  98. unsigned int Count = WEXITSTATUS(Status);
  99. if (Count > 100)
  100. {
  101. Count -= 100;
  102. for (; Opts != 0 && Count != 1; Opts = Opts->Next, Count--);
  103. _error->Error("Problem executing scripts %s '%s'",Cnf,Opts->Value.c_str());
  104. }
  105. return _error->Error("Sub-process returned an error code");
  106. }
  107. return true;
  108. }
  109. /*}}}*/
  110. // CopyFile - Buffered copy of a file /*{{{*/
  111. // ---------------------------------------------------------------------
  112. /* The caller is expected to set things so that failure causes erasure */
  113. bool CopyFile(FileFd &From,FileFd &To)
  114. {
  115. if (From.IsOpen() == false || To.IsOpen() == false)
  116. return false;
  117. // Buffered copy between fds
  118. SPtrArray<unsigned char> Buf = new unsigned char[64000];
  119. unsigned long long Size = From.Size();
  120. while (Size != 0)
  121. {
  122. unsigned long long ToRead = Size;
  123. if (Size > 64000)
  124. ToRead = 64000;
  125. if (From.Read(Buf,ToRead) == false ||
  126. To.Write(Buf,ToRead) == false)
  127. return false;
  128. Size -= ToRead;
  129. }
  130. return true;
  131. }
  132. /*}}}*/
  133. // GetLock - Gets a lock file /*{{{*/
  134. // ---------------------------------------------------------------------
  135. /* This will create an empty file of the given name and lock it. Once this
  136. is done all other calls to GetLock in any other process will fail with
  137. -1. The return result is the fd of the file, the call should call
  138. close at some time. */
  139. int GetLock(string File,bool Errors)
  140. {
  141. // GetLock() is used in aptitude on directories with public-write access
  142. // Use O_NOFOLLOW here to prevent symlink traversal attacks
  143. int FD = open(File.c_str(),O_RDWR | O_CREAT | O_NOFOLLOW,0640);
  144. if (FD < 0)
  145. {
  146. // Read only .. cant have locking problems there.
  147. if (errno == EROFS)
  148. {
  149. _error->Warning(_("Not using locking for read only 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 open lock file %s"),File.c_str());
  154. // Feh.. We do this to distinguish the lock vs open case..
  155. errno = EPERM;
  156. return -1;
  157. }
  158. SetCloseExec(FD,true);
  159. // Aquire a write lock
  160. struct flock fl;
  161. fl.l_type = F_WRLCK;
  162. fl.l_whence = SEEK_SET;
  163. fl.l_start = 0;
  164. fl.l_len = 0;
  165. if (fcntl(FD,F_SETLK,&fl) == -1)
  166. {
  167. if (errno == ENOLCK)
  168. {
  169. _error->Warning(_("Not using locking for nfs mounted lock file %s"),File.c_str());
  170. return dup(0); // Need something for the caller to close
  171. }
  172. if (Errors == true)
  173. _error->Errno("open",_("Could not get lock %s"),File.c_str());
  174. int Tmp = errno;
  175. close(FD);
  176. errno = Tmp;
  177. return -1;
  178. }
  179. return FD;
  180. }
  181. /*}}}*/
  182. // FileExists - Check if a file exists /*{{{*/
  183. // ---------------------------------------------------------------------
  184. /* Beware: Directories are also files! */
  185. bool FileExists(string File)
  186. {
  187. struct stat Buf;
  188. if (stat(File.c_str(),&Buf) != 0)
  189. return false;
  190. return true;
  191. }
  192. /*}}}*/
  193. // RealFileExists - Check if a file exists and if it is really a file /*{{{*/
  194. // ---------------------------------------------------------------------
  195. /* */
  196. bool RealFileExists(string File)
  197. {
  198. struct stat Buf;
  199. if (stat(File.c_str(),&Buf) != 0)
  200. return false;
  201. return ((Buf.st_mode & S_IFREG) != 0);
  202. }
  203. /*}}}*/
  204. // DirectoryExists - Check if a directory exists and is really one /*{{{*/
  205. // ---------------------------------------------------------------------
  206. /* */
  207. bool DirectoryExists(string const &Path)
  208. {
  209. struct stat Buf;
  210. if (stat(Path.c_str(),&Buf) != 0)
  211. return false;
  212. return ((Buf.st_mode & S_IFDIR) != 0);
  213. }
  214. /*}}}*/
  215. // CreateDirectory - poor man's mkdir -p guarded by a parent directory /*{{{*/
  216. // ---------------------------------------------------------------------
  217. /* This method will create all directories needed for path in good old
  218. mkdir -p style but refuses to do this if Parent is not a prefix of
  219. this Path. Example: /var/cache/ and /var/cache/apt/archives are given,
  220. so it will create apt/archives if /var/cache exists - on the other
  221. hand if the parent is /var/lib the creation will fail as this path
  222. is not a parent of the path to be generated. */
  223. bool CreateDirectory(string const &Parent, string const &Path)
  224. {
  225. if (Parent.empty() == true || Path.empty() == true)
  226. return false;
  227. if (DirectoryExists(Path) == true)
  228. return true;
  229. if (DirectoryExists(Parent) == false)
  230. return false;
  231. // we are not going to create directories "into the blue"
  232. if (Path.find(Parent, 0) != 0)
  233. return false;
  234. vector<string> const dirs = VectorizeString(Path.substr(Parent.size()), '/');
  235. string progress = Parent;
  236. for (vector<string>::const_iterator d = dirs.begin(); d != dirs.end(); ++d)
  237. {
  238. if (d->empty() == true)
  239. continue;
  240. progress.append("/").append(*d);
  241. if (DirectoryExists(progress) == true)
  242. continue;
  243. if (mkdir(progress.c_str(), 0755) != 0)
  244. return false;
  245. }
  246. return true;
  247. }
  248. /*}}}*/
  249. // CreateAPTDirectoryIfNeeded - ensure that the given directory exists /*{{{*/
  250. // ---------------------------------------------------------------------
  251. /* a small wrapper around CreateDirectory to check if it exists and to
  252. remove the trailing "/apt/" from the parent directory if needed */
  253. bool CreateAPTDirectoryIfNeeded(string const &Parent, string const &Path)
  254. {
  255. if (DirectoryExists(Path) == true)
  256. return true;
  257. size_t const len = Parent.size();
  258. if (len > 5 && Parent.find("/apt/", len - 6, 5) == len - 5)
  259. {
  260. if (CreateDirectory(Parent.substr(0,len-5), Path) == true)
  261. return true;
  262. }
  263. else if (CreateDirectory(Parent, Path) == true)
  264. return true;
  265. return false;
  266. }
  267. /*}}}*/
  268. // GetListOfFilesInDir - returns a vector of files in the given dir /*{{{*/
  269. // ---------------------------------------------------------------------
  270. /* If an extension is given only files with this extension are included
  271. in the returned vector, otherwise every "normal" file is included. */
  272. std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
  273. bool const &SortList, bool const &AllowNoExt)
  274. {
  275. std::vector<string> ext;
  276. ext.reserve(2);
  277. if (Ext.empty() == false)
  278. ext.push_back(Ext);
  279. if (AllowNoExt == true && ext.empty() == false)
  280. ext.push_back("");
  281. return GetListOfFilesInDir(Dir, ext, SortList);
  282. }
  283. std::vector<string> GetListOfFilesInDir(string const &Dir, std::vector<string> const &Ext,
  284. bool const &SortList)
  285. {
  286. // Attention debuggers: need to be set with the environment config file!
  287. bool const Debug = _config->FindB("Debug::GetListOfFilesInDir", false);
  288. if (Debug == true)
  289. {
  290. std::clog << "Accept in " << Dir << " only files with the following " << Ext.size() << " extensions:" << std::endl;
  291. if (Ext.empty() == true)
  292. std::clog << "\tNO extension" << std::endl;
  293. else
  294. for (std::vector<string>::const_iterator e = Ext.begin();
  295. e != Ext.end(); ++e)
  296. std::clog << '\t' << (e->empty() == true ? "NO" : *e) << " extension" << std::endl;
  297. }
  298. std::vector<string> List;
  299. if (DirectoryExists(Dir.c_str()) == false)
  300. {
  301. _error->Error(_("List of files can't be created as '%s' is not a directory"), Dir.c_str());
  302. return List;
  303. }
  304. Configuration::MatchAgainstConfig SilentIgnore("Dir::Ignore-Files-Silently");
  305. DIR *D = opendir(Dir.c_str());
  306. if (D == 0)
  307. {
  308. _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
  309. return List;
  310. }
  311. for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D))
  312. {
  313. // skip "hidden" files
  314. if (Ent->d_name[0] == '.')
  315. continue;
  316. // Make sure it is a file and not something else
  317. string const File = flCombine(Dir,Ent->d_name);
  318. #ifdef _DIRENT_HAVE_D_TYPE
  319. if (Ent->d_type != DT_REG)
  320. #endif
  321. {
  322. if (RealFileExists(File.c_str()) == false)
  323. {
  324. if (SilentIgnore.Match(Ent->d_name) == false)
  325. _error->Notice(_("Ignoring '%s' in directory '%s' as it is not a regular file"), Ent->d_name, Dir.c_str());
  326. continue;
  327. }
  328. }
  329. // check for accepted extension:
  330. // no extension given -> periods are bad as hell!
  331. // extensions given -> "" extension allows no extension
  332. if (Ext.empty() == false)
  333. {
  334. string d_ext = flExtension(Ent->d_name);
  335. if (d_ext == Ent->d_name) // no extension
  336. {
  337. if (std::find(Ext.begin(), Ext.end(), "") == Ext.end())
  338. {
  339. if (Debug == true)
  340. std::clog << "Bad file: " << Ent->d_name << " → no extension" << std::endl;
  341. if (SilentIgnore.Match(Ent->d_name) == false)
  342. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has no filename extension"), Ent->d_name, Dir.c_str());
  343. continue;
  344. }
  345. }
  346. else if (std::find(Ext.begin(), Ext.end(), d_ext) == Ext.end())
  347. {
  348. if (Debug == true)
  349. std::clog << "Bad file: " << Ent->d_name << " → bad extension »" << flExtension(Ent->d_name) << "«" << std::endl;
  350. if (SilentIgnore.Match(Ent->d_name) == false)
  351. _error->Notice(_("Ignoring file '%s' in directory '%s' as it has an invalid filename extension"), Ent->d_name, Dir.c_str());
  352. continue;
  353. }
  354. }
  355. // Skip bad filenames ala run-parts
  356. const char *C = Ent->d_name;
  357. for (; *C != 0; ++C)
  358. if (isalpha(*C) == 0 && isdigit(*C) == 0
  359. && *C != '_' && *C != '-') {
  360. // no required extension -> dot is a bad character
  361. if (*C == '.' && Ext.empty() == false)
  362. continue;
  363. break;
  364. }
  365. // we don't reach the end of the name -> bad character included
  366. if (*C != 0)
  367. {
  368. if (Debug == true)
  369. std::clog << "Bad file: " << Ent->d_name << " → bad character »"
  370. << *C << "« in filename (period allowed: " << (Ext.empty() ? "no" : "yes") << ")" << std::endl;
  371. continue;
  372. }
  373. // skip filenames which end with a period. These are never valid
  374. if (*(C - 1) == '.')
  375. {
  376. if (Debug == true)
  377. std::clog << "Bad file: " << Ent->d_name << " → Period as last character" << std::endl;
  378. continue;
  379. }
  380. if (Debug == true)
  381. std::clog << "Accept file: " << Ent->d_name << " in " << Dir << std::endl;
  382. List.push_back(File);
  383. }
  384. closedir(D);
  385. if (SortList == true)
  386. std::sort(List.begin(),List.end());
  387. return List;
  388. }
  389. /*}}}*/
  390. // SafeGetCWD - This is a safer getcwd that returns a dynamic string /*{{{*/
  391. // ---------------------------------------------------------------------
  392. /* We return / on failure. */
  393. string SafeGetCWD()
  394. {
  395. // Stash the current dir.
  396. char S[300];
  397. S[0] = 0;
  398. if (getcwd(S,sizeof(S)-2) == 0)
  399. return "/";
  400. unsigned int Len = strlen(S);
  401. S[Len] = '/';
  402. S[Len+1] = 0;
  403. return S;
  404. }
  405. /*}}}*/
  406. // GetModificationTime - Get the mtime of the given file or -1 on error /*{{{*/
  407. // ---------------------------------------------------------------------
  408. /* We return / on failure. */
  409. time_t GetModificationTime(string const &Path)
  410. {
  411. struct stat St;
  412. if (stat(Path.c_str(), &St) < 0)
  413. return -1;
  414. return St.st_mtime;
  415. }
  416. /*}}}*/
  417. // flNotDir - Strip the directory from the filename /*{{{*/
  418. // ---------------------------------------------------------------------
  419. /* */
  420. string flNotDir(string File)
  421. {
  422. string::size_type Res = File.rfind('/');
  423. if (Res == string::npos)
  424. return File;
  425. Res++;
  426. return string(File,Res,Res - File.length());
  427. }
  428. /*}}}*/
  429. // flNotFile - Strip the file from the directory name /*{{{*/
  430. // ---------------------------------------------------------------------
  431. /* Result ends in a / */
  432. string flNotFile(string File)
  433. {
  434. string::size_type Res = File.rfind('/');
  435. if (Res == string::npos)
  436. return "./";
  437. Res++;
  438. return string(File,0,Res);
  439. }
  440. /*}}}*/
  441. // flExtension - Return the extension for the file /*{{{*/
  442. // ---------------------------------------------------------------------
  443. /* */
  444. string flExtension(string File)
  445. {
  446. string::size_type Res = File.rfind('.');
  447. if (Res == string::npos)
  448. return File;
  449. Res++;
  450. return string(File,Res,Res - File.length());
  451. }
  452. /*}}}*/
  453. // flNoLink - If file is a symlink then deref it /*{{{*/
  454. // ---------------------------------------------------------------------
  455. /* If the name is not a link then the returned path is the input. */
  456. string flNoLink(string File)
  457. {
  458. struct stat St;
  459. if (lstat(File.c_str(),&St) != 0 || S_ISLNK(St.st_mode) == 0)
  460. return File;
  461. if (stat(File.c_str(),&St) != 0)
  462. return File;
  463. /* Loop resolving the link. There is no need to limit the number of
  464. loops because the stat call above ensures that the symlink is not
  465. circular */
  466. char Buffer[1024];
  467. string NFile = File;
  468. while (1)
  469. {
  470. // Read the link
  471. int Res;
  472. if ((Res = readlink(NFile.c_str(),Buffer,sizeof(Buffer))) <= 0 ||
  473. (unsigned)Res >= sizeof(Buffer))
  474. return File;
  475. // Append or replace the previous path
  476. Buffer[Res] = 0;
  477. if (Buffer[0] == '/')
  478. NFile = Buffer;
  479. else
  480. NFile = flNotFile(NFile) + Buffer;
  481. // See if we are done
  482. if (lstat(NFile.c_str(),&St) != 0)
  483. return File;
  484. if (S_ISLNK(St.st_mode) == 0)
  485. return NFile;
  486. }
  487. }
  488. /*}}}*/
  489. // flCombine - Combine a file and a directory /*{{{*/
  490. // ---------------------------------------------------------------------
  491. /* If the file is an absolute path then it is just returned, otherwise
  492. the directory is pre-pended to it. */
  493. string flCombine(string Dir,string File)
  494. {
  495. if (File.empty() == true)
  496. return string();
  497. if (File[0] == '/' || Dir.empty() == true)
  498. return File;
  499. if (File.length() >= 2 && File[0] == '.' && File[1] == '/')
  500. return File;
  501. if (Dir[Dir.length()-1] == '/')
  502. return Dir + File;
  503. return Dir + '/' + File;
  504. }
  505. /*}}}*/
  506. // SetCloseExec - Set the close on exec flag /*{{{*/
  507. // ---------------------------------------------------------------------
  508. /* */
  509. void SetCloseExec(int Fd,bool Close)
  510. {
  511. if (fcntl(Fd,F_SETFD,(Close == false)?0:FD_CLOEXEC) != 0)
  512. {
  513. cerr << "FATAL -> Could not set close on exec " << strerror(errno) << endl;
  514. exit(100);
  515. }
  516. }
  517. /*}}}*/
  518. // SetNonBlock - Set the nonblocking flag /*{{{*/
  519. // ---------------------------------------------------------------------
  520. /* */
  521. void SetNonBlock(int Fd,bool Block)
  522. {
  523. int Flags = fcntl(Fd,F_GETFL) & (~O_NONBLOCK);
  524. if (fcntl(Fd,F_SETFL,Flags | ((Block == false)?0:O_NONBLOCK)) != 0)
  525. {
  526. cerr << "FATAL -> Could not set non-blocking flag " << strerror(errno) << endl;
  527. exit(100);
  528. }
  529. }
  530. /*}}}*/
  531. // WaitFd - Wait for a FD to become readable /*{{{*/
  532. // ---------------------------------------------------------------------
  533. /* This waits for a FD to become readable using select. It is useful for
  534. applications making use of non-blocking sockets. The timeout is
  535. in seconds. */
  536. bool WaitFd(int Fd,bool write,unsigned long timeout)
  537. {
  538. fd_set Set;
  539. struct timeval tv;
  540. FD_ZERO(&Set);
  541. FD_SET(Fd,&Set);
  542. tv.tv_sec = timeout;
  543. tv.tv_usec = 0;
  544. if (write == true)
  545. {
  546. int Res;
  547. do
  548. {
  549. Res = select(Fd+1,0,&Set,0,(timeout != 0?&tv:0));
  550. }
  551. while (Res < 0 && errno == EINTR);
  552. if (Res <= 0)
  553. return false;
  554. }
  555. else
  556. {
  557. int Res;
  558. do
  559. {
  560. Res = select(Fd+1,&Set,0,0,(timeout != 0?&tv:0));
  561. }
  562. while (Res < 0 && errno == EINTR);
  563. if (Res <= 0)
  564. return false;
  565. }
  566. return true;
  567. }
  568. /*}}}*/
  569. // ExecFork - Magical fork that sanitizes the context before execing /*{{{*/
  570. // ---------------------------------------------------------------------
  571. /* This is used if you want to cleanse the environment for the forked
  572. child, it fixes up the important signals and nukes all of the fds,
  573. otherwise acts like normal fork. */
  574. pid_t ExecFork()
  575. {
  576. // Fork off the process
  577. pid_t Process = fork();
  578. if (Process < 0)
  579. {
  580. cerr << "FATAL -> Failed to fork." << endl;
  581. exit(100);
  582. }
  583. // Spawn the subprocess
  584. if (Process == 0)
  585. {
  586. // Setup the signals
  587. signal(SIGPIPE,SIG_DFL);
  588. signal(SIGQUIT,SIG_DFL);
  589. signal(SIGINT,SIG_DFL);
  590. signal(SIGWINCH,SIG_DFL);
  591. signal(SIGCONT,SIG_DFL);
  592. signal(SIGTSTP,SIG_DFL);
  593. set<int> KeepFDs;
  594. Configuration::Item const *Opts = _config->Tree("APT::Keep-Fds");
  595. if (Opts != 0 && Opts->Child != 0)
  596. {
  597. Opts = Opts->Child;
  598. for (; Opts != 0; Opts = Opts->Next)
  599. {
  600. if (Opts->Value.empty() == true)
  601. continue;
  602. int fd = atoi(Opts->Value.c_str());
  603. KeepFDs.insert(fd);
  604. }
  605. }
  606. // Close all of our FDs - just in case
  607. for (int K = 3; K != 40; K++)
  608. {
  609. if(KeepFDs.find(K) == KeepFDs.end())
  610. fcntl(K,F_SETFD,FD_CLOEXEC);
  611. }
  612. }
  613. return Process;
  614. }
  615. /*}}}*/
  616. // ExecWait - Fancy waitpid /*{{{*/
  617. // ---------------------------------------------------------------------
  618. /* Waits for the given sub process. If Reap is set then no errors are
  619. generated. Otherwise a failed subprocess will generate a proper descriptive
  620. message */
  621. bool ExecWait(pid_t Pid,const char *Name,bool Reap)
  622. {
  623. if (Pid <= 1)
  624. return true;
  625. // Wait and collect the error code
  626. int Status;
  627. while (waitpid(Pid,&Status,0) != Pid)
  628. {
  629. if (errno == EINTR)
  630. continue;
  631. if (Reap == true)
  632. return false;
  633. return _error->Error(_("Waited for %s but it wasn't there"),Name);
  634. }
  635. // Check for an error code.
  636. if (WIFEXITED(Status) == 0 || WEXITSTATUS(Status) != 0)
  637. {
  638. if (Reap == true)
  639. return false;
  640. if (WIFSIGNALED(Status) != 0)
  641. {
  642. if( WTERMSIG(Status) == SIGSEGV)
  643. return _error->Error(_("Sub-process %s received a segmentation fault."),Name);
  644. else
  645. return _error->Error(_("Sub-process %s received signal %u."),Name, WTERMSIG(Status));
  646. }
  647. if (WIFEXITED(Status) != 0)
  648. return _error->Error(_("Sub-process %s returned an error code (%u)"),Name,WEXITSTATUS(Status));
  649. return _error->Error(_("Sub-process %s exited unexpectedly"),Name);
  650. }
  651. return true;
  652. }
  653. /*}}}*/
  654. // FileFd::Open - Open a file /*{{{*/
  655. // ---------------------------------------------------------------------
  656. /* The most commonly used open mode combinations are given with Mode */
  657. bool FileFd::Open(string FileName,OpenMode Mode,CompressMode Compress, unsigned long const Perms)
  658. {
  659. if (Mode == ReadOnlyGzip)
  660. return Open(FileName, ReadOnly, Gzip, Perms);
  661. Close();
  662. d = new FileFdPrivate;
  663. Flags = AutoClose;
  664. if (Compress == Auto && (Mode & WriteOnly) == WriteOnly)
  665. return _error->Error("Autodetection on %s only works in ReadOnly openmode!", FileName.c_str());
  666. if ((Mode & WriteOnly) != WriteOnly && (Mode & (Atomic | Create | Empty | Exclusive)) != 0)
  667. return _error->Error("ReadOnly mode for %s doesn't accept additional flags!", FileName.c_str());
  668. int fileflags = 0;
  669. #define if_FLAGGED_SET(FLAG, MODE) if ((Mode & FLAG) == FLAG) fileflags |= MODE
  670. if_FLAGGED_SET(ReadWrite, O_RDWR);
  671. else if_FLAGGED_SET(ReadOnly, O_RDONLY);
  672. else if_FLAGGED_SET(WriteOnly, O_WRONLY);
  673. else return _error->Error("No openmode provided in FileFd::Open for %s", FileName.c_str());
  674. if_FLAGGED_SET(Create, O_CREAT);
  675. if_FLAGGED_SET(Exclusive, O_EXCL);
  676. else if_FLAGGED_SET(Atomic, O_EXCL);
  677. if_FLAGGED_SET(Empty, O_TRUNC);
  678. #undef if_FLAGGED_SET
  679. // FIXME: Denote inbuilt compressors somehow - as we don't need to have the binaries for them
  680. std::vector<APT::Configuration::Compressor> const compressors = APT::Configuration::getCompressors();
  681. std::vector<APT::Configuration::Compressor>::const_iterator compressor = compressors.begin();
  682. if (Compress == Auto)
  683. {
  684. Compress = None;
  685. for (; compressor != compressors.end(); ++compressor)
  686. {
  687. std::string file = std::string(FileName).append(compressor->Extension);
  688. if (FileExists(file) == false)
  689. continue;
  690. FileName = file;
  691. if (compressor->Binary == ".")
  692. Compress = None;
  693. else
  694. Compress = Extension;
  695. break;
  696. }
  697. }
  698. else if (Compress == Extension)
  699. {
  700. Compress = None;
  701. std::string ext = flExtension(FileName);
  702. if (ext != FileName)
  703. {
  704. ext = "." + ext;
  705. for (; compressor != compressors.end(); ++compressor)
  706. if (ext == compressor->Extension)
  707. break;
  708. }
  709. }
  710. else if (Compress != None)
  711. {
  712. std::string name;
  713. switch (Compress)
  714. {
  715. case Gzip: name = "gzip"; break;
  716. case Bzip2: name = "bzip2"; break;
  717. case Lzma: name = "lzma"; break;
  718. case Xz: name = "xz"; break;
  719. default: return _error->Error("Can't find a match for specified compressor mode for file %s", FileName.c_str());
  720. }
  721. for (; compressor != compressors.end(); ++compressor)
  722. if (compressor->Name == name)
  723. break;
  724. if (compressor == compressors.end() && name != "gzip")
  725. return _error->Error("Can't find a configured compressor %s for file %s", name.c_str(), FileName.c_str());
  726. }
  727. // if we have them, use inbuilt compressors instead of forking
  728. if (compressor != compressors.end())
  729. {
  730. if (compressor->Name == "gzip")
  731. {
  732. Compress = Gzip;
  733. compressor = compressors.end();
  734. }
  735. else if (compressor->Name == "." || Compress == None)
  736. {
  737. Compress = None;
  738. compressor = compressors.end();
  739. }
  740. }
  741. if ((Mode & Atomic) == Atomic)
  742. {
  743. Flags |= Replace;
  744. char *name = strdup((FileName + ".XXXXXX").c_str());
  745. TemporaryFileName = string(mktemp(name));
  746. free(name);
  747. }
  748. else if ((Mode & (Exclusive | Create)) == (Exclusive | Create))
  749. {
  750. // for atomic, this will be done by rename in Close()
  751. unlink(FileName.c_str());
  752. }
  753. if ((Mode & Empty) == Empty)
  754. {
  755. struct stat Buf;
  756. if (lstat(FileName.c_str(),&Buf) == 0 && S_ISLNK(Buf.st_mode))
  757. unlink(FileName.c_str());
  758. }
  759. if (compressor != compressors.end())
  760. {
  761. if ((Mode & ReadWrite) == ReadWrite)
  762. _error->Error("External compressors like %s do not support readwrite mode for file %s", compressor->Name.c_str(), FileName.c_str());
  763. _error->Error("Forking external compressor %s is not implemented for %s", compressor->Name.c_str(), FileName.c_str());
  764. }
  765. else
  766. {
  767. if (TemporaryFileName.empty() == false)
  768. iFd = open(TemporaryFileName.c_str(), fileflags, Perms);
  769. else
  770. iFd = open(FileName.c_str(), fileflags, Perms);
  771. if (iFd != -1)
  772. {
  773. if (OpenInternDescriptor(Mode, Compress) == false)
  774. {
  775. close (iFd);
  776. iFd = -1;
  777. }
  778. }
  779. }
  780. if (iFd == -1)
  781. return _error->Errno("open",_("Could not open file %s"),FileName.c_str());
  782. this->FileName = FileName;
  783. SetCloseExec(iFd,true);
  784. return true;
  785. }
  786. /*}}}*/
  787. // FileFd::OpenDescriptor - Open a filedescriptor /*{{{*/
  788. // ---------------------------------------------------------------------
  789. /* */
  790. bool FileFd::OpenDescriptor(int Fd, OpenMode Mode, CompressMode Compress, bool AutoClose)
  791. {
  792. Close();
  793. d = new FileFdPrivate;
  794. Flags = (AutoClose) ? FileFd::AutoClose : 0;
  795. iFd = Fd;
  796. if (OpenInternDescriptor(Mode, Compress) == false)
  797. {
  798. if (AutoClose)
  799. close (iFd);
  800. return _error->Errno("gzdopen",_("Could not open file descriptor %d"), Fd);
  801. }
  802. this->FileName = "";
  803. return true;
  804. }
  805. bool FileFd::OpenInternDescriptor(OpenMode Mode, CompressMode Compress)
  806. {
  807. if (Compress == None)
  808. return true;
  809. else if (Compress == Gzip)
  810. {
  811. if ((Mode & ReadWrite) == ReadWrite)
  812. d->gz = gzdopen(iFd, "r+");
  813. else if ((Mode & WriteOnly) == WriteOnly)
  814. d->gz = gzdopen(iFd, "w");
  815. else
  816. d->gz = gzdopen (iFd, "r");
  817. if (d->gz == NULL)
  818. return false;
  819. Flags |= Compressed;
  820. }
  821. else
  822. return false;
  823. return true;
  824. }
  825. /*}}}*/
  826. // FileFd::~File - Closes the file /*{{{*/
  827. // ---------------------------------------------------------------------
  828. /* If the proper modes are selected then we close the Fd and possibly
  829. unlink the file on error. */
  830. FileFd::~FileFd()
  831. {
  832. Close();
  833. }
  834. /*}}}*/
  835. // FileFd::Read - Read a bit of the file /*{{{*/
  836. // ---------------------------------------------------------------------
  837. /* We are carefull to handle interruption by a signal while reading
  838. gracefully. */
  839. bool FileFd::Read(void *To,unsigned long long Size,unsigned long long *Actual)
  840. {
  841. int Res;
  842. errno = 0;
  843. if (Actual != 0)
  844. *Actual = 0;
  845. do
  846. {
  847. if (d->gz != NULL)
  848. Res = gzread(d->gz,To,Size);
  849. else
  850. Res = read(iFd,To,Size);
  851. if (Res < 0 && errno == EINTR)
  852. continue;
  853. if (Res < 0)
  854. {
  855. Flags |= Fail;
  856. return _error->Errno("read",_("Read error"));
  857. }
  858. To = (char *)To + Res;
  859. Size -= Res;
  860. if (Actual != 0)
  861. *Actual += Res;
  862. }
  863. while (Res > 0 && Size > 0);
  864. if (Size == 0)
  865. return true;
  866. // Eof handling
  867. if (Actual != 0)
  868. {
  869. Flags |= HitEof;
  870. return true;
  871. }
  872. Flags |= Fail;
  873. return _error->Error(_("read, still have %llu to read but none left"), Size);
  874. }
  875. /*}}}*/
  876. // FileFd::ReadLine - Read a complete line from the file /*{{{*/
  877. // ---------------------------------------------------------------------
  878. /* Beware: This method can be quiet slow for big buffers on UNcompressed
  879. files because of the naive implementation! */
  880. char* FileFd::ReadLine(char *To, unsigned long long const Size)
  881. {
  882. if (d->gz != NULL)
  883. return gzgets(d->gz, To, Size);
  884. unsigned long long read = 0;
  885. if (Read(To, Size, &read) == false)
  886. return NULL;
  887. char* c = To;
  888. for (; *c != '\n' && *c != '\0' && read != 0; --read, ++c)
  889. ; // find the end of the line
  890. if (*c != '\0')
  891. *c = '\0';
  892. if (read != 0)
  893. Seek(Tell() - read);
  894. return To;
  895. }
  896. /*}}}*/
  897. // FileFd::Write - Write to the file /*{{{*/
  898. // ---------------------------------------------------------------------
  899. /* */
  900. bool FileFd::Write(const void *From,unsigned long long Size)
  901. {
  902. int Res;
  903. errno = 0;
  904. do
  905. {
  906. if (d->gz != NULL)
  907. Res = gzwrite(d->gz,From,Size);
  908. else
  909. Res = write(iFd,From,Size);
  910. if (Res < 0 && errno == EINTR)
  911. continue;
  912. if (Res < 0)
  913. {
  914. Flags |= Fail;
  915. return _error->Errno("write",_("Write error"));
  916. }
  917. From = (char *)From + Res;
  918. Size -= Res;
  919. }
  920. while (Res > 0 && Size > 0);
  921. if (Size == 0)
  922. return true;
  923. Flags |= Fail;
  924. return _error->Error(_("write, still have %llu to write but couldn't"), Size);
  925. }
  926. /*}}}*/
  927. // FileFd::Seek - Seek in the file /*{{{*/
  928. // ---------------------------------------------------------------------
  929. /* */
  930. bool FileFd::Seek(unsigned long long To)
  931. {
  932. int res;
  933. if (d->gz)
  934. res = gzseek(d->gz,To,SEEK_SET);
  935. else
  936. res = lseek(iFd,To,SEEK_SET);
  937. if (res != (signed)To)
  938. {
  939. Flags |= Fail;
  940. return _error->Error("Unable to seek to %llu", To);
  941. }
  942. return true;
  943. }
  944. /*}}}*/
  945. // FileFd::Skip - Seek in the file /*{{{*/
  946. // ---------------------------------------------------------------------
  947. /* */
  948. bool FileFd::Skip(unsigned long long Over)
  949. {
  950. int res;
  951. if (d->gz != NULL)
  952. res = gzseek(d->gz,Over,SEEK_CUR);
  953. else
  954. res = lseek(iFd,Over,SEEK_CUR);
  955. if (res < 0)
  956. {
  957. Flags |= Fail;
  958. return _error->Error("Unable to seek ahead %llu",Over);
  959. }
  960. return true;
  961. }
  962. /*}}}*/
  963. // FileFd::Truncate - Truncate the file /*{{{*/
  964. // ---------------------------------------------------------------------
  965. /* */
  966. bool FileFd::Truncate(unsigned long long To)
  967. {
  968. if (d->gz != NULL)
  969. {
  970. Flags |= Fail;
  971. return _error->Error("Truncating gzipped files is not implemented (%s)", FileName.c_str());
  972. }
  973. if (ftruncate(iFd,To) != 0)
  974. {
  975. Flags |= Fail;
  976. return _error->Error("Unable to truncate to %llu",To);
  977. }
  978. return true;
  979. }
  980. /*}}}*/
  981. // FileFd::Tell - Current seek position /*{{{*/
  982. // ---------------------------------------------------------------------
  983. /* */
  984. unsigned long long FileFd::Tell()
  985. {
  986. off_t Res;
  987. if (d->gz != NULL)
  988. Res = gztell(d->gz);
  989. else
  990. Res = lseek(iFd,0,SEEK_CUR);
  991. if (Res == (off_t)-1)
  992. _error->Errno("lseek","Failed to determine the current file position");
  993. return Res;
  994. }
  995. /*}}}*/
  996. // FileFd::FileSize - Return the size of the file /*{{{*/
  997. // ---------------------------------------------------------------------
  998. /* */
  999. unsigned long long FileFd::FileSize()
  1000. {
  1001. struct stat Buf;
  1002. if (fstat(iFd,&Buf) != 0)
  1003. return _error->Errno("fstat","Unable to determine the file size");
  1004. return Buf.st_size;
  1005. }
  1006. /*}}}*/
  1007. // FileFd::Size - Return the size of the content in the file /*{{{*/
  1008. // ---------------------------------------------------------------------
  1009. /* */
  1010. unsigned long long FileFd::Size()
  1011. {
  1012. unsigned long long size = FileSize();
  1013. // only check gzsize if we are actually a gzip file, just checking for
  1014. // "gz" is not sufficient as uncompressed files could be opened with
  1015. // gzopen in "direct" mode as well
  1016. if (d->gz && !gzdirect(d->gz) && size > 0)
  1017. {
  1018. /* unfortunately zlib.h doesn't provide a gzsize(), so we have to do
  1019. * this ourselves; the original (uncompressed) file size is the last 32
  1020. * bits of the file */
  1021. // FIXME: Size for gz-files is limited by 32bit… no largefile support
  1022. off_t orig_pos = lseek(iFd, 0, SEEK_CUR);
  1023. if (lseek(iFd, -4, SEEK_END) < 0)
  1024. return _error->Errno("lseek","Unable to seek to end of gzipped file");
  1025. size = 0L;
  1026. if (read(iFd, &size, 4) != 4)
  1027. return _error->Errno("read","Unable to read original size of gzipped file");
  1028. #ifdef WORDS_BIGENDIAN
  1029. uint32_t tmp_size = size;
  1030. uint8_t const * const p = (uint8_t const * const) &tmp_size;
  1031. tmp_size = (p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
  1032. size = tmp_size;
  1033. #endif
  1034. if (lseek(iFd, orig_pos, SEEK_SET) < 0)
  1035. return _error->Errno("lseek","Unable to seek in gzipped file");
  1036. return size;
  1037. }
  1038. return size;
  1039. }
  1040. /*}}}*/
  1041. // FileFd::ModificationTime - Return the time of last touch /*{{{*/
  1042. // ---------------------------------------------------------------------
  1043. /* */
  1044. time_t FileFd::ModificationTime()
  1045. {
  1046. struct stat Buf;
  1047. if (fstat(iFd,&Buf) != 0)
  1048. {
  1049. _error->Errno("fstat","Unable to determine the modification time of file %s", FileName.c_str());
  1050. return 0;
  1051. }
  1052. return Buf.st_mtime;
  1053. }
  1054. /*}}}*/
  1055. // FileFd::Close - Close the file if the close flag is set /*{{{*/
  1056. // ---------------------------------------------------------------------
  1057. /* */
  1058. bool FileFd::Close()
  1059. {
  1060. if (iFd == -1)
  1061. return true;
  1062. bool Res = true;
  1063. if ((Flags & AutoClose) == AutoClose)
  1064. {
  1065. if (d != NULL && d->gz != NULL) {
  1066. int const e = gzclose(d->gz);
  1067. // gzdopen() on empty files always fails with "buffer error" here, ignore that
  1068. if (e != 0 && e != Z_BUF_ERROR)
  1069. Res &= _error->Errno("close",_("Problem closing the gzip file %s"), FileName.c_str());
  1070. } else
  1071. if (iFd > 0 && close(iFd) != 0)
  1072. Res &= _error->Errno("close",_("Problem closing the file %s"), FileName.c_str());
  1073. }
  1074. if ((Flags & Replace) == Replace && iFd >= 0) {
  1075. if (rename(TemporaryFileName.c_str(), FileName.c_str()) != 0)
  1076. Res &= _error->Errno("rename",_("Problem renaming the file %s to %s"), TemporaryFileName.c_str(), FileName.c_str());
  1077. FileName = TemporaryFileName; // for the unlink() below.
  1078. TemporaryFileName.clear();
  1079. }
  1080. iFd = -1;
  1081. if ((Flags & Fail) == Fail && (Flags & DelOnFail) == DelOnFail &&
  1082. FileName.empty() == false)
  1083. if (unlink(FileName.c_str()) != 0)
  1084. Res &= _error->WarningE("unlnk",_("Problem unlinking the file %s"), FileName.c_str());
  1085. if (d != NULL)
  1086. {
  1087. delete d;
  1088. d = NULL;
  1089. }
  1090. return Res;
  1091. }
  1092. /*}}}*/
  1093. // FileFd::Sync - Sync the file /*{{{*/
  1094. // ---------------------------------------------------------------------
  1095. /* */
  1096. bool FileFd::Sync()
  1097. {
  1098. #ifdef _POSIX_SYNCHRONIZED_IO
  1099. if (fsync(iFd) != 0)
  1100. return _error->Errno("sync",_("Problem syncing the file"));
  1101. #endif
  1102. return true;
  1103. }
  1104. /*}}}*/
  1105. gzFile FileFd::gzFd() {return d->gz;};