extracttar.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: extracttar.cc,v 1.8.2.1 2004/01/16 18:58:50 mdz Exp $
  4. /* ######################################################################
  5. Extract a Tar - Tar Extractor
  6. Some performance measurements showed that zlib performed quite poorly
  7. in comparison to a forked gzip process. This tar extractor makes use
  8. of the fact that dup'd file descriptors have the same seek pointer
  9. and that gzip will not read past the end of a compressed stream,
  10. even if there is more data. We use the dup property to track extraction
  11. progress and the gzip feature to just feed gzip a fd in the middle
  12. of an AR file.
  13. ##################################################################### */
  14. /*}}}*/
  15. // Include Files /*{{{*/
  16. #include<config.h>
  17. #include <apt-pkg/dirstream.h>
  18. #include <apt-pkg/extracttar.h>
  19. #include <apt-pkg/error.h>
  20. #include <apt-pkg/strutl.h>
  21. #include <apt-pkg/configuration.h>
  22. #include <apt-pkg/fileutl.h>
  23. #include <string.h>
  24. #include <algorithm>
  25. #include <string>
  26. #include <unistd.h>
  27. #include <signal.h>
  28. #include <fcntl.h>
  29. #include <iostream>
  30. #include <apti18n.h>
  31. /*}}}*/
  32. using namespace std;
  33. // The on disk header for a tar file.
  34. struct ExtractTar::TarHeader
  35. {
  36. char Name[100];
  37. char Mode[8];
  38. char UserID[8];
  39. char GroupID[8];
  40. char Size[12];
  41. char MTime[12];
  42. char Checksum[8];
  43. char LinkFlag;
  44. char LinkName[100];
  45. char MagicNumber[8];
  46. char UserName[32];
  47. char GroupName[32];
  48. char Major[8];
  49. char Minor[8];
  50. };
  51. // ExtractTar::ExtractTar - Constructor /*{{{*/
  52. // ---------------------------------------------------------------------
  53. /* */
  54. #if APT_PKG_ABI >= 413
  55. ExtractTar::ExtractTar(FileFd &Fd,unsigned long long Max,string DecompressionProgram)
  56. : File(Fd), MaxInSize(Max), DecompressProg(DecompressionProgram)
  57. #else
  58. ExtractTar::ExtractTar(FileFd &Fd,unsigned long Max,string DecompressionProgram)
  59. : File(Fd), MaxInSize(Max), DecompressProg(DecompressionProgram)
  60. #endif
  61. {
  62. GZPid = -1;
  63. Eof = false;
  64. }
  65. /*}}}*/
  66. // ExtractTar::ExtractTar - Destructor /*{{{*/
  67. // ---------------------------------------------------------------------
  68. /* */
  69. ExtractTar::~ExtractTar()
  70. {
  71. // Error close
  72. Done(true);
  73. }
  74. /*}}}*/
  75. // ExtractTar::Done - Reap the gzip sub process /*{{{*/
  76. // ---------------------------------------------------------------------
  77. /* If the force flag is given then error messages are suppressed - this
  78. means we hit the end of the tar file but there was still gzip data. */
  79. bool ExtractTar::Done(bool Force)
  80. {
  81. InFd.Close();
  82. if (GZPid <= 0)
  83. return true;
  84. /* If there is a pending error then we are cleaning up gzip and are
  85. not interested in it's failures */
  86. if (_error->PendingError() == true)
  87. Force = true;
  88. // Make sure we clean it up!
  89. kill(GZPid,SIGINT);
  90. string confvar = string("dir::bin::") + DecompressProg;
  91. if (ExecWait(GZPid,_config->Find(confvar.c_str(),DecompressProg.c_str()).c_str(),
  92. Force) == false)
  93. {
  94. GZPid = -1;
  95. return Force;
  96. }
  97. GZPid = -1;
  98. return true;
  99. }
  100. /*}}}*/
  101. // ExtractTar::StartGzip - Startup gzip /*{{{*/
  102. // ---------------------------------------------------------------------
  103. /* This creates a gzip sub process that has its input as the file itself.
  104. If this tar file is embedded into something like an ar file then
  105. gzip will efficiently ignore the extra bits. */
  106. bool ExtractTar::StartGzip()
  107. {
  108. if (DecompressProg.empty())
  109. {
  110. InFd.OpenDescriptor(File.Fd(), FileFd::ReadOnly, FileFd::None, false);
  111. return true;
  112. }
  113. int Pipes[2];
  114. if (pipe(Pipes) != 0)
  115. return _error->Errno("pipe",_("Failed to create pipes"));
  116. // Fork off the process
  117. GZPid = ExecFork();
  118. // Spawn the subprocess
  119. if (GZPid == 0)
  120. {
  121. // Setup the FDs
  122. dup2(Pipes[1],STDOUT_FILENO);
  123. dup2(File.Fd(),STDIN_FILENO);
  124. int Fd = open("/dev/null",O_RDWR);
  125. if (Fd == -1)
  126. _exit(101);
  127. dup2(Fd,STDERR_FILENO);
  128. close(Fd);
  129. SetCloseExec(STDOUT_FILENO,false);
  130. SetCloseExec(STDIN_FILENO,false);
  131. SetCloseExec(STDERR_FILENO,false);
  132. const char *Args[3];
  133. string confvar = string("dir::bin::") + DecompressProg;
  134. string argv0 = _config->Find(confvar.c_str(),DecompressProg.c_str());
  135. Args[0] = argv0.c_str();
  136. Args[1] = "-d";
  137. Args[2] = 0;
  138. execvp(Args[0],(char **)Args);
  139. cerr << _("Failed to exec gzip ") << Args[0] << endl;
  140. _exit(100);
  141. }
  142. // Fix up our FDs
  143. InFd.OpenDescriptor(Pipes[0], FileFd::ReadOnly, FileFd::None, true);
  144. close(Pipes[1]);
  145. return true;
  146. }
  147. /*}}}*/
  148. // ExtractTar::Go - Perform extraction /*{{{*/
  149. // ---------------------------------------------------------------------
  150. /* This reads each 512 byte block from the archive and extracts the header
  151. information into the Item structure. Then it resolves the UID/GID and
  152. invokes the correct processing function. */
  153. bool ExtractTar::Go(pkgDirStream &Stream)
  154. {
  155. if (StartGzip() == false)
  156. return false;
  157. // Loop over all blocks
  158. string LastLongLink, ItemLink;
  159. string LastLongName, ItemName;
  160. while (1)
  161. {
  162. bool BadRecord = false;
  163. unsigned char Block[512];
  164. if (InFd.Read(Block,sizeof(Block),true) == false)
  165. return false;
  166. if (InFd.Eof() == true)
  167. break;
  168. // Get the checksum
  169. TarHeader *Tar = (TarHeader *)Block;
  170. unsigned long CheckSum;
  171. if (StrToNum(Tar->Checksum,CheckSum,sizeof(Tar->Checksum),8) == false)
  172. return _error->Error(_("Corrupted archive"));
  173. /* Compute the checksum field. The actual checksum is blanked out
  174. with spaces so it is not included in the computation */
  175. unsigned long NewSum = 0;
  176. memset(Tar->Checksum,' ',sizeof(Tar->Checksum));
  177. for (int I = 0; I != sizeof(Block); I++)
  178. NewSum += Block[I];
  179. /* Check for a block of nulls - in this case we kill gzip, GNU tar
  180. does this.. */
  181. if (NewSum == ' '*sizeof(Tar->Checksum))
  182. return Done(true);
  183. if (NewSum != CheckSum)
  184. return _error->Error(_("Tar checksum failed, archive corrupted"));
  185. // Decode all of the fields
  186. pkgDirStream::Item Itm;
  187. if (StrToNum(Tar->Mode,Itm.Mode,sizeof(Tar->Mode),8) == false ||
  188. (Base256ToNum(Tar->UserID,Itm.UID,8) == false &&
  189. StrToNum(Tar->UserID,Itm.UID,sizeof(Tar->UserID),8) == false) ||
  190. (Base256ToNum(Tar->GroupID,Itm.GID,8) == false &&
  191. StrToNum(Tar->GroupID,Itm.GID,sizeof(Tar->GroupID),8) == false) ||
  192. (Base256ToNum(Tar->Size,Itm.Size,12) == false &&
  193. StrToNum(Tar->Size,Itm.Size,sizeof(Tar->Size),8) == false) ||
  194. (Base256ToNum(Tar->MTime,Itm.MTime,12) == false &&
  195. StrToNum(Tar->MTime,Itm.MTime,sizeof(Tar->MTime),8) == false) ||
  196. StrToNum(Tar->Major,Itm.Major,sizeof(Tar->Major),8) == false ||
  197. StrToNum(Tar->Minor,Itm.Minor,sizeof(Tar->Minor),8) == false)
  198. return _error->Error(_("Corrupted archive"));
  199. // Grab the filename and link target: use last long name if one was
  200. // set, otherwise use the header value as-is, but remember that it may
  201. // fill the entire 100-byte block and needs to be zero-terminated.
  202. // See Debian Bug #689582.
  203. if (LastLongName.empty() == false)
  204. Itm.Name = (char *)LastLongName.c_str();
  205. else
  206. Itm.Name = (char *)ItemName.assign(Tar->Name, sizeof(Tar->Name)).c_str();
  207. if (Itm.Name[0] == '.' && Itm.Name[1] == '/' && Itm.Name[2] != 0)
  208. Itm.Name += 2;
  209. if (LastLongLink.empty() == false)
  210. Itm.LinkTarget = (char *)LastLongLink.c_str();
  211. else
  212. Itm.LinkTarget = (char *)ItemLink.assign(Tar->LinkName, sizeof(Tar->LinkName)).c_str();
  213. // Convert the type over
  214. switch (Tar->LinkFlag)
  215. {
  216. case NormalFile0:
  217. case NormalFile:
  218. Itm.Type = pkgDirStream::Item::File;
  219. break;
  220. case HardLink:
  221. Itm.Type = pkgDirStream::Item::HardLink;
  222. break;
  223. case SymbolicLink:
  224. Itm.Type = pkgDirStream::Item::SymbolicLink;
  225. break;
  226. case CharacterDevice:
  227. Itm.Type = pkgDirStream::Item::CharDevice;
  228. break;
  229. case BlockDevice:
  230. Itm.Type = pkgDirStream::Item::BlockDevice;
  231. break;
  232. case Directory:
  233. Itm.Type = pkgDirStream::Item::Directory;
  234. break;
  235. case FIFO:
  236. Itm.Type = pkgDirStream::Item::FIFO;
  237. break;
  238. case GNU_LongLink:
  239. {
  240. unsigned long long Length = Itm.Size;
  241. unsigned char Block[512];
  242. while (Length > 0)
  243. {
  244. if (InFd.Read(Block,sizeof(Block),true) == false)
  245. return false;
  246. if (Length <= sizeof(Block))
  247. {
  248. LastLongLink.append(Block,Block+sizeof(Block));
  249. break;
  250. }
  251. LastLongLink.append(Block,Block+sizeof(Block));
  252. Length -= sizeof(Block);
  253. }
  254. continue;
  255. }
  256. case GNU_LongName:
  257. {
  258. unsigned long long Length = Itm.Size;
  259. unsigned char Block[512];
  260. while (Length > 0)
  261. {
  262. if (InFd.Read(Block,sizeof(Block),true) == false)
  263. return false;
  264. if (Length < sizeof(Block))
  265. {
  266. LastLongName.append(Block,Block+sizeof(Block));
  267. break;
  268. }
  269. LastLongName.append(Block,Block+sizeof(Block));
  270. Length -= sizeof(Block);
  271. }
  272. continue;
  273. }
  274. default:
  275. BadRecord = true;
  276. _error->Warning(_("Unknown TAR header type %u, member %s"),(unsigned)Tar->LinkFlag,Tar->Name);
  277. break;
  278. }
  279. int Fd = -1;
  280. if (BadRecord == false)
  281. if (Stream.DoItem(Itm,Fd) == false)
  282. return false;
  283. // Copy the file over the FD
  284. unsigned long long Size = Itm.Size;
  285. while (Size != 0)
  286. {
  287. unsigned char Junk[32*1024];
  288. unsigned long Read = min(Size, (unsigned long long)sizeof(Junk));
  289. if (InFd.Read(Junk,((Read+511)/512)*512) == false)
  290. return false;
  291. if (BadRecord == false)
  292. {
  293. if (Fd > 0)
  294. {
  295. if (write(Fd,Junk,Read) != (signed)Read)
  296. return Stream.Fail(Itm,Fd);
  297. }
  298. else
  299. {
  300. /* An Fd of -2 means to send to a special processing
  301. function */
  302. if (Fd == -2)
  303. if (Stream.Process(Itm,Junk,Read,Itm.Size - Size) == false)
  304. return Stream.Fail(Itm,Fd);
  305. }
  306. }
  307. Size -= Read;
  308. }
  309. // And finish up
  310. if (BadRecord == false)
  311. if (Stream.FinishedFile(Itm,Fd) == false)
  312. return false;
  313. LastLongName.erase();
  314. LastLongLink.erase();
  315. }
  316. return Done(false);
  317. }
  318. /*}}}*/