acquire-item.cc 48 KB

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