acquire-item.cc 49 KB

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