acquire-item.cc 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083
  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 <config.h>
  14. #include <apt-pkg/acquire-item.h>
  15. #include <apt-pkg/configuration.h>
  16. #include <apt-pkg/aptconfiguration.h>
  17. #include <apt-pkg/sourcelist.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 <sys/stat.h>
  25. #include <unistd.h>
  26. #include <errno.h>
  27. #include <string>
  28. #include <sstream>
  29. #include <stdio.h>
  30. #include <ctime>
  31. #include <apti18n.h>
  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 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 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. // Acquire::Item::ReportMirrorFailure /*{{{*/
  134. // ---------------------------------------------------------------------
  135. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  136. {
  137. // we only act if a mirror was used at all
  138. if(UsedMirror.empty())
  139. return;
  140. #if 0
  141. std::cerr << "\nReportMirrorFailure: "
  142. << UsedMirror
  143. << " Uri: " << DescURI()
  144. << " FailCode: "
  145. << FailCode << std::endl;
  146. #endif
  147. const char *Args[40];
  148. unsigned int i = 0;
  149. string report = _config->Find("Methods::Mirror::ProblemReporting",
  150. "/usr/lib/apt/apt-report-mirror-failure");
  151. if(!FileExists(report))
  152. return;
  153. Args[i++] = report.c_str();
  154. Args[i++] = UsedMirror.c_str();
  155. Args[i++] = DescURI().c_str();
  156. Args[i++] = FailCode.c_str();
  157. Args[i++] = NULL;
  158. pid_t pid = ExecFork();
  159. if(pid < 0)
  160. {
  161. _error->Error("ReportMirrorFailure Fork failed");
  162. return;
  163. }
  164. else if(pid == 0)
  165. {
  166. execvp(Args[0], (char**)Args);
  167. std::cerr << "Could not exec " << Args[0] << std::endl;
  168. _exit(100);
  169. }
  170. if(!ExecWait(pid, "report-mirror-failure"))
  171. {
  172. _error->Warning("Couldn't report problem to '%s'",
  173. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  174. }
  175. }
  176. /*}}}*/
  177. // AcqSubIndex::AcqSubIndex - Constructor /*{{{*/
  178. // ---------------------------------------------------------------------
  179. /* Get the Index file first and see if there are languages available
  180. * If so, create a pkgAcqIndexTrans for the found language(s).
  181. */
  182. pkgAcqSubIndex::pkgAcqSubIndex(pkgAcquire *Owner, string const &URI,
  183. string const &URIDesc, string const &ShortDesc,
  184. HashString const &ExpectedHash)
  185. : Item(Owner), ExpectedHash(ExpectedHash)
  186. {
  187. Debug = _config->FindB("Debug::pkgAcquire::SubIndex",false);
  188. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  189. DestFile += URItoFileName(URI);
  190. Desc.URI = URI;
  191. Desc.Description = URIDesc;
  192. Desc.Owner = this;
  193. Desc.ShortDesc = ShortDesc;
  194. QueueURI(Desc);
  195. if(Debug)
  196. std::clog << "pkgAcqSubIndex: " << Desc.URI << std::endl;
  197. }
  198. /*}}}*/
  199. // AcqSubIndex::Custom600Headers - Insert custom request headers /*{{{*/
  200. // ---------------------------------------------------------------------
  201. /* The only header we use is the last-modified header. */
  202. string pkgAcqSubIndex::Custom600Headers()
  203. {
  204. string Final = _config->FindDir("Dir::State::lists");
  205. Final += URItoFileName(Desc.URI);
  206. struct stat Buf;
  207. if (stat(Final.c_str(),&Buf) != 0)
  208. return "\nIndex-File: true\nFail-Ignore: true\n";
  209. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  210. }
  211. /*}}}*/
  212. void pkgAcqSubIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  213. {
  214. if(Debug)
  215. std::clog << "pkgAcqSubIndex failed: " << Desc.URI << std::endl;
  216. Complete = false;
  217. Status = StatDone;
  218. Dequeue();
  219. // No good Index is provided, so try guessing
  220. std::vector<std::string> langs = APT::Configuration::getLanguages(true);
  221. for (std::vector<std::string>::const_iterator l = langs.begin();
  222. l != langs.end(); ++l)
  223. {
  224. if (*l == "none") continue;
  225. string const file = "Translation-" + *l;
  226. new pkgAcqIndexTrans(Owner, Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file),
  227. Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file),
  228. file);
  229. }
  230. }
  231. /*}}}*/
  232. void pkgAcqSubIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  233. pkgAcquire::MethodConfig *Cnf)
  234. {
  235. if(Debug)
  236. std::clog << "pkgAcqSubIndex::Done(): " << Desc.URI << std::endl;
  237. string FileName = LookupTag(Message,"Filename");
  238. if (FileName.empty() == true)
  239. {
  240. Status = StatError;
  241. ErrorText = "Method gave a blank filename";
  242. return;
  243. }
  244. if (FileName != DestFile)
  245. {
  246. Local = true;
  247. Desc.URI = "copy:" + FileName;
  248. QueueURI(Desc);
  249. return;
  250. }
  251. Item::Done(Message,Size,Md5Hash,Cnf);
  252. string FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(Desc.URI);
  253. /* Downloaded invalid transindex => Error (LP: #346386) (Closes: #627642) */
  254. indexRecords SubIndexParser;
  255. if (FileExists(DestFile) == true && !SubIndexParser.Load(DestFile)) {
  256. Status = StatError;
  257. ErrorText = SubIndexParser.ErrorText;
  258. return;
  259. }
  260. // sucess in downloading the index
  261. // rename the index
  262. if(Debug)
  263. std::clog << "Renaming: " << DestFile << " -> " << FinalFile << std::endl;
  264. Rename(DestFile,FinalFile);
  265. chmod(FinalFile.c_str(),0644);
  266. DestFile = FinalFile;
  267. if(ParseIndex(DestFile) == false)
  268. return Failed("", NULL);
  269. Complete = true;
  270. Status = StatDone;
  271. Dequeue();
  272. return;
  273. }
  274. /*}}}*/
  275. bool pkgAcqSubIndex::ParseIndex(string const &IndexFile) /*{{{*/
  276. {
  277. indexRecords SubIndexParser;
  278. if (FileExists(IndexFile) == false || SubIndexParser.Load(IndexFile) == false)
  279. return false;
  280. std::vector<std::string> lang = APT::Configuration::getLanguages(true);
  281. for (std::vector<std::string>::const_iterator l = lang.begin();
  282. l != lang.end(); ++l)
  283. {
  284. if (*l == "none")
  285. continue;
  286. string file = "Translation-" + *l;
  287. indexRecords::checkSum const *Record = SubIndexParser.Lookup(file);
  288. HashString expected;
  289. if (Record == NULL)
  290. {
  291. // FIXME: the Index file provided by debian currently only includes bz2 records
  292. Record = SubIndexParser.Lookup(file + ".bz2");
  293. if (Record == NULL)
  294. continue;
  295. }
  296. else
  297. {
  298. expected = Record->Hash;
  299. if (expected.empty() == true)
  300. continue;
  301. }
  302. IndexTarget target;
  303. target.Description = Desc.Description.erase(Desc.Description.rfind(' ')+1).append(file);
  304. target.MetaKey = file;
  305. target.ShortDesc = file;
  306. target.URI = Desc.URI.substr(0, Desc.URI.rfind('/')+1).append(file);
  307. new pkgAcqIndexTrans(Owner, &target, expected, &SubIndexParser);
  308. }
  309. return true;
  310. }
  311. /*}}}*/
  312. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  313. // ---------------------------------------------------------------------
  314. /* Get the DiffIndex file first and see if there are patches availabe
  315. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  316. * patches. If anything goes wrong in that process, it will fall back to
  317. * the original packages file
  318. */
  319. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  320. string URI,string URIDesc,string ShortDesc,
  321. HashString ExpectedHash)
  322. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  323. Description(URIDesc)
  324. {
  325. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  326. Desc.Description = URIDesc + "/DiffIndex";
  327. Desc.Owner = this;
  328. Desc.ShortDesc = ShortDesc;
  329. Desc.URI = URI + ".diff/Index";
  330. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  331. DestFile += URItoFileName(URI) + string(".DiffIndex");
  332. if(Debug)
  333. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  334. // look for the current package file
  335. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  336. CurrentPackagesFile += URItoFileName(RealURI);
  337. // FIXME: this file:/ check is a hack to prevent fetching
  338. // from local sources. this is really silly, and
  339. // should be fixed cleanly as soon as possible
  340. if(!FileExists(CurrentPackagesFile) ||
  341. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  342. {
  343. // we don't have a pkg file or we don't want to queue
  344. if(Debug)
  345. std::clog << "No index file, local or canceld by user" << std::endl;
  346. Failed("", NULL);
  347. return;
  348. }
  349. if(Debug)
  350. std::clog << "pkgAcqIndexDiffs::pkgAcqIndexDiffs(): "
  351. << CurrentPackagesFile << std::endl;
  352. QueueURI(Desc);
  353. }
  354. /*}}}*/
  355. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  356. // ---------------------------------------------------------------------
  357. /* The only header we use is the last-modified header. */
  358. string pkgAcqDiffIndex::Custom600Headers()
  359. {
  360. string Final = _config->FindDir("Dir::State::lists");
  361. Final += URItoFileName(RealURI) + string(".IndexDiff");
  362. if(Debug)
  363. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  364. struct stat Buf;
  365. if (stat(Final.c_str(),&Buf) != 0)
  366. return "\nIndex-File: true";
  367. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  368. }
  369. /*}}}*/
  370. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  371. {
  372. if(Debug)
  373. std::clog << "pkgAcqIndexDiffs::ParseIndexDiff() " << IndexDiffFile
  374. << std::endl;
  375. pkgTagSection Tags;
  376. string ServerSha1;
  377. vector<DiffInfo> available_patches;
  378. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  379. pkgTagFile TF(&Fd);
  380. if (_error->PendingError() == true)
  381. return false;
  382. if(TF.Step(Tags) == true)
  383. {
  384. bool found = false;
  385. DiffInfo d;
  386. string size;
  387. string const tmp = Tags.FindS("SHA1-Current");
  388. std::stringstream ss(tmp);
  389. ss >> ServerSha1 >> size;
  390. unsigned long const ServerSize = atol(size.c_str());
  391. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  392. SHA1Summation SHA1;
  393. SHA1.AddFD(fd.Fd(), fd.Size());
  394. string const local_sha1 = SHA1.Result();
  395. if(local_sha1 == ServerSha1)
  396. {
  397. // we have the same sha1 as the server
  398. if(Debug)
  399. std::clog << "Package file is up-to-date" << std::endl;
  400. // set found to true, this will queue a pkgAcqIndexDiffs with
  401. // a empty availabe_patches
  402. found = true;
  403. }
  404. else
  405. {
  406. if(Debug)
  407. std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
  408. // check the historie and see what patches we need
  409. string const history = Tags.FindS("SHA1-History");
  410. std::stringstream hist(history);
  411. while(hist >> d.sha1 >> size >> d.file)
  412. {
  413. // read until the first match is found
  414. // from that point on, we probably need all diffs
  415. if(d.sha1 == local_sha1)
  416. found=true;
  417. else if (found == false)
  418. continue;
  419. if(Debug)
  420. std::clog << "Need to get diff: " << d.file << std::endl;
  421. available_patches.push_back(d);
  422. }
  423. if (available_patches.empty() == false)
  424. {
  425. // patching with too many files is rather slow compared to a fast download
  426. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  427. if (fileLimit != 0 && fileLimit < available_patches.size())
  428. {
  429. if (Debug)
  430. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  431. << ") so fallback to complete download" << std::endl;
  432. return false;
  433. }
  434. // see if the patches are too big
  435. found = false; // it was true and it will be true again at the end
  436. d = *available_patches.begin();
  437. string const firstPatch = d.file;
  438. unsigned long patchesSize = 0;
  439. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  440. while(patches >> d.sha1 >> size >> d.file)
  441. {
  442. if (firstPatch == d.file)
  443. found = true;
  444. else if (found == false)
  445. continue;
  446. patchesSize += atol(size.c_str());
  447. }
  448. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  449. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  450. {
  451. if (Debug)
  452. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  453. << ") so fallback to complete download" << std::endl;
  454. return false;
  455. }
  456. }
  457. }
  458. // we have something, queue the next diff
  459. if(found)
  460. {
  461. // queue the diffs
  462. string::size_type const last_space = Description.rfind(" ");
  463. if(last_space != string::npos)
  464. Description.erase(last_space, Description.size()-last_space);
  465. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  466. ExpectedHash, ServerSha1, available_patches);
  467. Complete = false;
  468. Status = StatDone;
  469. Dequeue();
  470. return true;
  471. }
  472. }
  473. // Nothing found, report and return false
  474. // Failing here is ok, if we return false later, the full
  475. // IndexFile is queued
  476. if(Debug)
  477. std::clog << "Can't find a patch in the index file" << std::endl;
  478. return false;
  479. }
  480. /*}}}*/
  481. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  482. {
  483. if(Debug)
  484. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << std::endl
  485. << "Falling back to normal index file aquire" << std::endl;
  486. new pkgAcqIndex(Owner, RealURI, Description, Desc.ShortDesc,
  487. ExpectedHash);
  488. Complete = false;
  489. Status = StatDone;
  490. Dequeue();
  491. }
  492. /*}}}*/
  493. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  494. pkgAcquire::MethodConfig *Cnf)
  495. {
  496. if(Debug)
  497. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  498. Item::Done(Message,Size,Md5Hash,Cnf);
  499. string FinalFile;
  500. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  501. // sucess in downloading the index
  502. // rename the index
  503. FinalFile += string(".IndexDiff");
  504. if(Debug)
  505. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  506. << std::endl;
  507. Rename(DestFile,FinalFile);
  508. chmod(FinalFile.c_str(),0644);
  509. DestFile = FinalFile;
  510. if(!ParseDiffIndex(DestFile))
  511. return Failed("", NULL);
  512. Complete = true;
  513. Status = StatDone;
  514. Dequeue();
  515. return;
  516. }
  517. /*}}}*/
  518. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  519. // ---------------------------------------------------------------------
  520. /* The package diff is added to the queue. one object is constructed
  521. * for each diff and the index
  522. */
  523. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  524. string URI,string URIDesc,string ShortDesc,
  525. HashString ExpectedHash,
  526. string ServerSha1,
  527. vector<DiffInfo> diffs)
  528. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash),
  529. available_patches(diffs), ServerSha1(ServerSha1)
  530. {
  531. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  532. DestFile += URItoFileName(URI);
  533. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  534. Description = URIDesc;
  535. Desc.Owner = this;
  536. Desc.ShortDesc = ShortDesc;
  537. if(available_patches.size() == 0)
  538. {
  539. // we are done (yeah!)
  540. Finish(true);
  541. }
  542. else
  543. {
  544. // get the next diff
  545. State = StateFetchDiff;
  546. QueueNextDiff();
  547. }
  548. }
  549. /*}}}*/
  550. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  551. {
  552. if(Debug)
  553. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << std::endl
  554. << "Falling back to normal index file aquire" << std::endl;
  555. new pkgAcqIndex(Owner, RealURI, Description,Desc.ShortDesc,
  556. ExpectedHash);
  557. Finish();
  558. }
  559. /*}}}*/
  560. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  561. void pkgAcqIndexDiffs::Finish(bool allDone)
  562. {
  563. // we restore the original name, this is required, otherwise
  564. // the file will be cleaned
  565. if(allDone)
  566. {
  567. DestFile = _config->FindDir("Dir::State::lists");
  568. DestFile += URItoFileName(RealURI);
  569. if(!ExpectedHash.empty() && !ExpectedHash.VerifyFile(DestFile))
  570. {
  571. Status = StatAuthError;
  572. ErrorText = _("MD5Sum mismatch");
  573. Rename(DestFile,DestFile + ".FAILED");
  574. Dequeue();
  575. return;
  576. }
  577. // this is for the "real" finish
  578. Complete = true;
  579. Status = StatDone;
  580. Dequeue();
  581. if(Debug)
  582. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  583. return;
  584. }
  585. if(Debug)
  586. std::clog << "Finishing: " << Desc.URI << std::endl;
  587. Complete = false;
  588. Status = StatDone;
  589. Dequeue();
  590. return;
  591. }
  592. /*}}}*/
  593. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  594. {
  595. // calc sha1 of the just patched file
  596. string FinalFile = _config->FindDir("Dir::State::lists");
  597. FinalFile += URItoFileName(RealURI);
  598. FileFd fd(FinalFile, FileFd::ReadOnly);
  599. SHA1Summation SHA1;
  600. SHA1.AddFD(fd.Fd(), fd.Size());
  601. string local_sha1 = string(SHA1.Result());
  602. if(Debug)
  603. std::clog << "QueueNextDiff: "
  604. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  605. // final file reached before all patches are applied
  606. if(local_sha1 == ServerSha1)
  607. {
  608. Finish(true);
  609. return true;
  610. }
  611. // remove all patches until the next matching patch is found
  612. // this requires the Index file to be ordered
  613. for(vector<DiffInfo>::iterator I=available_patches.begin();
  614. available_patches.empty() == false &&
  615. I != available_patches.end() &&
  616. I->sha1 != local_sha1;
  617. ++I)
  618. {
  619. available_patches.erase(I);
  620. }
  621. // error checking and falling back if no patch was found
  622. if(available_patches.empty() == true)
  623. {
  624. Failed("", NULL);
  625. return false;
  626. }
  627. // queue the right diff
  628. Desc.URI = string(RealURI) + ".diff/" + available_patches[0].file + ".gz";
  629. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  630. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  631. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  632. if(Debug)
  633. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  634. QueueURI(Desc);
  635. return true;
  636. }
  637. /*}}}*/
  638. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size,string Md5Hash, /*{{{*/
  639. pkgAcquire::MethodConfig *Cnf)
  640. {
  641. if(Debug)
  642. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  643. Item::Done(Message,Size,Md5Hash,Cnf);
  644. string FinalFile;
  645. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  646. // sucess in downloading a diff, enter ApplyDiff state
  647. if(State == StateFetchDiff)
  648. {
  649. // rred excepts the patch as $FinalFile.ed
  650. Rename(DestFile,FinalFile+".ed");
  651. if(Debug)
  652. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  653. State = StateApplyDiff;
  654. Local = true;
  655. Desc.URI = "rred:" + FinalFile;
  656. QueueURI(Desc);
  657. Mode = "rred";
  658. return;
  659. }
  660. // success in download/apply a diff, queue next (if needed)
  661. if(State == StateApplyDiff)
  662. {
  663. // remove the just applied patch
  664. available_patches.erase(available_patches.begin());
  665. // move into place
  666. if(Debug)
  667. {
  668. std::clog << "Moving patched file in place: " << std::endl
  669. << DestFile << " -> " << FinalFile << std::endl;
  670. }
  671. Rename(DestFile,FinalFile);
  672. chmod(FinalFile.c_str(),0644);
  673. // see if there is more to download
  674. if(available_patches.empty() == false) {
  675. new pkgAcqIndexDiffs(Owner, RealURI, Description, Desc.ShortDesc,
  676. ExpectedHash, ServerSha1, available_patches);
  677. return Finish();
  678. } else
  679. return Finish(true);
  680. }
  681. }
  682. /*}}}*/
  683. // AcqIndex::AcqIndex - Constructor /*{{{*/
  684. // ---------------------------------------------------------------------
  685. /* The package file is added to the queue and a second class is
  686. instantiated to fetch the revision file */
  687. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  688. string URI,string URIDesc,string ShortDesc,
  689. HashString ExpectedHash, string comprExt)
  690. : Item(Owner), RealURI(URI), ExpectedHash(ExpectedHash)
  691. {
  692. if(comprExt.empty() == true)
  693. {
  694. // autoselect the compression method
  695. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  696. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  697. comprExt.append(*t).append(" ");
  698. if (comprExt.empty() == false)
  699. comprExt.erase(comprExt.end()-1);
  700. }
  701. CompressionExtension = comprExt;
  702. Init(URI, URIDesc, ShortDesc);
  703. }
  704. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner, IndexTarget const *Target,
  705. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  706. : Item(Owner), RealURI(Target->URI), ExpectedHash(ExpectedHash)
  707. {
  708. // autoselect the compression method
  709. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  710. CompressionExtension = "";
  711. if (ExpectedHash.empty() == false)
  712. {
  713. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  714. if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
  715. CompressionExtension.append(*t).append(" ");
  716. }
  717. else
  718. {
  719. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  720. CompressionExtension.append(*t).append(" ");
  721. }
  722. if (CompressionExtension.empty() == false)
  723. CompressionExtension.erase(CompressionExtension.end()-1);
  724. // only verify non-optional targets, see acquire-item.h for a FIXME
  725. // to make this more flexible
  726. if (Target->IsOptional())
  727. Verify = false;
  728. else
  729. Verify = true;
  730. Init(Target->URI, Target->Description, Target->ShortDesc);
  731. }
  732. /*}}}*/
  733. // AcqIndex::Init - defered Constructor /*{{{*/
  734. void pkgAcqIndex::Init(string const &URI, string const &URIDesc, string const &ShortDesc) {
  735. Decompression = false;
  736. Erase = false;
  737. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  738. DestFile += URItoFileName(URI);
  739. std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  740. if (comprExt == "uncompressed")
  741. Desc.URI = URI;
  742. else
  743. Desc.URI = URI + '.' + comprExt;
  744. Desc.Description = URIDesc;
  745. Desc.Owner = this;
  746. Desc.ShortDesc = ShortDesc;
  747. QueueURI(Desc);
  748. }
  749. /*}}}*/
  750. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  751. // ---------------------------------------------------------------------
  752. /* The only header we use is the last-modified header. */
  753. string pkgAcqIndex::Custom600Headers()
  754. {
  755. string Final = _config->FindDir("Dir::State::lists");
  756. Final += URItoFileName(RealURI);
  757. if (_config->FindB("Acquire::GzipIndexes",false))
  758. Final += ".gz";
  759. string msg = "\nIndex-File: true";
  760. // FIXME: this really should use "IndexTarget::IsOptional()" but that
  761. // seems to be difficult without breaking ABI
  762. if (ShortDesc().find("Translation") != 0)
  763. msg += "\nFail-Ignore: true";
  764. struct stat Buf;
  765. if (stat(Final.c_str(),&Buf) == 0)
  766. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  767. return msg;
  768. }
  769. /*}}}*/
  770. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  771. {
  772. size_t const nextExt = CompressionExtension.find(' ');
  773. if (nextExt != std::string::npos)
  774. {
  775. CompressionExtension = CompressionExtension.substr(nextExt+1);
  776. Init(RealURI, Desc.Description, Desc.ShortDesc);
  777. return;
  778. }
  779. // on decompression failure, remove bad versions in partial/
  780. if (Decompression && Erase) {
  781. string s = _config->FindDir("Dir::State::lists") + "partial/";
  782. s.append(URItoFileName(RealURI));
  783. unlink(s.c_str());
  784. }
  785. Item::Failed(Message,Cnf);
  786. }
  787. /*}}}*/
  788. // AcqIndex::Done - Finished a fetch /*{{{*/
  789. // ---------------------------------------------------------------------
  790. /* This goes through a number of states.. On the initial fetch the
  791. method could possibly return an alternate filename which points
  792. to the uncompressed version of the file. If this is so the file
  793. is copied into the partial directory. In all other cases the file
  794. is decompressed with a gzip uri. */
  795. void pkgAcqIndex::Done(string Message,unsigned long long Size,string Hash,
  796. pkgAcquire::MethodConfig *Cfg)
  797. {
  798. Item::Done(Message,Size,Hash,Cfg);
  799. if (Decompression == true)
  800. {
  801. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  802. {
  803. std::cerr << std::endl << RealURI << ": Computed Hash: " << Hash;
  804. std::cerr << " Expected Hash: " << ExpectedHash.toStr() << std::endl;
  805. }
  806. if (!ExpectedHash.empty() && ExpectedHash.toStr() != Hash)
  807. {
  808. Status = StatAuthError;
  809. ErrorText = _("Hash Sum mismatch");
  810. Rename(DestFile,DestFile + ".FAILED");
  811. ReportMirrorFailure("HashChecksumFailure");
  812. return;
  813. }
  814. /* Verify the index file for correctness (all indexes must
  815. * have a Package field) (LP: #346386) (Closes: #627642) */
  816. if (Verify == true)
  817. {
  818. FileFd fd(DestFile, FileFd::ReadOnly);
  819. pkgTagSection sec;
  820. pkgTagFile tag(&fd);
  821. // Only test for correctness if the file is not empty (empty is ok)
  822. if (fd.Size() > 0) {
  823. if (_error->PendingError() || !tag.Step(sec)) {
  824. Status = StatError;
  825. _error->DumpErrors();
  826. Rename(DestFile,DestFile + ".FAILED");
  827. return;
  828. } else if (!sec.Exists("Package")) {
  829. Status = StatError;
  830. ErrorText = ("Encountered a section with no Package: header");
  831. Rename(DestFile,DestFile + ".FAILED");
  832. return;
  833. }
  834. }
  835. }
  836. // Done, move it into position
  837. string FinalFile = _config->FindDir("Dir::State::lists");
  838. FinalFile += URItoFileName(RealURI);
  839. Rename(DestFile,FinalFile);
  840. chmod(FinalFile.c_str(),0644);
  841. /* We restore the original name to DestFile so that the clean operation
  842. will work OK */
  843. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  844. DestFile += URItoFileName(RealURI);
  845. // Remove the compressed version.
  846. if (Erase == true)
  847. unlink(DestFile.c_str());
  848. return;
  849. }
  850. Erase = false;
  851. Complete = true;
  852. // Handle the unzipd case
  853. string FileName = LookupTag(Message,"Alt-Filename");
  854. if (FileName.empty() == false)
  855. {
  856. // The files timestamp matches
  857. if (StringToBool(LookupTag(Message,"Alt-IMS-Hit"),false) == true)
  858. return;
  859. Decompression = true;
  860. Local = true;
  861. DestFile += ".decomp";
  862. Desc.URI = "copy:" + FileName;
  863. QueueURI(Desc);
  864. Mode = "copy";
  865. return;
  866. }
  867. FileName = LookupTag(Message,"Filename");
  868. if (FileName.empty() == true)
  869. {
  870. Status = StatError;
  871. ErrorText = "Method gave a blank filename";
  872. }
  873. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  874. // The files timestamp matches
  875. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true) {
  876. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  877. // Update DestFile for .gz suffix so that the clean operation keeps it
  878. DestFile += ".gz";
  879. return;
  880. }
  881. if (FileName == DestFile)
  882. Erase = true;
  883. else
  884. Local = true;
  885. string decompProg;
  886. // If we enable compressed indexes and already have gzip, keep it
  887. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz" && !Local) {
  888. string FinalFile = _config->FindDir("Dir::State::lists");
  889. FinalFile += URItoFileName(RealURI) + ".gz";
  890. Rename(DestFile,FinalFile);
  891. chmod(FinalFile.c_str(),0644);
  892. // Update DestFile for .gz suffix so that the clean operation keeps it
  893. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  894. DestFile += URItoFileName(RealURI) + ".gz";
  895. return;
  896. }
  897. // get the binary name for your used compression type
  898. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  899. if(decompProg.empty() == false);
  900. else if(compExt == "uncompressed")
  901. decompProg = "copy";
  902. else {
  903. _error->Error("Unsupported extension: %s", compExt.c_str());
  904. return;
  905. }
  906. Decompression = true;
  907. DestFile += ".decomp";
  908. Desc.URI = decompProg + ":" + FileName;
  909. QueueURI(Desc);
  910. Mode = decompProg.c_str();
  911. }
  912. /*}}}*/
  913. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  914. // ---------------------------------------------------------------------
  915. /* The Translation file is added to the queue */
  916. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  917. string URI,string URIDesc,string ShortDesc)
  918. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashString(), "")
  919. {
  920. }
  921. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner, IndexTarget const *Target,
  922. HashString const &ExpectedHash, indexRecords const *MetaIndexParser)
  923. : pkgAcqIndex(Owner, Target, ExpectedHash, MetaIndexParser)
  924. {
  925. }
  926. /*}}}*/
  927. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  928. // ---------------------------------------------------------------------
  929. string pkgAcqIndexTrans::Custom600Headers()
  930. {
  931. string Final = _config->FindDir("Dir::State::lists");
  932. Final += URItoFileName(RealURI);
  933. struct stat Buf;
  934. if (stat(Final.c_str(),&Buf) != 0)
  935. return "\nFail-Ignore: true\nIndex-File: true";
  936. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  937. }
  938. /*}}}*/
  939. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  940. // ---------------------------------------------------------------------
  941. /* */
  942. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  943. {
  944. size_t const nextExt = CompressionExtension.find(' ');
  945. if (nextExt != std::string::npos)
  946. {
  947. CompressionExtension = CompressionExtension.substr(nextExt+1);
  948. Init(RealURI, Desc.Description, Desc.ShortDesc);
  949. Status = StatIdle;
  950. return;
  951. }
  952. if (Cnf->LocalOnly == true ||
  953. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  954. {
  955. // Ignore this
  956. Status = StatDone;
  957. Complete = false;
  958. Dequeue();
  959. return;
  960. }
  961. Item::Failed(Message,Cnf);
  962. }
  963. /*}}}*/
  964. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  965. string URI,string URIDesc,string ShortDesc,
  966. string MetaIndexURI, string MetaIndexURIDesc,
  967. string MetaIndexShortDesc,
  968. const vector<IndexTarget*>* IndexTargets,
  969. indexRecords* MetaIndexParser) :
  970. Item(Owner), RealURI(URI), MetaIndexURI(MetaIndexURI),
  971. MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  972. MetaIndexParser(MetaIndexParser), IndexTargets(IndexTargets)
  973. {
  974. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  975. DestFile += URItoFileName(URI);
  976. // remove any partial downloaded sig-file in partial/.
  977. // it may confuse proxies and is too small to warrant a
  978. // partial download anyway
  979. unlink(DestFile.c_str());
  980. // Create the item
  981. Desc.Description = URIDesc;
  982. Desc.Owner = this;
  983. Desc.ShortDesc = ShortDesc;
  984. Desc.URI = URI;
  985. string Final = _config->FindDir("Dir::State::lists");
  986. Final += URItoFileName(RealURI);
  987. struct stat Buf;
  988. if (stat(Final.c_str(),&Buf) == 0)
  989. {
  990. // File was already in place. It needs to be re-downloaded/verified
  991. // because Release might have changed, we do give it a differnt
  992. // name than DestFile because otherwise the http method will
  993. // send If-Range requests and there are too many broken servers
  994. // out there that do not understand them
  995. LastGoodSig = DestFile+".reverify";
  996. Rename(Final,LastGoodSig);
  997. }
  998. QueueURI(Desc);
  999. }
  1000. /*}}}*/
  1001. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1002. // ---------------------------------------------------------------------
  1003. /* The only header we use is the last-modified header. */
  1004. string pkgAcqMetaSig::Custom600Headers()
  1005. {
  1006. struct stat Buf;
  1007. if (stat(LastGoodSig.c_str(),&Buf) != 0)
  1008. return "\nIndex-File: true";
  1009. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1010. }
  1011. void pkgAcqMetaSig::Done(string Message,unsigned long long Size,string MD5,
  1012. pkgAcquire::MethodConfig *Cfg)
  1013. {
  1014. Item::Done(Message,Size,MD5,Cfg);
  1015. string FileName = LookupTag(Message,"Filename");
  1016. if (FileName.empty() == true)
  1017. {
  1018. Status = StatError;
  1019. ErrorText = "Method gave a blank filename";
  1020. return;
  1021. }
  1022. if (FileName != DestFile)
  1023. {
  1024. // We have to copy it into place
  1025. Local = true;
  1026. Desc.URI = "copy:" + FileName;
  1027. QueueURI(Desc);
  1028. return;
  1029. }
  1030. Complete = true;
  1031. // put the last known good file back on i-m-s hit (it will
  1032. // be re-verified again)
  1033. // Else do nothing, we have the new file in DestFile then
  1034. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1035. Rename(LastGoodSig, DestFile);
  1036. // queue a pkgAcqMetaIndex to be verified against the sig we just retrieved
  1037. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc,
  1038. MetaIndexShortDesc, DestFile, IndexTargets,
  1039. MetaIndexParser);
  1040. }
  1041. /*}}}*/
  1042. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1043. {
  1044. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1045. // if we get a network error we fail gracefully
  1046. if(Status == StatTransientNetworkError)
  1047. {
  1048. Item::Failed(Message,Cnf);
  1049. // move the sigfile back on transient network failures
  1050. if(FileExists(LastGoodSig))
  1051. Rename(LastGoodSig,Final);
  1052. // set the status back to , Item::Failed likes to reset it
  1053. Status = pkgAcquire::Item::StatTransientNetworkError;
  1054. return;
  1055. }
  1056. // Delete any existing sigfile when the acquire failed
  1057. unlink(Final.c_str());
  1058. // queue a pkgAcqMetaIndex with no sigfile
  1059. new pkgAcqMetaIndex(Owner, MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1060. "", IndexTargets, MetaIndexParser);
  1061. if (Cnf->LocalOnly == true ||
  1062. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1063. {
  1064. // Ignore this
  1065. Status = StatDone;
  1066. Complete = false;
  1067. Dequeue();
  1068. return;
  1069. }
  1070. Item::Failed(Message,Cnf);
  1071. }
  1072. /*}}}*/
  1073. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1074. string URI,string URIDesc,string ShortDesc,
  1075. string SigFile,
  1076. const vector<struct IndexTarget*>* IndexTargets,
  1077. indexRecords* MetaIndexParser) :
  1078. Item(Owner), RealURI(URI), SigFile(SigFile), IndexTargets(IndexTargets),
  1079. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false)
  1080. {
  1081. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1082. DestFile += URItoFileName(URI);
  1083. // Create the item
  1084. Desc.Description = URIDesc;
  1085. Desc.Owner = this;
  1086. Desc.ShortDesc = ShortDesc;
  1087. Desc.URI = URI;
  1088. QueueURI(Desc);
  1089. }
  1090. /*}}}*/
  1091. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1092. // ---------------------------------------------------------------------
  1093. /* The only header we use is the last-modified header. */
  1094. string pkgAcqMetaIndex::Custom600Headers()
  1095. {
  1096. string Final = _config->FindDir("Dir::State::lists");
  1097. Final += URItoFileName(RealURI);
  1098. struct stat Buf;
  1099. if (stat(Final.c_str(),&Buf) != 0)
  1100. return "\nIndex-File: true";
  1101. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1102. }
  1103. /*}}}*/
  1104. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,string Hash, /*{{{*/
  1105. pkgAcquire::MethodConfig *Cfg)
  1106. {
  1107. Item::Done(Message,Size,Hash,Cfg);
  1108. // MetaIndexes are done in two passes: one to download the
  1109. // metaindex with an appropriate method, and a second to verify it
  1110. // with the gpgv method
  1111. if (AuthPass == true)
  1112. {
  1113. AuthDone(Message);
  1114. // all cool, move Release file into place
  1115. Complete = true;
  1116. }
  1117. else
  1118. {
  1119. RetrievalDone(Message);
  1120. if (!Complete)
  1121. // Still more retrieving to do
  1122. return;
  1123. if (SigFile == "")
  1124. {
  1125. // There was no signature file, so we are finished. Download
  1126. // the indexes and do only hashsum verification if possible
  1127. MetaIndexParser->Load(DestFile);
  1128. QueueIndexes(false);
  1129. }
  1130. else
  1131. {
  1132. // There was a signature file, so pass it to gpgv for
  1133. // verification
  1134. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1135. std::cerr << "Metaindex acquired, queueing gpg verification ("
  1136. << SigFile << "," << DestFile << ")\n";
  1137. AuthPass = true;
  1138. Desc.URI = "gpgv:" + SigFile;
  1139. QueueURI(Desc);
  1140. Mode = "gpgv";
  1141. return;
  1142. }
  1143. }
  1144. if (Complete == true)
  1145. {
  1146. string FinalFile = _config->FindDir("Dir::State::lists");
  1147. FinalFile += URItoFileName(RealURI);
  1148. if (SigFile == DestFile)
  1149. SigFile = FinalFile;
  1150. Rename(DestFile,FinalFile);
  1151. chmod(FinalFile.c_str(),0644);
  1152. DestFile = FinalFile;
  1153. }
  1154. }
  1155. /*}}}*/
  1156. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  1157. {
  1158. // We have just finished downloading a Release file (it is not
  1159. // verified yet)
  1160. string FileName = LookupTag(Message,"Filename");
  1161. if (FileName.empty() == true)
  1162. {
  1163. Status = StatError;
  1164. ErrorText = "Method gave a blank filename";
  1165. return;
  1166. }
  1167. if (FileName != DestFile)
  1168. {
  1169. Local = true;
  1170. Desc.URI = "copy:" + FileName;
  1171. QueueURI(Desc);
  1172. return;
  1173. }
  1174. // make sure to verify against the right file on I-M-S hit
  1175. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1176. if(IMSHit)
  1177. {
  1178. string FinalFile = _config->FindDir("Dir::State::lists");
  1179. FinalFile += URItoFileName(RealURI);
  1180. if (SigFile == DestFile)
  1181. SigFile = FinalFile;
  1182. DestFile = FinalFile;
  1183. }
  1184. Complete = true;
  1185. }
  1186. /*}}}*/
  1187. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  1188. {
  1189. // At this point, the gpgv method has succeeded, so there is a
  1190. // valid signature from a key in the trusted keyring. We
  1191. // perform additional verification of its contents, and use them
  1192. // to verify the indexes we are about to download
  1193. if (!MetaIndexParser->Load(DestFile))
  1194. {
  1195. Status = StatAuthError;
  1196. ErrorText = MetaIndexParser->ErrorText;
  1197. return;
  1198. }
  1199. if (!VerifyVendor(Message))
  1200. {
  1201. return;
  1202. }
  1203. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1204. std::cerr << "Signature verification succeeded: "
  1205. << DestFile << std::endl;
  1206. // Download further indexes with verification
  1207. QueueIndexes(true);
  1208. // is it a clearsigned MetaIndex file?
  1209. if (DestFile == SigFile)
  1210. return;
  1211. // Done, move signature file into position
  1212. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1213. URItoFileName(RealURI) + ".gpg";
  1214. Rename(SigFile,VerifiedSigFile);
  1215. chmod(VerifiedSigFile.c_str(),0644);
  1216. }
  1217. /*}}}*/
  1218. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  1219. {
  1220. #if 0
  1221. /* Reject invalid, existing Release files (LP: #346386) (Closes: #627642)
  1222. * FIXME: Disabled; it breaks unsigned repositories without hashes */
  1223. if (!verify && FileExists(DestFile) && !MetaIndexParser->Load(DestFile))
  1224. {
  1225. Status = StatError;
  1226. ErrorText = MetaIndexParser->ErrorText;
  1227. return;
  1228. }
  1229. #endif
  1230. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1231. Target != IndexTargets->end();
  1232. ++Target)
  1233. {
  1234. HashString ExpectedIndexHash;
  1235. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1236. if (Record == NULL)
  1237. {
  1238. if (verify == true && (*Target)->IsOptional() == false)
  1239. {
  1240. Status = StatAuthError;
  1241. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1242. return;
  1243. }
  1244. }
  1245. else
  1246. {
  1247. ExpectedIndexHash = Record->Hash;
  1248. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1249. {
  1250. std::cerr << "Queueing: " << (*Target)->URI << std::endl;
  1251. std::cerr << "Expected Hash: " << ExpectedIndexHash.toStr() << std::endl;
  1252. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1253. }
  1254. if (verify == true && ExpectedIndexHash.empty() == true && (*Target)->IsOptional() == false)
  1255. {
  1256. Status = StatAuthError;
  1257. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1258. return;
  1259. }
  1260. }
  1261. if ((*Target)->IsOptional() == true)
  1262. {
  1263. if ((*Target)->IsSubIndex() == true)
  1264. new pkgAcqSubIndex(Owner, (*Target)->URI, (*Target)->Description,
  1265. (*Target)->ShortDesc, ExpectedIndexHash);
  1266. else
  1267. new pkgAcqIndexTrans(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1268. continue;
  1269. }
  1270. /* Queue Packages file (either diff or full packages files, depending
  1271. on the users option) - we also check if the PDiff Index file is listed
  1272. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1273. instead, but passing the required info to it is to much hassle */
  1274. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1275. MetaIndexParser->Exists(string((*Target)->MetaKey).append(".diff/Index")) == true))
  1276. new pkgAcqDiffIndex(Owner, (*Target)->URI, (*Target)->Description,
  1277. (*Target)->ShortDesc, ExpectedIndexHash);
  1278. else
  1279. new pkgAcqIndex(Owner, *Target, ExpectedIndexHash, MetaIndexParser);
  1280. }
  1281. }
  1282. /*}}}*/
  1283. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1284. {
  1285. string::size_type pos;
  1286. // check for missing sigs (that where not fatal because otherwise we had
  1287. // bombed earlier)
  1288. string missingkeys;
  1289. string msg = _("There is no public key available for the "
  1290. "following key IDs:\n");
  1291. pos = Message.find("NO_PUBKEY ");
  1292. if (pos != std::string::npos)
  1293. {
  1294. string::size_type start = pos+strlen("NO_PUBKEY ");
  1295. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1296. missingkeys += (Fingerprint);
  1297. }
  1298. if(!missingkeys.empty())
  1299. _error->Warning("%s", string(msg+missingkeys).c_str());
  1300. string Transformed = MetaIndexParser->GetExpectedDist();
  1301. if (Transformed == "../project/experimental")
  1302. {
  1303. Transformed = "experimental";
  1304. }
  1305. pos = Transformed.rfind('/');
  1306. if (pos != string::npos)
  1307. {
  1308. Transformed = Transformed.substr(0, pos);
  1309. }
  1310. if (Transformed == ".")
  1311. {
  1312. Transformed = "";
  1313. }
  1314. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1315. MetaIndexParser->GetValidUntil() > 0) {
  1316. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1317. if (invalid_since > 0)
  1318. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1319. // the time since then the file is invalid - formated in the same way as in
  1320. // the download progress display (e.g. 7d 3h 42min 1s)
  1321. return _error->Error(
  1322. _("Release file for %s is expired (invalid since %s). "
  1323. "Updates for this repository will not be applied."),
  1324. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1325. }
  1326. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1327. {
  1328. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1329. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1330. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1331. }
  1332. if (MetaIndexParser->CheckDist(Transformed) == false)
  1333. {
  1334. // This might become fatal one day
  1335. // Status = StatAuthError;
  1336. // ErrorText = "Conflicting distribution; expected "
  1337. // + MetaIndexParser->GetExpectedDist() + " but got "
  1338. // + MetaIndexParser->GetDist();
  1339. // return false;
  1340. if (!Transformed.empty())
  1341. {
  1342. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1343. Desc.Description.c_str(),
  1344. Transformed.c_str(),
  1345. MetaIndexParser->GetDist().c_str());
  1346. }
  1347. }
  1348. return true;
  1349. }
  1350. /*}}}*/
  1351. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1352. // ---------------------------------------------------------------------
  1353. /* */
  1354. void pkgAcqMetaIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1355. {
  1356. if (AuthPass == true)
  1357. {
  1358. // gpgv method failed, if we have a good signature
  1359. string LastGoodSigFile = _config->FindDir("Dir::State::lists");
  1360. if (DestFile == SigFile)
  1361. LastGoodSigFile.append(URItoFileName(RealURI));
  1362. else
  1363. LastGoodSigFile.append("partial/").append(URItoFileName(RealURI)).append(".gpg.reverify");
  1364. if(FileExists(LastGoodSigFile))
  1365. {
  1366. if (DestFile != SigFile)
  1367. {
  1368. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1369. URItoFileName(RealURI) + ".gpg";
  1370. Rename(LastGoodSigFile,VerifiedSigFile);
  1371. }
  1372. Status = StatTransientNetworkError;
  1373. _error->Warning(_("A error occurred during the signature "
  1374. "verification. The repository is not updated "
  1375. "and the previous index files will be used. "
  1376. "GPG error: %s: %s\n"),
  1377. Desc.Description.c_str(),
  1378. LookupTag(Message,"Message").c_str());
  1379. RunScripts("APT::Update::Auth-Failure");
  1380. return;
  1381. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1382. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1383. _error->Error(_("GPG error: %s: %s"),
  1384. Desc.Description.c_str(),
  1385. LookupTag(Message,"Message").c_str());
  1386. return;
  1387. } else {
  1388. _error->Warning(_("GPG error: %s: %s"),
  1389. Desc.Description.c_str(),
  1390. LookupTag(Message,"Message").c_str());
  1391. }
  1392. // gpgv method failed
  1393. ReportMirrorFailure("GPGFailure");
  1394. }
  1395. /* Always move the meta index, even if gpgv failed. This ensures
  1396. * that PackageFile objects are correctly filled in */
  1397. if (FileExists(DestFile)) {
  1398. string FinalFile = _config->FindDir("Dir::State::lists");
  1399. FinalFile += URItoFileName(RealURI);
  1400. /* InRelease files become Release files, otherwise
  1401. * they would be considered as trusted later on */
  1402. if (SigFile == DestFile) {
  1403. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1404. "Release");
  1405. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1406. "Release");
  1407. SigFile = FinalFile;
  1408. }
  1409. Rename(DestFile,FinalFile);
  1410. chmod(FinalFile.c_str(),0644);
  1411. DestFile = FinalFile;
  1412. }
  1413. // No Release file was present, or verification failed, so fall
  1414. // back to queueing Packages files without verification
  1415. QueueIndexes(false);
  1416. }
  1417. /*}}}*/
  1418. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1419. string const &URI, string const &URIDesc, string const &ShortDesc,
  1420. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1421. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1422. const vector<struct IndexTarget*>* IndexTargets,
  1423. indexRecords* MetaIndexParser) :
  1424. pkgAcqMetaIndex(Owner, URI, URIDesc, ShortDesc, "", IndexTargets, MetaIndexParser),
  1425. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1426. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1427. {
  1428. SigFile = DestFile;
  1429. }
  1430. /*}}}*/
  1431. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1432. // ---------------------------------------------------------------------
  1433. // FIXME: this can go away once the InRelease file is used widely
  1434. string pkgAcqMetaClearSig::Custom600Headers()
  1435. {
  1436. string Final = _config->FindDir("Dir::State::lists");
  1437. Final += URItoFileName(RealURI);
  1438. struct stat Buf;
  1439. if (stat(Final.c_str(),&Buf) != 0)
  1440. return "\nIndex-File: true\nFail-Ignore: true\n";
  1441. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1442. }
  1443. /*}}}*/
  1444. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1445. {
  1446. if (AuthPass == false)
  1447. {
  1448. new pkgAcqMetaSig(Owner,
  1449. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1450. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1451. IndexTargets, MetaIndexParser);
  1452. if (Cnf->LocalOnly == true ||
  1453. StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
  1454. Dequeue();
  1455. }
  1456. else
  1457. pkgAcqMetaIndex::Failed(Message, Cnf);
  1458. }
  1459. /*}}}*/
  1460. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1461. // ---------------------------------------------------------------------
  1462. /* This just sets up the initial fetch environment and queues the first
  1463. possibilitiy */
  1464. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1465. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1466. string &StoreFilename) :
  1467. Item(Owner), Version(Version), Sources(Sources), Recs(Recs),
  1468. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1469. Trusted(false)
  1470. {
  1471. Retries = _config->FindI("Acquire::Retries",0);
  1472. if (Version.Arch() == 0)
  1473. {
  1474. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1475. "This might mean you need to manually fix this package. "
  1476. "(due to missing arch)"),
  1477. Version.ParentPkg().Name());
  1478. return;
  1479. }
  1480. /* We need to find a filename to determine the extension. We make the
  1481. assumption here that all the available sources for this version share
  1482. the same extension.. */
  1483. // Skip not source sources, they do not have file fields.
  1484. for (; Vf.end() == false; Vf++)
  1485. {
  1486. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1487. continue;
  1488. break;
  1489. }
  1490. // Does not really matter here.. we are going to fail out below
  1491. if (Vf.end() != true)
  1492. {
  1493. // If this fails to get a file name we will bomb out below.
  1494. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1495. if (_error->PendingError() == true)
  1496. return;
  1497. // Generate the final file name as: package_version_arch.foo
  1498. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1499. QuoteString(Version.VerStr(),"_:") + '_' +
  1500. QuoteString(Version.Arch(),"_:.") +
  1501. "." + flExtension(Parse.FileName());
  1502. }
  1503. // check if we have one trusted source for the package. if so, switch
  1504. // to "TrustedOnly" mode
  1505. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  1506. {
  1507. pkgIndexFile *Index;
  1508. if (Sources->FindIndex(i.File(),Index) == false)
  1509. continue;
  1510. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1511. {
  1512. std::cerr << "Checking index: " << Index->Describe()
  1513. << "(Trusted=" << Index->IsTrusted() << ")\n";
  1514. }
  1515. if (Index->IsTrusted()) {
  1516. Trusted = true;
  1517. break;
  1518. }
  1519. }
  1520. // "allow-unauthenticated" restores apts old fetching behaviour
  1521. // that means that e.g. unauthenticated file:// uris are higher
  1522. // priority than authenticated http:// uris
  1523. if (_config->FindB("APT::Get::AllowUnauthenticated",false) == true)
  1524. Trusted = false;
  1525. // Select a source
  1526. if (QueueNext() == false && _error->PendingError() == false)
  1527. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1528. "This might mean you need to manually fix this package."),
  1529. Version.ParentPkg().Name());
  1530. }
  1531. /*}}}*/
  1532. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1533. // ---------------------------------------------------------------------
  1534. /* This queues the next available file version for download. It checks if
  1535. the archive is already available in the cache and stashs the MD5 for
  1536. checking later. */
  1537. bool pkgAcqArchive::QueueNext()
  1538. {
  1539. string const ForceHash = _config->Find("Acquire::ForceHash");
  1540. for (; Vf.end() == false; ++Vf)
  1541. {
  1542. // Ignore not source sources
  1543. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1544. continue;
  1545. // Try to cross match against the source list
  1546. pkgIndexFile *Index;
  1547. if (Sources->FindIndex(Vf.File(),Index) == false)
  1548. continue;
  1549. // only try to get a trusted package from another source if that source
  1550. // is also trusted
  1551. if(Trusted && !Index->IsTrusted())
  1552. continue;
  1553. // Grab the text package record
  1554. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1555. if (_error->PendingError() == true)
  1556. return false;
  1557. string PkgFile = Parse.FileName();
  1558. if (ForceHash.empty() == false)
  1559. {
  1560. if(stringcasecmp(ForceHash, "sha512") == 0)
  1561. ExpectedHash = HashString("SHA512", Parse.SHA512Hash());
  1562. if(stringcasecmp(ForceHash, "sha256") == 0)
  1563. ExpectedHash = HashString("SHA256", Parse.SHA256Hash());
  1564. else if (stringcasecmp(ForceHash, "sha1") == 0)
  1565. ExpectedHash = HashString("SHA1", Parse.SHA1Hash());
  1566. else
  1567. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1568. }
  1569. else
  1570. {
  1571. string Hash;
  1572. if ((Hash = Parse.SHA512Hash()).empty() == false)
  1573. ExpectedHash = HashString("SHA512", Hash);
  1574. else if ((Hash = Parse.SHA256Hash()).empty() == false)
  1575. ExpectedHash = HashString("SHA256", Hash);
  1576. else if ((Hash = Parse.SHA1Hash()).empty() == false)
  1577. ExpectedHash = HashString("SHA1", Hash);
  1578. else
  1579. ExpectedHash = HashString("MD5Sum", Parse.MD5Hash());
  1580. }
  1581. if (PkgFile.empty() == true)
  1582. return _error->Error(_("The package index files are corrupted. No Filename: "
  1583. "field for package %s."),
  1584. Version.ParentPkg().Name());
  1585. Desc.URI = Index->ArchiveURI(PkgFile);
  1586. Desc.Description = Index->ArchiveInfo(Version);
  1587. Desc.Owner = this;
  1588. Desc.ShortDesc = Version.ParentPkg().Name();
  1589. // See if we already have the file. (Legacy filenames)
  1590. FileSize = Version->Size;
  1591. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1592. struct stat Buf;
  1593. if (stat(FinalFile.c_str(),&Buf) == 0)
  1594. {
  1595. // Make sure the size matches
  1596. if ((unsigned long long)Buf.st_size == Version->Size)
  1597. {
  1598. Complete = true;
  1599. Local = true;
  1600. Status = StatDone;
  1601. StoreFilename = DestFile = FinalFile;
  1602. return true;
  1603. }
  1604. /* Hmm, we have a file and its size does not match, this means it is
  1605. an old style mismatched arch */
  1606. unlink(FinalFile.c_str());
  1607. }
  1608. // Check it again using the new style output filenames
  1609. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  1610. if (stat(FinalFile.c_str(),&Buf) == 0)
  1611. {
  1612. // Make sure the size matches
  1613. if ((unsigned long long)Buf.st_size == Version->Size)
  1614. {
  1615. Complete = true;
  1616. Local = true;
  1617. Status = StatDone;
  1618. StoreFilename = DestFile = FinalFile;
  1619. return true;
  1620. }
  1621. /* Hmm, we have a file and its size does not match, this shouldnt
  1622. happen.. */
  1623. unlink(FinalFile.c_str());
  1624. }
  1625. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  1626. // Check the destination file
  1627. if (stat(DestFile.c_str(),&Buf) == 0)
  1628. {
  1629. // Hmm, the partial file is too big, erase it
  1630. if ((unsigned long long)Buf.st_size > Version->Size)
  1631. unlink(DestFile.c_str());
  1632. else
  1633. PartialSize = Buf.st_size;
  1634. }
  1635. // Create the item
  1636. Local = false;
  1637. Desc.URI = Index->ArchiveURI(PkgFile);
  1638. Desc.Description = Index->ArchiveInfo(Version);
  1639. Desc.Owner = this;
  1640. Desc.ShortDesc = Version.ParentPkg().Name();
  1641. QueueURI(Desc);
  1642. ++Vf;
  1643. return true;
  1644. }
  1645. return false;
  1646. }
  1647. /*}}}*/
  1648. // AcqArchive::Done - Finished fetching /*{{{*/
  1649. // ---------------------------------------------------------------------
  1650. /* */
  1651. void pkgAcqArchive::Done(string Message,unsigned long long Size,string CalcHash,
  1652. pkgAcquire::MethodConfig *Cfg)
  1653. {
  1654. Item::Done(Message,Size,CalcHash,Cfg);
  1655. // Check the size
  1656. if (Size != Version->Size)
  1657. {
  1658. Status = StatError;
  1659. ErrorText = _("Size mismatch");
  1660. return;
  1661. }
  1662. // Check the hash
  1663. if(ExpectedHash.toStr() != CalcHash)
  1664. {
  1665. Status = StatError;
  1666. ErrorText = _("Hash Sum mismatch");
  1667. if(FileExists(DestFile))
  1668. Rename(DestFile,DestFile + ".FAILED");
  1669. return;
  1670. }
  1671. // Grab the output filename
  1672. string FileName = LookupTag(Message,"Filename");
  1673. if (FileName.empty() == true)
  1674. {
  1675. Status = StatError;
  1676. ErrorText = "Method gave a blank filename";
  1677. return;
  1678. }
  1679. Complete = true;
  1680. // Reference filename
  1681. if (FileName != DestFile)
  1682. {
  1683. StoreFilename = DestFile = FileName;
  1684. Local = true;
  1685. return;
  1686. }
  1687. // Done, move it into position
  1688. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  1689. FinalFile += flNotDir(StoreFilename);
  1690. Rename(DestFile,FinalFile);
  1691. StoreFilename = DestFile = FinalFile;
  1692. Complete = true;
  1693. }
  1694. /*}}}*/
  1695. // AcqArchive::Failed - Failure handler /*{{{*/
  1696. // ---------------------------------------------------------------------
  1697. /* Here we try other sources */
  1698. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1699. {
  1700. ErrorText = LookupTag(Message,"Message");
  1701. /* We don't really want to retry on failed media swaps, this prevents
  1702. that. An interesting observation is that permanent failures are not
  1703. recorded. */
  1704. if (Cnf->Removable == true &&
  1705. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1706. {
  1707. // Vf = Version.FileList();
  1708. while (Vf.end() == false) ++Vf;
  1709. StoreFilename = string();
  1710. Item::Failed(Message,Cnf);
  1711. return;
  1712. }
  1713. if (QueueNext() == false)
  1714. {
  1715. // This is the retry counter
  1716. if (Retries != 0 &&
  1717. Cnf->LocalOnly == false &&
  1718. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1719. {
  1720. Retries--;
  1721. Vf = Version.FileList();
  1722. if (QueueNext() == true)
  1723. return;
  1724. }
  1725. StoreFilename = string();
  1726. Item::Failed(Message,Cnf);
  1727. }
  1728. }
  1729. /*}}}*/
  1730. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  1731. // ---------------------------------------------------------------------
  1732. bool pkgAcqArchive::IsTrusted()
  1733. {
  1734. return Trusted;
  1735. }
  1736. /*}}}*/
  1737. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  1738. // ---------------------------------------------------------------------
  1739. /* */
  1740. void pkgAcqArchive::Finished()
  1741. {
  1742. if (Status == pkgAcquire::Item::StatDone &&
  1743. Complete == true)
  1744. return;
  1745. StoreFilename = string();
  1746. }
  1747. /*}}}*/
  1748. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  1749. // ---------------------------------------------------------------------
  1750. /* The file is added to the queue */
  1751. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI,string Hash,
  1752. unsigned long long Size,string Dsc,string ShortDesc,
  1753. const string &DestDir, const string &DestFilename,
  1754. bool IsIndexFile) :
  1755. Item(Owner), ExpectedHash(Hash), IsIndexFile(IsIndexFile)
  1756. {
  1757. Retries = _config->FindI("Acquire::Retries",0);
  1758. if(!DestFilename.empty())
  1759. DestFile = DestFilename;
  1760. else if(!DestDir.empty())
  1761. DestFile = DestDir + "/" + flNotDir(URI);
  1762. else
  1763. DestFile = flNotDir(URI);
  1764. // Create the item
  1765. Desc.URI = URI;
  1766. Desc.Description = Dsc;
  1767. Desc.Owner = this;
  1768. // Set the short description to the archive component
  1769. Desc.ShortDesc = ShortDesc;
  1770. // Get the transfer sizes
  1771. FileSize = Size;
  1772. struct stat Buf;
  1773. if (stat(DestFile.c_str(),&Buf) == 0)
  1774. {
  1775. // Hmm, the partial file is too big, erase it
  1776. if ((unsigned long long)Buf.st_size > Size)
  1777. unlink(DestFile.c_str());
  1778. else
  1779. PartialSize = Buf.st_size;
  1780. }
  1781. QueueURI(Desc);
  1782. }
  1783. /*}}}*/
  1784. // AcqFile::Done - Item downloaded OK /*{{{*/
  1785. // ---------------------------------------------------------------------
  1786. /* */
  1787. void pkgAcqFile::Done(string Message,unsigned long long Size,string CalcHash,
  1788. pkgAcquire::MethodConfig *Cnf)
  1789. {
  1790. Item::Done(Message,Size,CalcHash,Cnf);
  1791. // Check the hash
  1792. if(!ExpectedHash.empty() && ExpectedHash.toStr() != CalcHash)
  1793. {
  1794. Status = StatError;
  1795. ErrorText = _("Hash Sum mismatch");
  1796. Rename(DestFile,DestFile + ".FAILED");
  1797. return;
  1798. }
  1799. string FileName = LookupTag(Message,"Filename");
  1800. if (FileName.empty() == true)
  1801. {
  1802. Status = StatError;
  1803. ErrorText = "Method gave a blank filename";
  1804. return;
  1805. }
  1806. Complete = true;
  1807. // The files timestamp matches
  1808. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1809. return;
  1810. // We have to copy it into place
  1811. if (FileName != DestFile)
  1812. {
  1813. Local = true;
  1814. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  1815. Cnf->Removable == true)
  1816. {
  1817. Desc.URI = "copy:" + FileName;
  1818. QueueURI(Desc);
  1819. return;
  1820. }
  1821. // Erase the file if it is a symlink so we can overwrite it
  1822. struct stat St;
  1823. if (lstat(DestFile.c_str(),&St) == 0)
  1824. {
  1825. if (S_ISLNK(St.st_mode) != 0)
  1826. unlink(DestFile.c_str());
  1827. }
  1828. // Symlink the file
  1829. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  1830. {
  1831. ErrorText = "Link to " + DestFile + " failure ";
  1832. Status = StatError;
  1833. Complete = false;
  1834. }
  1835. }
  1836. }
  1837. /*}}}*/
  1838. // AcqFile::Failed - Failure handler /*{{{*/
  1839. // ---------------------------------------------------------------------
  1840. /* Here we try other sources */
  1841. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1842. {
  1843. ErrorText = LookupTag(Message,"Message");
  1844. // This is the retry counter
  1845. if (Retries != 0 &&
  1846. Cnf->LocalOnly == false &&
  1847. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  1848. {
  1849. Retries--;
  1850. QueueURI(Desc);
  1851. return;
  1852. }
  1853. Item::Failed(Message,Cnf);
  1854. }
  1855. /*}}}*/
  1856. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1857. // ---------------------------------------------------------------------
  1858. /* The only header we use is the last-modified header. */
  1859. string pkgAcqFile::Custom600Headers()
  1860. {
  1861. if (IsIndexFile)
  1862. return "\nIndex-File: true";
  1863. return "";
  1864. }
  1865. /*}}}*/