acquire-item.cc 54 KB

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