extracttar.cc 10 KB

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