acquire-item.cc 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: acquire-item.cc,v 1.46.2.9 2004/01/16 18:51:11 mdz Exp $
  4. /* ######################################################################
  5. Acquire Item - Item to acquire
  6. Each item can download to exactly one file at a time. This means you
  7. cannot create an item that fetches two uri's to two files at the same
  8. time. The pkgAcqIndex class creates a second class upon instantiation
  9. to fetch the other index files because of this.
  10. ##################################################################### */
  11. /*}}}*/
  12. // Include Files /*{{{*/
  13. #include <apt-pkg/acquire-item.h>
  14. #include <apt-pkg/configuration.h>
  15. #include <apt-pkg/aptconfiguration.h>
  16. #include <apt-pkg/sourcelist.h>
  17. #include <apt-pkg/vendorlist.h>
  18. #include <apt-pkg/error.h>
  19. #include <apt-pkg/strutl.h>
  20. #include <apt-pkg/fileutl.h>
  21. #include <apt-pkg/md5.h>
  22. #include <apt-pkg/sha1.h>
  23. #include <apt-pkg/tagfile.h>
  24. #include <apti18n.h>
  25. #include <sys/stat.h>
  26. #include <unistd.h>
  27. #include <errno.h>
  28. #include <string>
  29. #include <sstream>
  30. #include <stdio.h>
  31. /*}}}*/
  32. using namespace std;
  33. // Acquire::Item::Item - Constructor /*{{{*/
  34. // ---------------------------------------------------------------------
  35. /* */
  36. pkgAcquire::Item::Item(pkgAcquire *Owner) : Owner(Owner), FileSize(0),
  37. PartialSize(0), Mode(0), ID(0), Complete(false),
  38. Local(false), QueueCounter(0)
  39. {
  40. Owner->Add(this);
  41. Status = StatIdle;
  42. }
  43. /*}}}*/
  44. // Acquire::Item::~Item - Destructor /*{{{*/
  45. // ---------------------------------------------------------------------
  46. /* */
  47. pkgAcquire::Item::~Item()
  48. {
  49. Owner->Remove(this);
  50. }
  51. /*}}}*/
  52. // Acquire::Item::Failed - Item failed to download /*{{{*/
  53. // ---------------------------------------------------------------------
  54. /* We return to an idle state if there are still other queues that could
  55. fetch this object */
  56. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  57. {
  58. Status = StatIdle;
  59. ErrorText = LookupTag(Message,"Message");
  60. if (QueueCounter <= 1)
  61. {
  62. /* This indicates that the file is not available right now but might
  63. be sometime later. If we do a retry cycle then this should be
  64. retried [CDROMs] */
  65. if (Cnf->LocalOnly == true &&
  66. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  67. {
  68. Status = StatIdle;
  69. Dequeue();
  70. return;
  71. }
  72. Status = StatError;
  73. Dequeue();
  74. }
  75. }
  76. /*}}}*/
  77. // Acquire::Item::Start - Item has begun to download /*{{{*/
  78. // ---------------------------------------------------------------------
  79. /* Stash status and the file size. Note that setting Complete means
  80. sub-phases of the acquire process such as decompresion are operating */
  81. void pkgAcquire::Item::Start(string /*Message*/,unsigned long Size)
  82. {
  83. Status = StatFetching;
  84. if (FileSize == 0 && Complete == false)
  85. FileSize = Size;
  86. }
  87. /*}}}*/
  88. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  89. // ---------------------------------------------------------------------
  90. /* */
  91. void pkgAcquire::Item::Done(string Message,unsigned long Size,string Hash,
  92. pkgAcquire::MethodConfig *Cnf)
  93. {
  94. // We just downloaded something..
  95. string FileName = LookupTag(Message,"Filename");
  96. // we only inform the Log class if it was actually not a local thing
  97. if (Complete == false && !Local && FileName == DestFile)
  98. {
  99. if (Owner->Log != 0)
  100. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  101. }
  102. if (FileSize == 0)
  103. FileSize= Size;
  104. Status = StatDone;
  105. ErrorText = string();
  106. Owner->Dequeue(this);
  107. }
  108. /*}}}*/
  109. // Acquire::Item::Rename - Rename a file /*{{{*/
  110. // ---------------------------------------------------------------------
  111. /* This helper function is used by alot of item methods as thier final
  112. step */
  113. void pkgAcquire::Item::Rename(string From,string To)
  114. {
  115. if (rename(From.c_str(),To.c_str()) != 0)
  116. {
  117. char S[300];
  118. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  119. From.c_str(),To.c_str());
  120. Status = StatError;
  121. ErrorText = S;
  122. }
  123. }
  124. /*}}}*/
  125. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  126. // ---------------------------------------------------------------------
  127. /* Get the DiffIndex file first and see if there are patches availabe
  128. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  129. * patches. If anything goes wrong in that process, it will fall back to
  130. * the original packages file
  131. */
  132. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  133. string URI,string URIDesc,string ShortDesc,
  134. HashString ExpectedHash)
  135. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  136. Description(URIDesc)
  137. {
  138. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  139. Desc.Description = URIDesc + "/DiffIndex";
  140. Desc.Owner = this;
  141. Desc.ShortDesc = ShortDesc;
  142. Desc.URI = URI + ".diff/Index";
  143. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  144. DestFile += URItoFileName(URI) + string(".DiffIndex");
  145. if(Debug)
  146. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  147. // look for the current package file
  148. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  149. CurrentPackagesFile += URItoFileName(RealURI);
  150. // FIXME: this file:/ check is a hack to prevent fetching
  151. // from local sources. this is really silly, and
  152. // should be fixed cleanly as soon as possible
  153. if(!FileExists(CurrentPackagesFile) ||
  154. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  155. {
  156. // we don't have a pkg file or we don't want to queue
  157. if(Debug)
  158. std::clog << "No index file, local or canceld by user" << std::endl;
  159. Failed("", NULL);
  160. return;
  161. }
  162. if(Debug)
  163. std::clog << "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
  164. << CurrentPackagesFile << std::endl;
  165. QueueURI(Desc);
  166. }
  167. /*}}}*/
  168. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  169. // ---------------------------------------------------------------------
  170. /* The only header we use is the last-modified header. */
  171. string pkgAcqDiffIndex::Custom600Headers()
  172. {
  173. string Final = _config->FindDir("Dir::State::lists");
  174. Final += URItoFileName(RealURI) + string(".IndexDiff");
  175. if(Debug)
  176. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  177. struct stat Buf;
  178. if (stat(Final.c_str(),&Buf) != 0)
  179. return "\nIndex-File: true";
  180. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  181. }
  182. /*}}}*/
  183. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  184. {
  185. if(Debug)
  186. std::clog << "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
  187. << std::endl;
  188. pkgTagSection Tags;
  189. string ServerSha1;
  190. vector<DiffInfo> available_patches;
  191. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  192. pkgTagFile TF(&Fd);
  193. if (_error->PendingError() == true)
  194. return false;
  195. if(TF.Step(Tags) == true)
  196. {
  197. bool found = false;
  198. DiffInfo d;
  199. string size;
  200. string const tmp = Tags.FindS("SHA1-Current");
  201. std::stringstream ss(tmp);
  202. ss >> ServerSha1 >> size;
  203. unsigned long const ServerSize = atol(size.c_str());
  204. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  205. SHA1Summation SHA1;
  206. SHA1.AddFD(fd.Fd(), fd.Size());
  207. string const local_sha1 = SHA1.Result();
  208. if(local_sha1 == ServerSha1)
  209. {
  210. // we have the same sha1 as the server
  211. if(Debug)
  212. std::clog << "Package file is up-to-date" << std::endl;
  213. // set found to true, this will queue a pkgAcqIndexDiffs with
  214. // a empty availabe_patches
  215. found = true;
  216. }
  217. else
  218. {
  219. if(Debug)
  220. std::clog << "SHA1-Current: " << ServerSha1 << std::endl;
  221. // check the historie and see what patches we need
  222. string const history = Tags.FindS("SHA1-History");
  223. std::stringstream hist(history);
  224. while(hist >> d.sha1 >> size >> d.file)
  225. {
  226. // read until the first match is found
  227. // from that point on, we probably need all diffs
  228. if(d.sha1 == local_sha1)
  229. found=true;
  230. else if (found == false)
  231. continue;
  232. if(Debug)
  233. std::clog << "Need to get diff: " << d.file << std::endl;
  234. available_patches.push_back(d);
  235. }
  236. if (available_patches.empty() == false)
  237. {
  238. // patching with too many files is rather slow compared to a fast download
  239. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  240. if (fileLimit != 0 && fileLimit < available_patches.size())
  241. {
  242. if (Debug)
  243. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  244. << ") so fallback to complete download" << std::endl;
  245. return false;
  246. }
  247. // see if the patches are too big
  248. found = false; // it was true and it will be true again at the end
  249. d = *available_patches.begin();
  250. string const firstPatch = d.file;
  251. unsigned long patchesSize = 0;
  252. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  253. while(patches >> d.sha1 >> size >> d.file)
  254. {
  255. if (firstPatch == d.file)
  256. found = true;
  257. else if (found == false)
  258. continue;
  259. patchesSize += atol(size.c_str());
  260. }
  261. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  262. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  263. {
  264. if (Debug)
  265. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  266. << ") so fallback to complete download" << std::endl;
  267. return false;
  268. }
  269. }
  270. }
  271. // we have something, queue the next diff
  272. if(found)
  273. {
  274. // queue the diffs
  275. string::size_type const last_space = Description.rfind(" ");
  276. if(last_space != string::npos)
  277. Description.erase(last_space, Description.size()-last_space);
  278. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  279. ExpectedHash, available_patches);
  280. Complete = false;
  281. Status = StatDone;
  282. Dequeue();
  283. return true;
  284. }
  285. }
  286. // Nothing found, report and return false
  287. // Failing here is ok, if we return false later, the full
  288. // IndexFile is queued
  289. if(Debug)
  290. std::clog << "Can't find a patch in the index file" << std::endl;
  291. return false;
  292. }
  293. /*}}}*/
  294. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  295. {
  296. if(Debug)
  297. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
  298. << "Falling back to normal index file aquire" << std::endl;
  299. new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
  300. ExpectedHash);
  301. Complete = false;
  302. Status = StatDone;
  303. Dequeue();
  304. }
  305. /*}}}*/
  306. void pkgAcqDiffIndex::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  307. pkgAcquire::MethodConfig *Cnf)
  308. {
  309. if(Debug)
  310. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  311. Item::Done(Message,Size,Md5Hash,Cnf);
  312. string FinalFile;
  313. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  314. // sucess in downloading the index
  315. // rename the index
  316. FinalFile += string(".IndexDiff");
  317. if(Debug)
  318. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  319. << std::endl;
  320. Rename(DestFile,FinalFile);
  321. chmod(FinalFile.c_str(),0644);
  322. DestFile = FinalFile;
  323. if(!ParseDiffIndex(DestFile))
  324. return Failed("", NULL);
  325. Complete = true;
  326. Status = StatDone;
  327. Dequeue();
  328. return;
  329. }
  330. /*}}}*/
  331. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  332. // ---------------------------------------------------------------------
  333. /* The package diff is added to the queue. one object is constructed
  334. * for each diff and the index
  335. */
  336. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  337. string URI,string URIDesc,string ShortDesc,
  338. HashString ExpectedHash,
  339. vector<DiffInfo> diffs)
  340. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  341. available_patches(diffs)
  342. {
  343. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  344. DestFile += URItoFileName(URI);
  345. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  346. Description = URIDesc;
  347. Desc.Owner = this;
  348. Desc.ShortDesc = ShortDesc;
  349. if(available_patches.size() == 0)
  350. {
  351. // we are done (yeah!)
  352. Finish(true);
  353. }
  354. else
  355. {
  356. // get the next diff
  357. State = StateFetchDiff;
  358. QueueNextDiff();
  359. }
  360. }
  361. /*}}}*/
  362. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  363. {
  364. if(Debug)
  365. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
  366. << "Falling back to normal index file aquire" << std::endl;
  367. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  368. ExpectedHash);
  369. Finish();
  370. }
  371. /*}}}*/
  372. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  373. void pkgAcqIndexDiffs::Finish(bool allDone)
  374. {
  375. // we restore the original name, this is required, otherwise
  376. // the file will be cleaned
  377. if(allDone)
  378. {
  379. DestFile = _config->FindDir("Dir::State::lists");
  380. DestFile += URItoFileName(RealURI);
  381. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  382. {
  383. Status = StatAuthError;
  384. ErrorText = _("MD5Sum mismatch");
  385. Rename(DestFile,DestFile + ".FAILED");
  386. Dequeue();
  387. return;
  388. }
  389. // this is for the "real" finish
  390. Complete = true;
  391. Status = StatDone;
  392. Dequeue();
  393. if(Debug)
  394. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  395. return;
  396. }
  397. if(Debug)
  398. std::clog << "Finishing: " << Desc.URI << std::endl;
  399. Complete = false;
  400. Status = StatDone;
  401. Dequeue();
  402. return;
  403. }
  404. /*}}}*/
  405. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  406. {
  407. // calc sha1 of the just patched file
  408. string FinalFile = _config->FindDir("Dir::State::lists");
  409. FinalFile += URItoFileName(RealURI);
  410. FileFd fd(FinalFile, FileFd::ReadOnly);
  411. SHA1Summation SHA1;
  412. SHA1.AddFD(fd.Fd(), fd.Size());
  413. string local_sha1 = string(SHA1.Result());
  414. if(Debug)
  415. std::clog << "QueueNextDiff: "
  416. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  417. // remove all patches until the next matching patch is found
  418. // this requires the Index file to be ordered
  419. for(vector<DiffInfo>::iterator I=available_patches.begin();
  420. available_patches.size() > 0 &&
  421. I != available_patches.end() &&
  422. (*I).sha1 != local_sha1;
  423. I++)
  424. {
  425. available_patches.erase(I);
  426. }
  427. // error checking and falling back if no patch was found
  428. if(available_patches.size() == 0)
  429. {
  430. Failed("", NULL);
  431. return false;
  432. }
  433. // queue the right diff
  434. Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
  435. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  436. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  437. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  438. if(Debug)
  439. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  440. QueueURI(Desc);
  441. return true;
  442. }
  443. /*}}}*/
  444. void pkgAcqIndexDiffs::Done(string Message,unsigned long Size,string Md5Hash, /*{{{*/
  445. pkgAcquire::MethodConfig *Cnf)
  446. {
  447. if(Debug)
  448. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  449. Item::Done(Message,Size,Md5Hash,Cnf);
  450. string FinalFile;
  451. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  452. // sucess in downloading a diff, enter ApplyDiff state
  453. if(State == StateFetchDiff)
  454. {
  455. if(Debug)
  456. std::clog << "Sending to gzip method: " << FinalFile << std::endl;
  457. string FileName = LookupTag(Message,"Filename");
  458. State = StateUnzipDiff;
  459. Local = true;
  460. Desc.URI = "gzip:" + FileName;
  461. DestFile += ".decomp";
  462. QueueURI(Desc);
  463. Mode = "gzip";
  464. return;
  465. }
  466. // sucess in downloading a diff, enter ApplyDiff state
  467. if(State == StateUnzipDiff)
  468. {
  469. // rred excepts the patch as $FinalFile.ed
  470. Rename(DestFile,FinalFile+".ed");
  471. if(Debug)
  472. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  473. State = StateApplyDiff;
  474. Local = true;
  475. Desc.URI = "rred:" + FinalFile;
  476. QueueURI(Desc);
  477. Mode = "rred";
  478. return;
  479. }
  480. // success in download/apply a diff, queue next (if needed)
  481. if(State == StateApplyDiff)
  482. {
  483. // remove the just applied patch
  484. available_patches.erase(available_patches.begin());
  485. // move into place
  486. if(Debug)
  487. {
  488. std::clog << "Moving patched file in place: " << std::endl
  489. << DestFile << " -> " << FinalFile << std::endl;
  490. }
  491. Rename(DestFile,FinalFile);
  492. chmod(FinalFile.c_str(),0644);
  493. // see if there is more to download
  494. if(available_patches.size() > 0) {
  495. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  496. ExpectedHash, available_patches);
  497. return Finish();
  498. } else
  499. return Finish(true);
  500. }
  501. }
  502. /*}}}*/
  503. // AcqIndex::AcqIndex - Constructor /*{{{*/
  504. // ---------------------------------------------------------------------
  505. /* The package file is added to the queue and a second class is
  506. instantiated to fetch the revision file */
  507. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  508. string URI,string URIDesc,string ShortDesc,
  509. HashString ExpectedHash, string comprExt)
  510. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
  511. {
  512. Decompression = false;
  513. Erase = false;
  514. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  515. DestFile += URItoFileName(URI);
  516. if(comprExt.empty())
  517. {
  518. // autoselect the compression method
  519. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  520. if (types.empty() == true)
  521. comprExt = "plain";
  522. else
  523. comprExt = "." + types[0];
  524. }
  525. CompressionExtension = ((comprExt == "plain" || comprExt == ".") ? "" : comprExt);
  526. Desc.URI = URI + CompressionExtension;
  527. Desc.Description = URIDesc;
  528. Desc.Owner = this;
  529. Desc.ShortDesc = ShortDesc;
  530. QueueURI(Desc);
  531. }
  532. /*}}}*/
  533. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  534. // ---------------------------------------------------------------------
  535. /* The only header we use is the last-modified header. */
  536. string pkgAcqIndex::Custom600Headers()
  537. {
  538. string Final = _config->FindDir("Dir::State::lists");
  539. Final += URItoFileName(RealURI);
  540. struct stat Buf;
  541. if (stat(Final.c_str(),&Buf) != 0)
  542. return "\nIndex-File: true";
  543. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  544. }
  545. /*}}}*/
  546. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  547. {
  548. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  549. for (std::vector<std::string>::const_iterator t = types.begin();
  550. t != types.end(); t++)
  551. {
  552. // jump over all already tried compression types
  553. const unsigned int nameLen = Desc.URI.size() - (*t).size();
  554. if(Desc.URI.substr(nameLen) != *t)
  555. continue;
  556. // we want to try it with the next extension (and make sure to
  557. // not skip over the end)
  558. t++;
  559. if (t == types.end())
  560. break;
  561. // queue new download
  562. Desc.URI = Desc.URI.substr(0, nameLen) + *t;
  563. new pkgAcqIndex(Owner, RealURI, Desc.Description, Desc.ShortDesc,
  564. ExpectedHash, string(".").append(*t));
  565. Status = StatDone;
  566. Complete = false;
  567. Dequeue();
  568. return;
  569. }
  570. // on decompression failure, remove bad versions in partial/
  571. if(Decompression && Erase) {
  572. string s = _config->FindDir("Dir::State::lists") + "partial/";
  573. s += URItoFileName(RealURI);
  574. unlink(s.c_str());
  575. }
  576. Item::Failed(Message,Cnf);
  577. }
  578. /*}}}*/
  579. // AcqIndex::Done - Finished a fetch /*{{{*/
  580. // ---------------------------------------------------------------------
  581. /* This goes through a number of states.. On the initial fetch the
  582. method could possibly return an alternate filename which points
  583. to the uncompressed version of the file. If this is so the file
  584. is copied into the partial directory. In all other cases the file
  585. is decompressed with a gzip uri. */
  586. void pkgAcqIndex::Done(string Message,unsigned long Size,string Hash,
  587. pkgAcquire::MethodConfig *Cfg)
  588. {
  589. Item::Done(Message,Size,Hash,Cfg);
  590. if (Decompression == true)
  591. {
  592. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  593. {
  594. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  595. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  596. }
  597. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  598. {
  599. Status = StatAuthError;
  600. ErrorText = _("Hash Sum mismatch");
  601. Rename(DestFile,DestFile + ".FAILED");
  602. return;
  603. }
  604. // Done, move it into position
  605. string FinalFile = _config->FindDir("Dir::State::lists");
  606. FinalFile += URItoFileName(RealURI);
  607. Rename(DestFile,FinalFile);
  608. chmod(FinalFile.c_str(),0644);
  609. /* We restore the original name to DestFile so that the clean operation
  610. will work OK */
  611. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  612. DestFile += URItoFileName(RealURI);
  613. // Remove the compressed version.
  614. if (Erase == true)
  615. unlink(DestFile.c_str());
  616. return;
  617. }
  618. Erase = false;
  619. Complete = true;
  620. // Handle the unzipd case
  621. string FileName = LookupTag(Message,"Alt-Filename");
  622. if (FileName.empty() == false)
  623. {
  624. // The files timestamp matches
  625. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  626. return;
  627. Decompression = true;
  628. Local = true;
  629. DestFile += ".decomp";
  630. Desc.URI = "copy:" + FileName;
  631. QueueURI(Desc);
  632. Mode = "copy";
  633. return;
  634. }
  635. FileName = LookupTag(Message,"Filename");
  636. if (FileName.empty() == true)
  637. {
  638. Status = StatError;
  639. ErrorText = "Method gave a blank filename";
  640. }
  641. // The files timestamp matches
  642. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  643. return;
  644. if (FileName == DestFile)
  645. Erase = true;
  646. else
  647. Local = true;
  648. string compExt = flExtension(flNotDir(URI(Desc.URI).Path));
  649. string decompProg;
  650. // get the binary name for your used compression type
  651. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  652. if(decompProg.empty() == false);
  653. // flExtensions returns the full name if no extension is found
  654. // this is why we have this complicated compare operation here
  655. // FIMXE: add a new flJustExtension() that return "" if no
  656. // extension is found and use that above so that it can
  657. // be tested against ""
  658. else if(compExt == flNotDir(URI(Desc.URI).Path))
  659. decompProg = "copy";
  660. else {
  661. _error->Error("Unsupported extension: %s", compExt.c_str());
  662. return;
  663. }
  664. Decompression = true;
  665. DestFile += ".decomp";
  666. Desc.URI = decompProg + ":" + FileName;
  667. QueueURI(Desc);
  668. Mode = decompProg.c_str();
  669. }
  670. /*}}}*/
  671. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  672. // ---------------------------------------------------------------------
  673. /* The Translation file is added to the queue */
  674. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  675. string URI,string URIDesc,string ShortDesc)
  676. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  677. {
  678. }
  679. /*}}}*/
  680. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  681. // ---------------------------------------------------------------------
  682. /* */
  683. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  684. {
  685. if (Cnf->LocalOnly == true ||
  686. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  687. {
  688. // Ignore this
  689. Status = StatDone;
  690. Complete = false;
  691. Dequeue();
  692. return;
  693. }
  694. Item::Failed(Message,Cnf);
  695. }
  696. /*}}}*/
  697. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  698. string URI,string URIDesc,string ShortDesc,
  699. string MetaIndexURI, string MetaIndexURIDesc,
  700. string MetaIndexShortDesc,
  701. const vector<IndexTarget*>* IndexTargets,
  702. indexRecords* MetaIndexParser) :
  703. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  704. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  705. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  706. {
  707. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  708. DestFile += URItoFileName(URI);
  709. // remove any partial downloaded sig-file in partial/.
  710. // it may confuse proxies and is too small to warrant a
  711. // partial download anyway
  712. unlink(DestFile.c_str());
  713. // Create the item
  714. Desc.Description = URIDesc;
  715. Desc.Owner = this;
  716. Desc.ShortDesc = ShortDesc;
  717. Desc.URI = URI;
  718. string Final = _config->FindDir("Dir::State::lists");
  719. Final += URItoFileName(RealURI);
  720. struct stat Buf;
  721. if (stat(Final.c_str(),&Buf) == 0)
  722. {
  723. // File was already in place. It needs to be re-downloaded/verified
  724. // because Release might have changed, we do give it a differnt
  725. // name than DestFile because otherwise the http method will
  726. // send If-Range requests and there are too many broken servers
  727. // out there that do not understand them
  728. LastGoodSig = DestFile+".reverify";
  729. Rename(Final,LastGoodSig);
  730. }
  731. QueueURI(Desc);
  732. }
  733. /*}}}*/
  734. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  735. // ---------------------------------------------------------------------
  736. /* The only header we use is the last-modified header. */
  737. string pkgAcqMetaSig::Custom600Headers()
  738. {
  739. struct stat Buf;
  740. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  741. return "\nIndex-File: true";
  742. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  743. }
  744. void pkgAcqMetaSig::Done(string Message,unsigned long Size,string MD5,
  745. pkgAcquire::MethodConfig *Cfg)
  746. {
  747. Item::Done(Message,Size,MD5,Cfg);
  748. string FileName = LookupTag(Message,"Filename");
  749. if (FileName.empty() == true)
  750. {
  751. Status = StatError;
  752. ErrorText = "Method gave a blank filename";
  753. return;
  754. }
  755. if (FileName != DestFile)
  756. {
  757. // We have to copy it into place
  758. Local = true;
  759. Desc.URI = "copy:" + FileName;
  760. QueueURI(Desc);
  761. return;
  762. }
  763. Complete = true;
  764. // put the last known good file back on i-m-s hit (it will
  765. // be re-verified again)
  766. // Else do nothing, we have the new file in DestFile then
  767. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  768. Rename(LastGoodSig, DestFile);
  769. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  770. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  771. DestFile, IndexTargets, MetaIndexParser);
  772. }
  773. /*}}}*/
  774. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  775. {
  776. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  777. // if we get a network error we fail gracefully
  778. if(Status == StatTransientNetworkError)
  779. {
  780. Item::Failed(Message,Cnf);
  781. // move the sigfile back on transient network failures
  782. if(FileExists(DestFile))
  783. Rename(LastGoodSig,Final);
  784. // set the status back to , Item::Failed likes to reset it
  785. Status = pkgAcquire::Item::StatTransientNetworkError;
  786. return;
  787. }
  788. // Delete any existing sigfile when the acquire failed
  789. unlink(Final.c_str());
  790. // queue a pkgAcqMetaIndex with no sigfile
  791. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  792. "", IndexTargets, MetaIndexParser);
  793. if (Cnf->LocalOnly == true ||
  794. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  795. {
  796. // Ignore this
  797. Status = StatDone;
  798. Complete = false;
  799. Dequeue();
  800. return;
  801. }
  802. Item::Failed(Message,Cnf);
  803. }
  804. /*}}}*/
  805. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  806. string URI,string URIDesc,string ShortDesc,
  807. string SigFile,
  808. const vector<struct IndexTarget*>* IndexTargets,
  809. indexRecords* MetaIndexParser) :
  810. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  811. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  812. {
  813. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  814. DestFile += URItoFileName(URI);
  815. // Create the item
  816. Desc.Description = URIDesc;
  817. Desc.Owner = this;
  818. Desc.ShortDesc = ShortDesc;
  819. Desc.URI = URI;
  820. QueueURI(Desc);
  821. }
  822. /*}}}*/
  823. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  824. // ---------------------------------------------------------------------
  825. /* The only header we use is the last-modified header. */
  826. string pkgAcqMetaIndex::Custom600Headers()
  827. {
  828. string Final = _config->FindDir("Dir::State::lists");
  829. Final += URItoFileName(RealURI);
  830. struct stat Buf;
  831. if (stat(Final.c_str(),&Buf) != 0)
  832. return "\nIndex-File: true";
  833. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  834. }
  835. /*}}}*/
  836. void pkgAcqMetaIndex::Done(string Message,unsigned long Size,string Hash, /*{{{*/
  837. pkgAcquire::MethodConfig *Cfg)
  838. {
  839. Item::Done(Message,Size,Hash,Cfg);
  840. // MetaIndexes are done in two passes: one to download the
  841. // metaindex with an appropriate method, and a second to verify it
  842. // with the gpgv method
  843. if (AuthPass == true)
  844. {
  845. AuthDone(Message);
  846. }
  847. else
  848. {
  849. RetrievalDone(Message);
  850. if (!Complete)
  851. // Still more retrieving to do
  852. return;
  853. if (SigFile == "")
  854. {
  855. // There was no signature file, so we are finished. Download
  856. // the indexes without verification.
  857. QueueIndexes(false);
  858. }
  859. else
  860. {
  861. // There was a signature file, so pass it to gpgv for
  862. // verification
  863. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  864. std::cerr << "Metaindex acquired, queueing gpg verification ("
  865. << SigFile << "," << DestFile << ")\n";
  866. AuthPass = true;
  867. Desc.URI = "gpgv:" + SigFile;
  868. QueueURI(Desc);
  869. Mode = "gpgv";
  870. }
  871. }
  872. }
  873. /*}}}*/
  874. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  875. {
  876. // We have just finished downloading a Release file (it is not
  877. // verified yet)
  878. string FileName = LookupTag(Message,"Filename");
  879. if (FileName.empty() == true)
  880. {
  881. Status = StatError;
  882. ErrorText = "Method gave a blank filename";
  883. return;
  884. }
  885. if (FileName != DestFile)
  886. {
  887. Local = true;
  888. Desc.URI = "copy:" + FileName;
  889. QueueURI(Desc);
  890. return;
  891. }
  892. // see if the download was a IMSHit
  893. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  894. Complete = true;
  895. string FinalFile = _config->FindDir("Dir::State::lists");
  896. FinalFile += URItoFileName(RealURI);
  897. // If we get a IMS hit we can remove the empty file in partial
  898. // othersie we move the file in place
  899. if (IMSHit)
  900. unlink(DestFile.c_str());
  901. else
  902. Rename(DestFile,FinalFile);
  903. chmod(FinalFile.c_str(),0644);
  904. DestFile = FinalFile;
  905. }
  906. /*}}}*/
  907. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  908. {
  909. // At this point, the gpgv method has succeeded, so there is a
  910. // valid signature from a key in the trusted keyring. We
  911. // perform additional verification of its contents, and use them
  912. // to verify the indexes we are about to download
  913. if (!MetaIndexParser->Load(DestFile))
  914. {
  915. Status = StatAuthError;
  916. ErrorText = MetaIndexParser->ErrorText;
  917. return;
  918. }
  919. if (!VerifyVendor(Message))
  920. {
  921. return;
  922. }
  923. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  924. std::cerr << "Signature verification succeeded: "
  925. << DestFile << std::endl;
  926. // Download further indexes with verification
  927. QueueIndexes(true);
  928. // Done, move signature file into position
  929. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  930. URItoFileName(RealURI) + ".gpg";
  931. Rename(SigFile,VerifiedSigFile);
  932. chmod(VerifiedSigFile.c_str(),0644);
  933. }
  934. /*}}}*/
  935. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  936. {
  937. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  938. Target != IndexTargets->end();
  939. Target++)
  940. {
  941. HashString ExpectedIndexHash;
  942. if (verify)
  943. {
  944. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  945. if (!Record)
  946. {
  947. Status = StatAuthError;
  948. ErrorText = "Unable to find expected entry "
  949. + (*Target)->MetaKey + " in Meta-index file (malformed Release file?)";
  950. return;
  951. }
  952. ExpectedIndexHash = Record->Hash;
  953. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  954. {
  955. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  956. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  957. }
  958. if (ExpectedIndexHash.empty())
  959. {
  960. Status = StatAuthError;
  961. ErrorText = "Unable to find hash sum for "
  962. + (*Target)->MetaKey + " in Meta-index file";
  963. return;
  964. }
  965. }
  966. // Queue Packages file (either diff or full packages files, depending
  967. // on the users option)
  968. if(_config->FindB("Acquire::PDiffs",true) == true)
  969. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  970. (*Target)->ShortDesc, ExpectedIndexHash);
  971. else
  972. new pkgAcqIndex(Owner, (*Target)->URI, (*Target)->Description,
  973. (*Target)->ShortDesc, ExpectedIndexHash);
  974. }
  975. }
  976. /*}}}*/
  977. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  978. {
  979. // // Maybe this should be made available from above so we don't have
  980. // // to read and parse it every time?
  981. // pkgVendorList List;
  982. // List.ReadMainList();
  983. // const Vendor* Vndr = NULL;
  984. // for (std::vector<string>::const_iterator I = GPGVOutput.begin(); I != GPGVOutput.end(); I++)
  985. // {
  986. // string::size_type pos = (*I).find("VALIDSIG ");
  987. // if (_config->FindB("Debug::Vendor", false))
  988. // std::cerr << "Looking for VALIDSIG in \"" << (*I) << "\": pos " << pos
  989. // << std::endl;
  990. // if (pos != std::string::npos)
  991. // {
  992. // string Fingerprint = (*I).substr(pos+sizeof("VALIDSIG"));
  993. // if (_config->FindB("Debug::Vendor", false))
  994. // std::cerr << "Looking for \"" << Fingerprint << "\" in vendor..." <<
  995. // std::endl;
  996. // Vndr = List.FindVendor(Fingerprint) != "";
  997. // if (Vndr != NULL);
  998. // break;
  999. // }
  1000. // }
  1001. string::size_type pos;
  1002. // check for missing sigs (that where not fatal because otherwise we had
  1003. // bombed earlier)
  1004. string missingkeys;
  1005. string msg = _("There is no public key available for the "
  1006. "following key IDs:\n");
  1007. pos = Message.find("NO_PUBKEY ");
  1008. if (pos != std::string::npos)
  1009. {
  1010. string::size_type start = pos+strlen("NO_PUBKEY ");
  1011. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1012. missingkeys += (Fingerprint);
  1013. }
  1014. if(!missingkeys.empty())
  1015. _error->Warning("%s", string(msg+missingkeys).c_str());
  1016. string Transformed = MetaIndexParser->GetExpectedDist();
  1017. if (Transformed == "../project/experimental")
  1018. {
  1019. Transformed = "experimental";
  1020. }
  1021. pos = Transformed.rfind('/');
  1022. if (pos != string::npos)
  1023. {
  1024. Transformed = Transformed.substr(0, pos);
  1025. }
  1026. if (Transformed == ".")
  1027. {
  1028. Transformed = "";
  1029. }
  1030. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1031. {
  1032. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1033. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1034. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1035. }
  1036. if (MetaIndexParser->CheckDist(Transformed) == false)
  1037. {
  1038. // This might become fatal one day
  1039. // Status = StatAuthError;
  1040. // ErrorText = "Conflicting distribution; expected "
  1041. // + MetaIndexParser->GetExpectedDist() + " but got "
  1042. // + MetaIndexParser->GetDist();
  1043. // return false;
  1044. if (!Transformed.empty())
  1045. {
  1046. _error->Warning("Conflicting distribution: %s (expected %s but got %s)",
  1047. Desc.Description.c_str(),
  1048. Transformed.c_str(),
  1049. MetaIndexParser->GetDist().c_str());
  1050. }
  1051. }
  1052. return true;
  1053. }
  1054. /*}}}*/
  1055. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1056. // ---------------------------------------------------------------------
  1057. /* */
  1058. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1059. {
  1060. if (AuthPass == true)
  1061. {
  1062. // if we fail the authentication but got the file via a IMS-Hit
  1063. // this means that the file wasn't downloaded and that it might be
  1064. // just stale (server problem, proxy etc). we delete what we have
  1065. // queue it again without i-m-s
  1066. // alternatively we could just unlink the file and let the user try again
  1067. if (IMSHit)
  1068. {
  1069. Complete = false;
  1070. Local = false;
  1071. AuthPass = false;
  1072. unlink(DestFile.c_str());
  1073. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1074. DestFile += URItoFileName(RealURI);
  1075. Desc.URI = RealURI;
  1076. QueueURI(Desc);
  1077. return;
  1078. }
  1079. // gpgv method failed
  1080. _error->Warning("GPG error: %s: %s",
  1081. Desc.Description.c_str(),
  1082. LookupTag(Message,"Message").c_str());
  1083. }
  1084. // No Release file was present, or verification failed, so fall
  1085. // back to queueing Packages files without verification
  1086. QueueIndexes(false);
  1087. }
  1088. /*}}}*/
  1089. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1090. // ---------------------------------------------------------------------
  1091. /* This just sets up the initial fetch environment and queues the first
  1092. possibilitiy */
  1093. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1094. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1095. string &StoreFilename) :
  1096. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1097. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1098. Trusted(false)
  1099. {
  1100. Retries = _config->FindI("Acquire::Retries",0);
  1101. if (Version.Arch() == 0)
  1102. {
  1103. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1104. "This might mean you need to manually fix this package. "
  1105. "(due to missing arch)"),
  1106. Version.ParentPkg().Name());
  1107. return;
  1108. }
  1109. /* We need to find a filename to determine the extension. We make the
  1110. assumption here that all the available sources for this version share
  1111. the same extension.. */
  1112. // Skip not source sources, they do not have file fields.
  1113. for (; Vf.end() == false; Vf++)
  1114. {
  1115. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1116. continue;
  1117. break;
  1118. }
  1119. // Does not really matter here.. we are going to fail out below
  1120. if (Vf.end() != true)
  1121. {
  1122. // If this fails to get a file name we will bomb out below.
  1123. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1124. if (_error->PendingError() == true)
  1125. return;
  1126. // Generate the final file name as: package_version_arch.foo
  1127. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1128. QuoteString(Version.VerStr(),"_:") + '_' +
  1129. QuoteString(Version.Arch(),"_:.") +
  1130. "." + flExtension(Parse.FileName());
  1131. }
  1132. // check if we have one trusted source for the package. if so, switch
  1133. // to "TrustedOnly" mode
  1134. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; i++)
  1135. {
  1136. pkgIndexFile *Index;
  1137. if (Sources->FindIndex(i.File(),Index) == false)
  1138. continue;
  1139. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1140. {
  1141. std::cerr << "Checking index: " << Index->Describe()
  1142. << "(Trusted=" << Index->IsTrusted() << ")\n";
  1143. }
  1144. if (Index->IsTrusted()) {
  1145. Trusted = true;
  1146. break;
  1147. }
  1148. }
  1149. // "allow-unauthenticated" restores apts old fetching behaviour
  1150. // that means that e.g. unauthenticated file:// uris are higher
  1151. // priority than authenticated http:// uris
  1152. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  1153. Trusted = false;
  1154. // Select a source
  1155. if (QueueNext() == false && _error->PendingError() == false)
  1156. _error->Error(_("I wasn't able to locate file for the %s package. "
  1157. "This might mean you need to manually fix this package."),
  1158. Version.ParentPkg().Name());
  1159. }
  1160. /*}}}*/
  1161. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1162. // ---------------------------------------------------------------------
  1163. /* This queues the next available file version for download. It checks if
  1164. the archive is already available in the cache and stashs the MD5 for
  1165. checking later. */
  1166. bool pkgAcqArchive::QueueNext()
  1167. {
  1168. for (; Vf.end() == false; Vf++)
  1169. {
  1170. // Ignore not source sources
  1171. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1172. continue;
  1173. // Try to cross match against the source list
  1174. pkgIndexFile *Index;
  1175. if (Sources->FindIndex(Vf.File(),Index) == false)
  1176. continue;
  1177. // only try to get a trusted package from another source if that source
  1178. // is also trusted
  1179. if(Trusted && !Index->IsTrusted())
  1180. continue;
  1181. // Grab the text package record
  1182. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1183. if (_error->PendingError() == true)
  1184. return false;
  1185. string PkgFile = Parse.FileName();
  1186. if(Parse.SHA256Hash() != "")
  1187. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1188. else if (Parse.SHA1Hash() != "")
  1189. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1190. else
  1191. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1192. if (PkgFile.empty() == true)
  1193. return _error->Error(_("The package index files are corrupted. No Filename: "
  1194. "field for package %s."),
  1195. Version.ParentPkg().Name());
  1196. Desc.URI = Index->ArchiveURI(PkgFile);
  1197. Desc.Description = Index->ArchiveInfo(Version);
  1198. Desc.Owner = this;
  1199. Desc.ShortDesc = Version.ParentPkg().Name();
  1200. // See if we already have the file. (Legacy filenames)
  1201. FileSize = Version->Size;
  1202. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1203. struct stat Buf;
  1204. if (stat(FinalFile.c_str(),&Buf) == 0)
  1205. {
  1206. // Make sure the size matches
  1207. if ((unsigned)Buf.st_size == Version->Size)
  1208. {
  1209. Complete = true;
  1210. Local = true;
  1211. Status = StatDone;
  1212. StoreFilename = DestFile = FinalFile;
  1213. return true;
  1214. }
  1215. /* Hmm, we have a file and its size does not match, this means it is
  1216. an old style mismatched arch */
  1217. unlink(FinalFile.c_str());
  1218. }
  1219. // Check it again using the new style output filenames
  1220. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1221. if (stat(FinalFile.c_str(),&Buf) == 0)
  1222. {
  1223. // Make sure the size matches
  1224. if ((unsigned)Buf.st_size == Version->Size)
  1225. {
  1226. Complete = true;
  1227. Local = true;
  1228. Status = StatDone;
  1229. StoreFilename = DestFile = FinalFile;
  1230. return true;
  1231. }
  1232. /* Hmm, we have a file and its size does not match, this shouldnt
  1233. happen.. */
  1234. unlink(FinalFile.c_str());
  1235. }
  1236. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1237. // Check the destination file
  1238. if (stat(DestFile.c_str(),&Buf) == 0)
  1239. {
  1240. // Hmm, the partial file is too big, erase it
  1241. if ((unsigned)Buf.st_size > Version->Size)
  1242. unlink(DestFile.c_str());
  1243. else
  1244. PartialSize = Buf.st_size;
  1245. }
  1246. // Create the item
  1247. Local = false;
  1248. Desc.URI = Index->ArchiveURI(PkgFile);
  1249. Desc.Description = Index->ArchiveInfo(Version);
  1250. Desc.Owner = this;
  1251. Desc.ShortDesc = Version.ParentPkg().Name();
  1252. QueueURI(Desc);
  1253. Vf++;
  1254. return true;
  1255. }
  1256. return false;
  1257. }
  1258. /*}}}*/
  1259. // AcqArchive::Done - Finished fetching /*{{{*/
  1260. // ---------------------------------------------------------------------
  1261. /* */
  1262. void pkgAcqArchive::Done(string Message,unsigned long Size,string CalcHash,
  1263. pkgAcquire::MethodConfig *Cfg)
  1264. {
  1265. Item::Done(Message,Size,CalcHash,Cfg);
  1266. // Check the size
  1267. if (Size != Version->Size)
  1268. {
  1269. Status = StatError;
  1270. ErrorText = _("Size mismatch");
  1271. return;
  1272. }
  1273. // Check the hash
  1274. if(ExpectedHash.toStr() != CalcHash)
  1275. {
  1276. Status = StatError;
  1277. ErrorText = _("Hash Sum mismatch");
  1278. if(FileExists(DestFile))
  1279. Rename(DestFile,DestFile + ".FAILED");
  1280. return;
  1281. }
  1282. // Grab the output filename
  1283. string FileName = LookupTag(Message,"Filename");
  1284. if (FileName.empty() == true)
  1285. {
  1286. Status = StatError;
  1287. ErrorText = "Method gave a blank filename";
  1288. return;
  1289. }
  1290. Complete = true;
  1291. // Reference filename
  1292. if (FileName != DestFile)
  1293. {
  1294. StoreFilename = DestFile = FileName;
  1295. Local = true;
  1296. return;
  1297. }
  1298. // Done, move it into position
  1299. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1300. FinalFile += flNotDir(StoreFilename);
  1301. Rename(DestFile,FinalFile);
  1302. StoreFilename = DestFile = FinalFile;
  1303. Complete = true;
  1304. }
  1305. /*}}}*/
  1306. // AcqArchive::Failed - Failure handler /*{{{*/
  1307. // ---------------------------------------------------------------------
  1308. /* Here we try other sources */
  1309. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1310. {
  1311. ErrorText = LookupTag(Message,"Message");
  1312. /* We don't really want to retry on failed media swaps, this prevents
  1313. that. An interesting observation is that permanent failures are not
  1314. recorded. */
  1315. if (Cnf->Removable == true &&
  1316. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1317. {
  1318. // Vf = Version.FileList();
  1319. while (Vf.end() == false) Vf++;
  1320. StoreFilename = string();
  1321. Item::Failed(Message,Cnf);
  1322. return;
  1323. }
  1324. if (QueueNext() == false)
  1325. {
  1326. // This is the retry counter
  1327. if (Retries != 0 &&
  1328. Cnf->LocalOnly == false &&
  1329. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1330. {
  1331. Retries--;
  1332. Vf = Version.FileList();
  1333. if (QueueNext() == true)
  1334. return;
  1335. }
  1336. StoreFilename = string();
  1337. Item::Failed(Message,Cnf);
  1338. }
  1339. }
  1340. /*}}}*/
  1341. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1342. // ---------------------------------------------------------------------
  1343. bool pkgAcqArchive::IsTrusted()
  1344. {
  1345. return Trusted;
  1346. }
  1347. /*}}}*/
  1348. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1349. // ---------------------------------------------------------------------
  1350. /* */
  1351. void pkgAcqArchive::Finished()
  1352. {
  1353. if (Status == pkgAcquire::Item::StatDone &&
  1354. Complete == true)
  1355. return;
  1356. StoreFilename = string();
  1357. }
  1358. /*}}}*/
  1359. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1360. // ---------------------------------------------------------------------
  1361. /* The file is added to the queue */
  1362. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1363. unsigned long Size,string Dsc,string ShortDesc,
  1364. const string &DestDir, const string &DestFilename) :
  1365. Item(Owner), ExpectedHash(Hash)
  1366. {
  1367. Retries = _config->FindI("Acquire::Retries",0);
  1368. if(!DestFilename.empty())
  1369. DestFile = DestFilename;
  1370. else if(!DestDir.empty())
  1371. DestFile = DestDir + "/" + flNotDir(URI);
  1372. else
  1373. DestFile = flNotDir(URI);
  1374. // Create the item
  1375. Desc.URI = URI;
  1376. Desc.Description = Dsc;
  1377. Desc.Owner = this;
  1378. // Set the short description to the archive component
  1379. Desc.ShortDesc = ShortDesc;
  1380. // Get the transfer sizes
  1381. FileSize = Size;
  1382. struct stat Buf;
  1383. if (stat(DestFile.c_str(),&Buf) == 0)
  1384. {
  1385. // Hmm, the partial file is too big, erase it
  1386. if ((unsigned)Buf.st_size > Size)
  1387. unlink(DestFile.c_str());
  1388. else
  1389. PartialSize = Buf.st_size;
  1390. }
  1391. QueueURI(Desc);
  1392. }
  1393. /*}}}*/
  1394. // AcqFile::Done - Item downloaded OK /*{{{*/
  1395. // ---------------------------------------------------------------------
  1396. /* */
  1397. void pkgAcqFile::Done(string Message,unsigned long Size,string CalcHash,
  1398. pkgAcquire::MethodConfig *Cnf)
  1399. {
  1400. Item::Done(Message,Size,CalcHash,Cnf);
  1401. // Check the hash
  1402. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1403. {
  1404. Status = StatError;
  1405. ErrorText = "Hash Sum mismatch";
  1406. Rename(DestFile,DestFile + ".FAILED");
  1407. return;
  1408. }
  1409. string FileName = LookupTag(Message,"Filename");
  1410. if (FileName.empty() == true)
  1411. {
  1412. Status = StatError;
  1413. ErrorText = "Method gave a blank filename";
  1414. return;
  1415. }
  1416. Complete = true;
  1417. // The files timestamp matches
  1418. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1419. return;
  1420. // We have to copy it into place
  1421. if (FileName != DestFile)
  1422. {
  1423. Local = true;
  1424. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1425. Cnf->Removable == true)
  1426. {
  1427. Desc.URI = "copy:" + FileName;
  1428. QueueURI(Desc);
  1429. return;
  1430. }
  1431. // Erase the file if it is a symlink so we can overwrite it
  1432. struct stat St;
  1433. if (lstat(DestFile.c_str(),&St) == 0)
  1434. {
  1435. if (S_ISLNK(St.st_mode) != 0)
  1436. unlink(DestFile.c_str());
  1437. }
  1438. // Symlink the file
  1439. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1440. {
  1441. ErrorText = "Link to " + DestFile + " failure ";
  1442. Status = StatError;
  1443. Complete = false;
  1444. }
  1445. }
  1446. }
  1447. /*}}}*/
  1448. // AcqFile::Failed - Failure handler /*{{{*/
  1449. // ---------------------------------------------------------------------
  1450. /* Here we try other sources */
  1451. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1452. {
  1453. ErrorText = LookupTag(Message,"Message");
  1454. // This is the retry counter
  1455. if (Retries != 0 &&
  1456. Cnf->LocalOnly == false &&
  1457. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1458. {
  1459. Retries--;
  1460. QueueURI(Desc);
  1461. return;
  1462. }
  1463. Item::Failed(Message,Cnf);
  1464. }
  1465. /*}}}*/