acquire-item.cc 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  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/sha1.h>
  22. #include <apt-pkg/tagfile.h>
  23. #include <apt-pkg/indexrecords.h>
  24. #include <apt-pkg/acquire.h>
  25. #include <apt-pkg/hashes.h>
  26. #include <apt-pkg/indexfile.h>
  27. #include <apt-pkg/pkgcache.h>
  28. #include <apt-pkg/cacheiterators.h>
  29. #include <apt-pkg/pkgrecords.h>
  30. #include <stddef.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <iostream>
  34. #include <vector>
  35. #include <sys/stat.h>
  36. #include <unistd.h>
  37. #include <errno.h>
  38. #include <string>
  39. #include <sstream>
  40. #include <stdio.h>
  41. #include <ctime>
  42. #include <apti18n.h>
  43. /*}}}*/
  44. using namespace std;
  45. static void printHashSumComparision(std::string const &URI, HashStringList const &Expected, HashStringList const &Actual) /*{{{*/
  46. {
  47. if (_config->FindB("Debug::Acquire::HashSumMismatch", false) == false)
  48. return;
  49. std::cerr << std::endl << URI << ":" << std::endl << " Expected Hash: " << std::endl;
  50. for (HashStringList::const_iterator hs = Expected.begin(); hs != Expected.end(); ++hs)
  51. std::cerr << "\t- " << hs->toStr() << std::endl;
  52. std::cerr << " Actual Hash: " << std::endl;
  53. for (HashStringList::const_iterator hs = Actual.begin(); hs != Actual.end(); ++hs)
  54. std::cerr << "\t- " << hs->toStr() << std::endl;
  55. }
  56. /*}}}*/
  57. // Acquire::Item::Item - Constructor /*{{{*/
  58. pkgAcquire::Item::Item(pkgAcquire *Owner,
  59. HashStringList const &ExpectedHashes,
  60. pkgAcqMetaBase *TransactionManager)
  61. : Owner(Owner), FileSize(0), PartialSize(0), Mode(0), ID(0), Complete(false),
  62. Local(false), QueueCounter(0), TransactionManager(TransactionManager),
  63. ExpectedAdditionalItems(0), ExpectedHashes(ExpectedHashes)
  64. {
  65. Owner->Add(this);
  66. Status = StatIdle;
  67. if(TransactionManager != NULL)
  68. TransactionManager->Add(this);
  69. }
  70. /*}}}*/
  71. // Acquire::Item::~Item - Destructor /*{{{*/
  72. // ---------------------------------------------------------------------
  73. /* */
  74. pkgAcquire::Item::~Item()
  75. {
  76. Owner->Remove(this);
  77. }
  78. /*}}}*/
  79. // Acquire::Item::Failed - Item failed to download /*{{{*/
  80. // ---------------------------------------------------------------------
  81. /* We return to an idle state if there are still other queues that could
  82. fetch this object */
  83. void pkgAcquire::Item::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  84. {
  85. Status = StatIdle;
  86. if(ErrorText == "")
  87. ErrorText = LookupTag(Message,"Message");
  88. UsedMirror = LookupTag(Message,"UsedMirror");
  89. if (QueueCounter <= 1)
  90. {
  91. /* This indicates that the file is not available right now but might
  92. be sometime later. If we do a retry cycle then this should be
  93. retried [CDROMs] */
  94. if (Cnf->LocalOnly == true &&
  95. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  96. {
  97. Status = StatIdle;
  98. Dequeue();
  99. return;
  100. }
  101. Status = StatError;
  102. Dequeue();
  103. }
  104. // report mirror failure back to LP if we actually use a mirror
  105. string FailReason = LookupTag(Message, "FailReason");
  106. if(FailReason.size() != 0)
  107. ReportMirrorFailure(FailReason);
  108. else
  109. ReportMirrorFailure(ErrorText);
  110. }
  111. /*}}}*/
  112. // Acquire::Item::Start - Item has begun to download /*{{{*/
  113. // ---------------------------------------------------------------------
  114. /* Stash status and the file size. Note that setting Complete means
  115. sub-phases of the acquire process such as decompresion are operating */
  116. void pkgAcquire::Item::Start(string /*Message*/,unsigned long long Size)
  117. {
  118. Status = StatFetching;
  119. if (FileSize == 0 && Complete == false)
  120. FileSize = Size;
  121. }
  122. /*}}}*/
  123. // Acquire::Item::Done - Item downloaded OK /*{{{*/
  124. // ---------------------------------------------------------------------
  125. /* */
  126. void pkgAcquire::Item::Done(string Message,unsigned long long Size,HashStringList const &/*Hash*/,
  127. pkgAcquire::MethodConfig * /*Cnf*/)
  128. {
  129. // We just downloaded something..
  130. string FileName = LookupTag(Message,"Filename");
  131. UsedMirror = LookupTag(Message,"UsedMirror");
  132. if (Complete == false && !Local && FileName == DestFile)
  133. {
  134. if (Owner->Log != 0)
  135. Owner->Log->Fetched(Size,atoi(LookupTag(Message,"Resume-Point","0").c_str()));
  136. }
  137. if (FileSize == 0)
  138. FileSize= Size;
  139. Status = StatDone;
  140. ErrorText = string();
  141. Owner->Dequeue(this);
  142. }
  143. /*}}}*/
  144. // Acquire::Item::Rename - Rename a file /*{{{*/
  145. // ---------------------------------------------------------------------
  146. /* This helper function is used by a lot of item methods as their final
  147. step */
  148. bool pkgAcquire::Item::Rename(string From,string To)
  149. {
  150. if (rename(From.c_str(),To.c_str()) != 0)
  151. {
  152. char S[300];
  153. snprintf(S,sizeof(S),_("rename failed, %s (%s -> %s)."),strerror(errno),
  154. From.c_str(),To.c_str());
  155. Status = StatError;
  156. ErrorText += S;
  157. return false;
  158. }
  159. return true;
  160. }
  161. /*}}}*/
  162. bool pkgAcquire::Item::RenameOnError(pkgAcquire::Item::RenameOnErrorState const error)/*{{{*/
  163. {
  164. if(FileExists(DestFile))
  165. Rename(DestFile, DestFile + ".FAILED");
  166. switch (error)
  167. {
  168. case HashSumMismatch:
  169. ErrorText = _("Hash Sum mismatch");
  170. Status = StatAuthError;
  171. ReportMirrorFailure("HashChecksumFailure");
  172. break;
  173. case SizeMismatch:
  174. ErrorText = _("Size mismatch");
  175. Status = StatAuthError;
  176. ReportMirrorFailure("SizeFailure");
  177. break;
  178. case InvalidFormat:
  179. ErrorText = _("Invalid file format");
  180. Status = StatError;
  181. // do not report as usually its not the mirrors fault, but Portal/Proxy
  182. break;
  183. }
  184. return false;
  185. }
  186. /*}}}*/
  187. // Acquire::Item::ReportMirrorFailure /*{{{*/
  188. // ---------------------------------------------------------------------
  189. void pkgAcquire::Item::ReportMirrorFailure(string FailCode)
  190. {
  191. // we only act if a mirror was used at all
  192. if(UsedMirror.empty())
  193. return;
  194. #if 0
  195. std::cerr << "\nReportMirrorFailure: "
  196. << UsedMirror
  197. << " Uri: " << DescURI()
  198. << " FailCode: "
  199. << FailCode << std::endl;
  200. #endif
  201. const char *Args[40];
  202. unsigned int i = 0;
  203. string report = _config->Find("Methods::Mirror::ProblemReporting",
  204. "/usr/lib/apt/apt-report-mirror-failure");
  205. if(!FileExists(report))
  206. return;
  207. Args[i++] = report.c_str();
  208. Args[i++] = UsedMirror.c_str();
  209. Args[i++] = DescURI().c_str();
  210. Args[i++] = FailCode.c_str();
  211. Args[i++] = NULL;
  212. pid_t pid = ExecFork();
  213. if(pid < 0)
  214. {
  215. _error->Error("ReportMirrorFailure Fork failed");
  216. return;
  217. }
  218. else if(pid == 0)
  219. {
  220. execvp(Args[0], (char**)Args);
  221. std::cerr << "Could not exec " << Args[0] << std::endl;
  222. _exit(100);
  223. }
  224. if(!ExecWait(pid, "report-mirror-failure"))
  225. {
  226. _error->Warning("Couldn't report problem to '%s'",
  227. _config->Find("Methods::Mirror::ProblemReporting").c_str());
  228. }
  229. }
  230. /*}}}*/
  231. // AcqDiffIndex::AcqDiffIndex - Constructor /*{{{*/
  232. // ---------------------------------------------------------------------
  233. /* Get the DiffIndex file first and see if there are patches available
  234. * If so, create a pkgAcqIndexDiffs fetcher that will get and apply the
  235. * patches. If anything goes wrong in that process, it will fall back to
  236. * the original packages file
  237. */
  238. pkgAcqDiffIndex::pkgAcqDiffIndex(pkgAcquire *Owner,
  239. pkgAcqMetaBase *TransactionManager,
  240. IndexTarget const * const Target,
  241. HashStringList const &ExpectedHashes,
  242. indexRecords *MetaIndexParser)
  243. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes,
  244. MetaIndexParser), PackagesFileReadyInPartial(false)
  245. {
  246. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  247. RealURI = Target->URI;
  248. Desc.Owner = this;
  249. Desc.Description = Target->Description + "/DiffIndex";
  250. Desc.ShortDesc = Target->ShortDesc;
  251. Desc.URI = Target->URI + ".diff/Index";
  252. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  253. DestFile += URItoFileName(Desc.URI);
  254. if(Debug)
  255. std::clog << "pkgAcqDiffIndex: " << Desc.URI << std::endl;
  256. // look for the current package file
  257. CurrentPackagesFile = _config->FindDir("Dir::State::lists");
  258. CurrentPackagesFile += URItoFileName(RealURI);
  259. // FIXME: this file:/ check is a hack to prevent fetching
  260. // from local sources. this is really silly, and
  261. // should be fixed cleanly as soon as possible
  262. if(!FileExists(CurrentPackagesFile) ||
  263. Desc.URI.substr(0,strlen("file:/")) == "file:/")
  264. {
  265. // we don't have a pkg file or we don't want to queue
  266. if(Debug)
  267. std::clog << "No index file, local or canceld by user" << std::endl;
  268. Failed("", NULL);
  269. return;
  270. }
  271. if(Debug)
  272. std::clog << "pkgAcqDiffIndex::pkgAcqDiffIndex(): "
  273. << CurrentPackagesFile << std::endl;
  274. QueueURI(Desc);
  275. }
  276. /*}}}*/
  277. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  278. // ---------------------------------------------------------------------
  279. /* The only header we use is the last-modified header. */
  280. string pkgAcqDiffIndex::Custom600Headers() const
  281. {
  282. string Final = _config->FindDir("Dir::State::lists");
  283. Final += URItoFileName(Desc.URI);
  284. if(Debug)
  285. std::clog << "Custom600Header-IMS: " << Final << std::endl;
  286. struct stat Buf;
  287. if (stat(Final.c_str(),&Buf) != 0)
  288. return "\nIndex-File: true";
  289. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  290. }
  291. /*}}}*/
  292. bool pkgAcqDiffIndex::ParseDiffIndex(string IndexDiffFile) /*{{{*/
  293. {
  294. if(Debug)
  295. std::clog << "pkgAcqDiffIndex::ParseIndexDiff() " << IndexDiffFile
  296. << std::endl;
  297. pkgTagSection Tags;
  298. string ServerSha1;
  299. vector<DiffInfo> available_patches;
  300. FileFd Fd(IndexDiffFile,FileFd::ReadOnly);
  301. pkgTagFile TF(&Fd);
  302. if (_error->PendingError() == true)
  303. return false;
  304. if(TF.Step(Tags) == true)
  305. {
  306. bool found = false;
  307. DiffInfo d;
  308. string size;
  309. string const tmp = Tags.FindS("SHA1-Current");
  310. std::stringstream ss(tmp);
  311. ss >> ServerSha1 >> size;
  312. unsigned long const ServerSize = atol(size.c_str());
  313. FileFd fd(CurrentPackagesFile, FileFd::ReadOnly);
  314. SHA1Summation SHA1;
  315. SHA1.AddFD(fd);
  316. string const local_sha1 = SHA1.Result();
  317. if(local_sha1 == ServerSha1)
  318. {
  319. // we have the same sha1 as the server so we are done here
  320. if(Debug)
  321. std::clog << "Package file is up-to-date" << std::endl;
  322. // ensure we have no leftovers from previous runs
  323. std::string Partial = _config->FindDir("Dir::State::lists");
  324. Partial += "partial/" + URItoFileName(RealURI);
  325. unlink(Partial.c_str());
  326. // list cleanup needs to know that this file as well as the already
  327. // present index is ours, so we create an empty diff to save it for us
  328. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  329. ExpectedHashes, MetaIndexParser,
  330. ServerSha1, available_patches);
  331. return true;
  332. }
  333. else
  334. {
  335. if(Debug)
  336. std::clog << "SHA1-Current: " << ServerSha1 << " and we start at "<< fd.Name() << " " << fd.Size() << " " << local_sha1 << std::endl;
  337. // check the historie and see what patches we need
  338. string const history = Tags.FindS("SHA1-History");
  339. std::stringstream hist(history);
  340. while(hist >> d.sha1 >> size >> d.file)
  341. {
  342. // read until the first match is found
  343. // from that point on, we probably need all diffs
  344. if(d.sha1 == local_sha1)
  345. found=true;
  346. else if (found == false)
  347. continue;
  348. if(Debug)
  349. std::clog << "Need to get diff: " << d.file << std::endl;
  350. available_patches.push_back(d);
  351. }
  352. if (available_patches.empty() == false)
  353. {
  354. // patching with too many files is rather slow compared to a fast download
  355. unsigned long const fileLimit = _config->FindI("Acquire::PDiffs::FileLimit", 0);
  356. if (fileLimit != 0 && fileLimit < available_patches.size())
  357. {
  358. if (Debug)
  359. std::clog << "Need " << available_patches.size() << " diffs (Limit is " << fileLimit
  360. << ") so fallback to complete download" << std::endl;
  361. return false;
  362. }
  363. // see if the patches are too big
  364. found = false; // it was true and it will be true again at the end
  365. d = *available_patches.begin();
  366. string const firstPatch = d.file;
  367. unsigned long patchesSize = 0;
  368. std::stringstream patches(Tags.FindS("SHA1-Patches"));
  369. while(patches >> d.sha1 >> size >> d.file)
  370. {
  371. if (firstPatch == d.file)
  372. found = true;
  373. else if (found == false)
  374. continue;
  375. patchesSize += atol(size.c_str());
  376. }
  377. unsigned long const sizeLimit = ServerSize * _config->FindI("Acquire::PDiffs::SizeLimit", 100);
  378. if (sizeLimit > 0 && (sizeLimit/100) < patchesSize)
  379. {
  380. if (Debug)
  381. std::clog << "Need " << patchesSize << " bytes (Limit is " << sizeLimit/100
  382. << ") so fallback to complete download" << std::endl;
  383. return false;
  384. }
  385. }
  386. }
  387. // we have something, queue the next diff
  388. if(found)
  389. {
  390. // FIXME: make this use the method
  391. PackagesFileReadyInPartial = true;
  392. std::string Partial = _config->FindDir("Dir::State::lists");
  393. Partial += "partial/" + URItoFileName(RealURI);
  394. FileFd From(CurrentPackagesFile, FileFd::ReadOnly);
  395. FileFd To(Partial, FileFd::WriteEmpty);
  396. if(CopyFile(From, To) == false)
  397. return _error->Errno("CopyFile", "failed to copy");
  398. if(Debug)
  399. std::cerr << "Done copying " << CurrentPackagesFile
  400. << " -> " << Partial
  401. << std::endl;
  402. // queue the diffs
  403. string::size_type const last_space = Description.rfind(" ");
  404. if(last_space != string::npos)
  405. Description.erase(last_space, Description.size()-last_space);
  406. /* decide if we should download patches one by one or in one go:
  407. The first is good if the server merges patches, but many don't so client
  408. based merging can be attempt in which case the second is better.
  409. "bad things" will happen if patches are merged on the server,
  410. but client side merging is attempt as well */
  411. bool pdiff_merge = _config->FindB("Acquire::PDiffs::Merge", true);
  412. if (pdiff_merge == true)
  413. {
  414. // reprepro adds this flag if it has merged patches on the server
  415. std::string const precedence = Tags.FindS("X-Patch-Precedence");
  416. pdiff_merge = (precedence != "merged");
  417. }
  418. if (pdiff_merge == false)
  419. {
  420. new pkgAcqIndexDiffs(Owner, TransactionManager, Target, ExpectedHashes,
  421. MetaIndexParser,
  422. ServerSha1, available_patches);
  423. }
  424. else
  425. {
  426. std::vector<pkgAcqIndexMergeDiffs*> *diffs = new std::vector<pkgAcqIndexMergeDiffs*>(available_patches.size());
  427. for(size_t i = 0; i < available_patches.size(); ++i)
  428. (*diffs)[i] = new pkgAcqIndexMergeDiffs(Owner,
  429. TransactionManager,
  430. Target,
  431. ExpectedHashes,
  432. MetaIndexParser,
  433. available_patches[i],
  434. diffs);
  435. }
  436. Complete = false;
  437. Status = StatDone;
  438. Dequeue();
  439. return true;
  440. }
  441. }
  442. // Nothing found, report and return false
  443. // Failing here is ok, if we return false later, the full
  444. // IndexFile is queued
  445. if(Debug)
  446. std::clog << "Can't find a patch in the index file" << std::endl;
  447. return false;
  448. }
  449. /*}}}*/
  450. void pkgAcqDiffIndex::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  451. {
  452. if(Debug)
  453. std::clog << "pkgAcqDiffIndex failed: " << Desc.URI << " with " << Message << std::endl
  454. << "Falling back to normal index file acquire" << std::endl;
  455. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  456. Complete = false;
  457. Status = StatDone;
  458. Dequeue();
  459. }
  460. /*}}}*/
  461. void pkgAcqDiffIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  462. pkgAcquire::MethodConfig *Cnf)
  463. {
  464. if(Debug)
  465. std::clog << "pkgAcqDiffIndex::Done(): " << Desc.URI << std::endl;
  466. Item::Done(Message, Size, Hashes, Cnf);
  467. string FinalFile;
  468. FinalFile = _config->FindDir("Dir::State::lists")+URItoFileName(RealURI);
  469. // success in downloading the index
  470. // rename the index
  471. FinalFile += string(".IndexDiff");
  472. if(Debug)
  473. std::clog << "Renaming: " << DestFile << " -> " << FinalFile
  474. << std::endl;
  475. Rename(DestFile,FinalFile);
  476. chmod(FinalFile.c_str(),0644);
  477. DestFile = FinalFile;
  478. if(!ParseDiffIndex(DestFile))
  479. return Failed("", NULL);
  480. Complete = true;
  481. Status = StatDone;
  482. Dequeue();
  483. return;
  484. }
  485. /*}}}*/
  486. // AcqIndexDiffs::AcqIndexDiffs - Constructor /*{{{*/
  487. // ---------------------------------------------------------------------
  488. /* The package diff is added to the queue. one object is constructed
  489. * for each diff and the index
  490. */
  491. pkgAcqIndexDiffs::pkgAcqIndexDiffs(pkgAcquire *Owner,
  492. pkgAcqMetaBase *TransactionManager,
  493. struct IndexTarget const * const Target,
  494. HashStringList const &ExpectedHashes,
  495. indexRecords *MetaIndexParser,
  496. string ServerSha1,
  497. vector<DiffInfo> diffs)
  498. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  499. available_patches(diffs), ServerSha1(ServerSha1)
  500. {
  501. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  502. DestFile += URItoFileName(Target->URI);
  503. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  504. RealURI = Target->URI;
  505. Desc.Owner = this;
  506. Description = Target->Description;
  507. Desc.ShortDesc = Target->ShortDesc;
  508. if(available_patches.empty() == true)
  509. {
  510. // we are done (yeah!), check hashes against the final file
  511. DestFile = _config->FindDir("Dir::State::lists");
  512. DestFile += URItoFileName(Target->URI);
  513. Finish(true);
  514. }
  515. else
  516. {
  517. // get the next diff
  518. State = StateFetchDiff;
  519. QueueNextDiff();
  520. }
  521. }
  522. /*}}}*/
  523. void pkgAcqIndexDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  524. {
  525. if(Debug)
  526. std::clog << "pkgAcqIndexDiffs failed: " << Desc.URI << " with " << Message << std::endl
  527. << "Falling back to normal index file acquire" << std::endl;
  528. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  529. Finish();
  530. }
  531. /*}}}*/
  532. // Finish - helper that cleans the item out of the fetcher queue /*{{{*/
  533. void pkgAcqIndexDiffs::Finish(bool allDone)
  534. {
  535. if(Debug)
  536. std::clog << "pkgAcqIndexDiffs::Finish(): "
  537. << allDone << " "
  538. << Desc.URI << std::endl;
  539. // we restore the original name, this is required, otherwise
  540. // the file will be cleaned
  541. if(allDone)
  542. {
  543. if(HashSums().usable() && !HashSums().VerifyFile(DestFile))
  544. {
  545. RenameOnError(HashSumMismatch);
  546. Dequeue();
  547. return;
  548. }
  549. // queue for copy
  550. PartialFile = _config->FindDir("Dir::State::lists")+"partial/"+URItoFileName(RealURI);
  551. DestFile = _config->FindDir("Dir::State::lists");
  552. DestFile += URItoFileName(RealURI);
  553. // this happens if we have a up-to-date indexfile
  554. if(!FileExists(PartialFile))
  555. PartialFile = DestFile;
  556. // this is for the "real" finish
  557. Complete = true;
  558. Status = StatDone;
  559. Dequeue();
  560. if(Debug)
  561. std::clog << "\n\nallDone: " << DestFile << "\n" << std::endl;
  562. return;
  563. }
  564. if(Debug)
  565. std::clog << "Finishing: " << Desc.URI << std::endl;
  566. Complete = false;
  567. Status = StatDone;
  568. Dequeue();
  569. return;
  570. }
  571. /*}}}*/
  572. bool pkgAcqIndexDiffs::QueueNextDiff() /*{{{*/
  573. {
  574. // calc sha1 of the just patched file
  575. string FinalFile = _config->FindDir("Dir::State::lists");
  576. FinalFile += "partial/" + URItoFileName(RealURI);
  577. if(!FileExists(FinalFile))
  578. {
  579. Failed("No FinalFile " + FinalFile + " available", NULL);
  580. return false;
  581. }
  582. FileFd fd(FinalFile, FileFd::ReadOnly);
  583. SHA1Summation SHA1;
  584. SHA1.AddFD(fd);
  585. string local_sha1 = string(SHA1.Result());
  586. if(Debug)
  587. std::clog << "QueueNextDiff: "
  588. << FinalFile << " (" << local_sha1 << ")"<<std::endl;
  589. // final file reached before all patches are applied
  590. if(local_sha1 == ServerSha1)
  591. {
  592. Finish(true);
  593. return true;
  594. }
  595. // remove all patches until the next matching patch is found
  596. // this requires the Index file to be ordered
  597. for(vector<DiffInfo>::iterator I=available_patches.begin();
  598. available_patches.empty() == false &&
  599. I != available_patches.end() &&
  600. I->sha1 != local_sha1;
  601. ++I)
  602. {
  603. available_patches.erase(I);
  604. }
  605. // error checking and falling back if no patch was found
  606. if(available_patches.empty() == true)
  607. {
  608. Failed("No patches available", NULL);
  609. return false;
  610. }
  611. // queue the right diff
  612. Desc.URI = RealURI + ".diff/" + available_patches[0].file + ".gz";
  613. Desc.Description = Description + " " + available_patches[0].file + string(".pdiff");
  614. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  615. DestFile += URItoFileName(RealURI + ".diff/" + available_patches[0].file);
  616. if(Debug)
  617. std::clog << "pkgAcqIndexDiffs::QueueNextDiff(): " << Desc.URI << std::endl;
  618. QueueURI(Desc);
  619. return true;
  620. }
  621. /*}}}*/
  622. void pkgAcqIndexDiffs::Done(string Message,unsigned long long Size, HashStringList const &Hashes, /*{{{*/
  623. pkgAcquire::MethodConfig *Cnf)
  624. {
  625. if(Debug)
  626. std::clog << "pkgAcqIndexDiffs::Done(): " << Desc.URI << std::endl;
  627. Item::Done(Message, Size, Hashes, Cnf);
  628. string FinalFile;
  629. FinalFile = _config->FindDir("Dir::State::lists")+"partial/"+URItoFileName(RealURI);
  630. // success in downloading a diff, enter ApplyDiff state
  631. if(State == StateFetchDiff)
  632. {
  633. // rred excepts the patch as $FinalFile.ed
  634. Rename(DestFile,FinalFile+".ed");
  635. if(Debug)
  636. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  637. State = StateApplyDiff;
  638. Local = true;
  639. Desc.URI = "rred:" + FinalFile;
  640. QueueURI(Desc);
  641. Mode = "rred";
  642. return;
  643. }
  644. // success in download/apply a diff, queue next (if needed)
  645. if(State == StateApplyDiff)
  646. {
  647. // remove the just applied patch
  648. available_patches.erase(available_patches.begin());
  649. unlink((FinalFile + ".ed").c_str());
  650. // move into place
  651. if(Debug)
  652. {
  653. std::clog << "Moving patched file in place: " << std::endl
  654. << DestFile << " -> " << FinalFile << std::endl;
  655. }
  656. Rename(DestFile,FinalFile);
  657. chmod(FinalFile.c_str(),0644);
  658. // see if there is more to download
  659. if(available_patches.empty() == false) {
  660. new pkgAcqIndexDiffs(Owner, TransactionManager, Target,
  661. ExpectedHashes, MetaIndexParser,
  662. ServerSha1, available_patches);
  663. return Finish();
  664. } else
  665. // update
  666. DestFile = FinalFile;
  667. return Finish(true);
  668. }
  669. }
  670. /*}}}*/
  671. // AcqIndexMergeDiffs::AcqIndexMergeDiffs - Constructor /*{{{*/
  672. pkgAcqIndexMergeDiffs::pkgAcqIndexMergeDiffs(pkgAcquire *Owner,
  673. pkgAcqMetaBase *TransactionManager,
  674. struct IndexTarget const * const Target,
  675. HashStringList const &ExpectedHashes,
  676. indexRecords *MetaIndexParser,
  677. DiffInfo const &patch,
  678. std::vector<pkgAcqIndexMergeDiffs*> const * const allPatches)
  679. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser),
  680. patch(patch), allPatches(allPatches), State(StateFetchDiff)
  681. {
  682. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  683. DestFile += URItoFileName(Target->URI);
  684. Debug = _config->FindB("Debug::pkgAcquire::Diffs",false);
  685. RealURI = Target->URI;
  686. Desc.Owner = this;
  687. Description = Target->Description;
  688. Desc.ShortDesc = Target->ShortDesc;
  689. Desc.URI = RealURI + ".diff/" + patch.file + ".gz";
  690. Desc.Description = Description + " " + patch.file + string(".pdiff");
  691. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  692. DestFile += URItoFileName(RealURI + ".diff/" + patch.file);
  693. if(Debug)
  694. std::clog << "pkgAcqIndexMergeDiffs: " << Desc.URI << std::endl;
  695. QueueURI(Desc);
  696. }
  697. /*}}}*/
  698. void pkgAcqIndexMergeDiffs::Failed(string Message,pkgAcquire::MethodConfig * /*Cnf*/)/*{{{*/
  699. {
  700. if(Debug)
  701. std::clog << "pkgAcqIndexMergeDiffs failed: " << Desc.URI << " with " << Message << std::endl;
  702. Complete = false;
  703. Status = StatDone;
  704. Dequeue();
  705. // check if we are the first to fail, otherwise we are done here
  706. State = StateDoneDiff;
  707. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  708. I != allPatches->end(); ++I)
  709. if ((*I)->State == StateErrorDiff)
  710. return;
  711. // first failure means we should fallback
  712. State = StateErrorDiff;
  713. std::clog << "Falling back to normal index file acquire" << std::endl;
  714. new pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser);
  715. }
  716. /*}}}*/
  717. void pkgAcqIndexMergeDiffs::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  718. pkgAcquire::MethodConfig *Cnf)
  719. {
  720. if(Debug)
  721. std::clog << "pkgAcqIndexMergeDiffs::Done(): " << Desc.URI << std::endl;
  722. Item::Done(Message,Size,Hashes,Cnf);
  723. string const FinalFile = _config->FindDir("Dir::State::lists") + "partial/" + URItoFileName(RealURI);
  724. if (State == StateFetchDiff)
  725. {
  726. // rred expects the patch as $FinalFile.ed.$patchname.gz
  727. Rename(DestFile, FinalFile + ".ed." + patch.file + ".gz");
  728. // check if this is the last completed diff
  729. State = StateDoneDiff;
  730. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  731. I != allPatches->end(); ++I)
  732. if ((*I)->State != StateDoneDiff)
  733. {
  734. if(Debug)
  735. std::clog << "Not the last done diff in the batch: " << Desc.URI << std::endl;
  736. return;
  737. }
  738. // this is the last completed diff, so we are ready to apply now
  739. State = StateApplyDiff;
  740. if(Debug)
  741. std::clog << "Sending to rred method: " << FinalFile << std::endl;
  742. Local = true;
  743. Desc.URI = "rred:" + FinalFile;
  744. QueueURI(Desc);
  745. Mode = "rred";
  746. return;
  747. }
  748. // success in download/apply all diffs, clean up
  749. else if (State == StateApplyDiff)
  750. {
  751. // see if we really got the expected file
  752. if(ExpectedHashes.usable() && !ExpectedHashes.VerifyFile(DestFile))
  753. {
  754. RenameOnError(HashSumMismatch);
  755. return;
  756. }
  757. std::string FinalFile = _config->FindDir("Dir::State::lists");
  758. FinalFile += URItoFileName(RealURI);
  759. // move the result into place
  760. if(Debug)
  761. std::clog << "Queue patched file in place: " << std::endl
  762. << DestFile << " -> " << FinalFile << std::endl;
  763. // queue for copy by the transaction manager
  764. PartialFile = DestFile;
  765. DestFile = FinalFile;
  766. // ensure the ed's are gone regardless of list-cleanup
  767. for (std::vector<pkgAcqIndexMergeDiffs *>::const_iterator I = allPatches->begin();
  768. I != allPatches->end(); ++I)
  769. {
  770. std::string PartialFile = _config->FindDir("Dir::State::lists");
  771. PartialFile += "partial/" + URItoFileName(RealURI);
  772. std::string patch = PartialFile + ".ed." + (*I)->patch.file + ".gz";
  773. std::cerr << patch << std::endl;
  774. unlink(patch.c_str());
  775. }
  776. // all set and done
  777. Complete = true;
  778. if(Debug)
  779. std::clog << "allDone: " << DestFile << "\n" << std::endl;
  780. }
  781. }
  782. /*}}}*/
  783. // AcqIndex::AcqIndex - Constructor /*{{{*/
  784. // ---------------------------------------------------------------------
  785. /* The package file is added to the queue and a second class is
  786. instantiated to fetch the revision file */
  787. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  788. string URI,string URIDesc,string ShortDesc,
  789. HashStringList const &ExpectedHash)
  790. : pkgAcqBaseIndex(Owner, 0, NULL, ExpectedHash, NULL), RealURI(URI)
  791. {
  792. AutoSelectCompression();
  793. Init(URI, URIDesc, ShortDesc);
  794. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  795. std::clog << "New pkgIndex with TransactionManager "
  796. << TransactionManager << std::endl;
  797. }
  798. /*}}}*/
  799. // AcqIndex::AcqIndex - Constructor /*{{{*/
  800. // ---------------------------------------------------------------------
  801. pkgAcqIndex::pkgAcqIndex(pkgAcquire *Owner,
  802. pkgAcqMetaBase *TransactionManager,
  803. IndexTarget const *Target,
  804. HashStringList const &ExpectedHash,
  805. indexRecords *MetaIndexParser)
  806. : pkgAcqBaseIndex(Owner, TransactionManager, Target, ExpectedHash,
  807. MetaIndexParser), RealURI(Target->URI)
  808. {
  809. // autoselect the compression method
  810. AutoSelectCompression();
  811. Init(Target->URI, Target->Description, Target->ShortDesc);
  812. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  813. std::clog << "New pkgIndex with TransactionManager "
  814. << TransactionManager << std::endl;
  815. }
  816. /*}}}*/
  817. // AcqIndex::AutoSelectCompression - Select compression /*{{{*/
  818. // ---------------------------------------------------------------------
  819. void pkgAcqIndex::AutoSelectCompression()
  820. {
  821. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  822. CompressionExtension = "";
  823. if (ExpectedHashes.usable())
  824. {
  825. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  826. if (*t == "uncompressed" || MetaIndexParser->Exists(string(Target->MetaKey).append(".").append(*t)) == true)
  827. CompressionExtension.append(*t).append(" ");
  828. }
  829. else
  830. {
  831. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  832. CompressionExtension.append(*t).append(" ");
  833. }
  834. if (CompressionExtension.empty() == false)
  835. CompressionExtension.erase(CompressionExtension.end()-1);
  836. }
  837. // AcqIndex::Init - defered Constructor /*{{{*/
  838. // ---------------------------------------------------------------------
  839. void pkgAcqIndex::Init(string const &URI, string const &URIDesc,
  840. string const &ShortDesc)
  841. {
  842. Decompression = false;
  843. Erase = false;
  844. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  845. DestFile += URItoFileName(URI);
  846. std::string const comprExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  847. if (comprExt == "uncompressed")
  848. {
  849. Desc.URI = URI;
  850. if(Target)
  851. MetaKey = string(Target->MetaKey);
  852. }
  853. else
  854. {
  855. Desc.URI = URI + '.' + comprExt;
  856. if(Target)
  857. MetaKey = string(Target->MetaKey) + '.' + comprExt;
  858. }
  859. // load the filesize
  860. if(MetaIndexParser)
  861. {
  862. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  863. if(Record)
  864. FileSize = Record->Size;
  865. InitByHashIfNeeded(MetaKey);
  866. }
  867. Desc.Description = URIDesc;
  868. Desc.Owner = this;
  869. Desc.ShortDesc = ShortDesc;
  870. QueueURI(Desc);
  871. }
  872. /*}}}*/
  873. // AcqIndex::AdjustForByHash - modify URI for by-hash support /*{{{*/
  874. // ---------------------------------------------------------------------
  875. /* */
  876. void pkgAcqIndex::InitByHashIfNeeded(const std::string MetaKey)
  877. {
  878. // TODO:
  879. // - (maybe?) add support for by-hash into the sources.list as flag
  880. // - make apt-ftparchive generate the hashes (and expire?)
  881. std::string HostKnob = "APT::Acquire::" + ::URI(Desc.URI).Host + "::By-Hash";
  882. if(_config->FindB("APT::Acquire::By-Hash", false) == true ||
  883. _config->FindB(HostKnob, false) == true ||
  884. MetaIndexParser->GetSupportsAcquireByHash())
  885. {
  886. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  887. if(Record)
  888. {
  889. // FIXME: should we really use the best hash here? or a fixed one?
  890. const HashString *TargetHash = Record->Hashes.find("");
  891. std::string ByHash = "/by-hash/" + TargetHash->HashType() + "/" + TargetHash->HashValue();
  892. size_t trailing_slash = Desc.URI.find_last_of("/");
  893. Desc.URI = Desc.URI.replace(
  894. trailing_slash,
  895. Desc.URI.substr(trailing_slash+1).size()+1,
  896. ByHash);
  897. } else {
  898. _error->Warning(
  899. "Fetching ByHash requested but can not find record for %s",
  900. MetaKey.c_str());
  901. }
  902. }
  903. }
  904. /*}}}*/
  905. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  906. // ---------------------------------------------------------------------
  907. /* The only header we use is the last-modified header. */
  908. string pkgAcqIndex::Custom600Headers() const
  909. {
  910. string Final = GetFinalFilename();
  911. string msg = "\nIndex-File: true";
  912. struct stat Buf;
  913. if (stat(Final.c_str(),&Buf) == 0)
  914. msg += "\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  915. return msg;
  916. }
  917. /*}}}*/
  918. // pkgAcqIndex::Failed - getting the indexfile failed /*{{{*/
  919. // ---------------------------------------------------------------------
  920. /* */
  921. void pkgAcqIndex::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  922. {
  923. size_t const nextExt = CompressionExtension.find(' ');
  924. if (nextExt != std::string::npos)
  925. {
  926. CompressionExtension = CompressionExtension.substr(nextExt+1);
  927. Init(RealURI, Desc.Description, Desc.ShortDesc);
  928. return;
  929. }
  930. // on decompression failure, remove bad versions in partial/
  931. if (Decompression && Erase) {
  932. string s = _config->FindDir("Dir::State::lists") + "partial/";
  933. s.append(URItoFileName(RealURI));
  934. unlink(s.c_str());
  935. }
  936. Item::Failed(Message,Cnf);
  937. /// cancel the entire transaction
  938. TransactionManager->AbortTransaction();
  939. }
  940. /*}}}*/
  941. // pkgAcqIndex::GetFinalFilename - Return the full final file path /*{{{*/
  942. // ---------------------------------------------------------------------
  943. /* */
  944. std::string pkgAcqIndex::GetFinalFilename() const
  945. {
  946. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  947. std::string FinalFile = _config->FindDir("Dir::State::lists");
  948. FinalFile += URItoFileName(RealURI);
  949. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  950. FinalFile += ".gz";
  951. return FinalFile;
  952. }
  953. /*}}}*/
  954. // AcqIndex::ReverifyAfterIMS - Reverify index after an ims-hit /*{{{*/
  955. // ---------------------------------------------------------------------
  956. /* */
  957. void pkgAcqIndex::ReverifyAfterIMS()
  958. {
  959. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  960. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  961. DestFile += ".gz";
  962. // copy FinalFile into partial/ so that we check the hash again
  963. string FinalFile = GetFinalFilename();
  964. Decompression = true;
  965. Desc.URI = "copy:" + FinalFile;
  966. QueueURI(Desc);
  967. }
  968. /*}}}*/
  969. // AcqIndex::Done - Finished a fetch /*{{{*/
  970. // ---------------------------------------------------------------------
  971. /* This goes through a number of states.. On the initial fetch the
  972. method could possibly return an alternate filename which points
  973. to the uncompressed version of the file. If this is so the file
  974. is copied into the partial directory. In all other cases the file
  975. is decompressed with a compressed uri. */
  976. void pkgAcqIndex::Done(string Message, unsigned long long Size,
  977. HashStringList const &Hashes,
  978. pkgAcquire::MethodConfig *Cfg)
  979. {
  980. Item::Done(Message,Size,Hashes,Cfg);
  981. std::string const compExt = CompressionExtension.substr(0, CompressionExtension.find(' '));
  982. if (Decompression == true)
  983. {
  984. if (ExpectedHashes.usable() && ExpectedHashes != Hashes)
  985. {
  986. Desc.URI = RealURI;
  987. RenameOnError(HashSumMismatch);
  988. printHashSumComparision(RealURI, ExpectedHashes, Hashes);
  989. Failed(Message, Cfg);
  990. return;
  991. }
  992. // FIXME: this can go away once we only ever download stuff that
  993. // has a valid hash and we never do GET based probing
  994. //
  995. /* Always verify the index file for correctness (all indexes must
  996. * have a Package field) (LP: #346386) (Closes: #627642)
  997. */
  998. FileFd fd(DestFile, FileFd::ReadOnly, FileFd::Extension);
  999. // Only test for correctness if the content of the file is not empty
  1000. // (empty is ok)
  1001. if (fd.Size() > 0)
  1002. {
  1003. pkgTagSection sec;
  1004. pkgTagFile tag(&fd);
  1005. // all our current indexes have a field 'Package' in each section
  1006. if (_error->PendingError() == true || tag.Step(sec) == false || sec.Exists("Package") == false)
  1007. {
  1008. RenameOnError(InvalidFormat);
  1009. Failed(Message, Cfg);
  1010. return;
  1011. }
  1012. }
  1013. // FIXME: can we void the "Erase" bool here as its very non-local?
  1014. std::string CompressedFile = _config->FindDir("Dir::State::lists") + "partial/";
  1015. CompressedFile += URItoFileName(RealURI);
  1016. // Remove the compressed version.
  1017. if (Erase == true)
  1018. unlink(CompressedFile.c_str());
  1019. // Done, queue for rename on transaction finished
  1020. PartialFile = DestFile;
  1021. DestFile = GetFinalFilename();
  1022. return;
  1023. }
  1024. // FIXME: use the same method to find
  1025. // check the compressed hash too
  1026. if(MetaKey != "" && Hashes.size() > 0)
  1027. {
  1028. indexRecords::checkSum *Record = MetaIndexParser->Lookup(MetaKey);
  1029. if(Record && Record->Hashes.usable() && Hashes != Record->Hashes)
  1030. {
  1031. RenameOnError(HashSumMismatch);
  1032. printHashSumComparision(RealURI, Record->Hashes, Hashes);
  1033. Failed(Message, Cfg);
  1034. return;
  1035. }
  1036. }
  1037. Erase = false;
  1038. Complete = true;
  1039. // Handle the unzipd case
  1040. string FileName = LookupTag(Message,"Alt-Filename");
  1041. if (FileName.empty() == false)
  1042. {
  1043. Decompression = true;
  1044. Local = true;
  1045. DestFile += ".decomp";
  1046. Desc.URI = "copy:" + FileName;
  1047. QueueURI(Desc);
  1048. Mode = "copy";
  1049. return;
  1050. }
  1051. FileName = LookupTag(Message,"Filename");
  1052. if (FileName.empty() == true)
  1053. {
  1054. Status = StatError;
  1055. ErrorText = "Method gave a blank filename";
  1056. }
  1057. if (FileName == DestFile)
  1058. Erase = true;
  1059. else
  1060. Local = true;
  1061. // do not reverify cdrom sources as apt-cdrom may rewrite the Packages
  1062. // file when its doing the indexcopy
  1063. if (RealURI.substr(0,6) == "cdrom:" &&
  1064. StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1065. return;
  1066. // The files timestamp matches, reverify by copy into partial/
  1067. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1068. {
  1069. Erase = false;
  1070. ReverifyAfterIMS();
  1071. return;
  1072. }
  1073. string decompProg;
  1074. // If we enable compressed indexes, queue for hash verification
  1075. if (_config->FindB("Acquire::GzipIndexes",false) && compExt == "gz")
  1076. {
  1077. DestFile = _config->FindDir("Dir::State::lists");
  1078. DestFile += URItoFileName(RealURI) + ".gz";
  1079. Decompression = true;
  1080. Desc.URI = "copy:" + FileName;
  1081. QueueURI(Desc);
  1082. return;
  1083. }
  1084. // get the binary name for your used compression type
  1085. decompProg = _config->Find(string("Acquire::CompressionTypes::").append(compExt),"");
  1086. if(decompProg.empty() == false);
  1087. else if(compExt == "uncompressed")
  1088. decompProg = "copy";
  1089. else {
  1090. _error->Error("Unsupported extension: %s", compExt.c_str());
  1091. return;
  1092. }
  1093. Decompression = true;
  1094. DestFile += ".decomp";
  1095. Desc.URI = decompProg + ":" + FileName;
  1096. QueueURI(Desc);
  1097. // FIXME: this points to a c++ string that goes out of scope
  1098. Mode = decompProg.c_str();
  1099. }
  1100. /*}}}*/
  1101. // AcqIndexTrans::pkgAcqIndexTrans - Constructor /*{{{*/
  1102. // ---------------------------------------------------------------------
  1103. /* The Translation file is added to the queue */
  1104. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1105. string URI,string URIDesc,string ShortDesc)
  1106. : pkgAcqIndex(Owner, URI, URIDesc, ShortDesc, HashStringList())
  1107. {
  1108. }
  1109. /*}}}*/
  1110. pkgAcqIndexTrans::pkgAcqIndexTrans(pkgAcquire *Owner,
  1111. pkgAcqMetaBase *TransactionManager,
  1112. IndexTarget const * const Target,
  1113. HashStringList const &ExpectedHashes,
  1114. indexRecords *MetaIndexParser)
  1115. : pkgAcqIndex(Owner, TransactionManager, Target, ExpectedHashes, MetaIndexParser)
  1116. {
  1117. // load the filesize
  1118. indexRecords::checkSum *Record = MetaIndexParser->Lookup(string(Target->MetaKey));
  1119. if(Record)
  1120. FileSize = Record->Size;
  1121. }
  1122. /*}}}*/
  1123. // AcqIndexTrans::Custom600Headers - Insert custom request headers /*{{{*/
  1124. // ---------------------------------------------------------------------
  1125. string pkgAcqIndexTrans::Custom600Headers() const
  1126. {
  1127. string Final = GetFinalFilename();
  1128. struct stat Buf;
  1129. if (stat(Final.c_str(),&Buf) != 0)
  1130. return "\nFail-Ignore: true\nIndex-File: true";
  1131. return "\nFail-Ignore: true\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1132. }
  1133. /*}}}*/
  1134. // AcqIndexTrans::Failed - Silence failure messages for missing files /*{{{*/
  1135. // ---------------------------------------------------------------------
  1136. /* */
  1137. void pkgAcqIndexTrans::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  1138. {
  1139. size_t const nextExt = CompressionExtension.find(' ');
  1140. if (nextExt != std::string::npos)
  1141. {
  1142. CompressionExtension = CompressionExtension.substr(nextExt+1);
  1143. Init(RealURI, Desc.Description, Desc.ShortDesc);
  1144. Status = StatIdle;
  1145. return;
  1146. }
  1147. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1148. if (Cnf->LocalOnly == true ||
  1149. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1150. {
  1151. // Ignore this
  1152. Status = StatDone;
  1153. Complete = false;
  1154. Dequeue();
  1155. return;
  1156. }
  1157. Item::Failed(Message,Cnf);
  1158. }
  1159. /*}}}*/
  1160. void pkgAcqMetaBase::Add(Item *I)
  1161. {
  1162. Transaction.push_back(I);
  1163. }
  1164. void pkgAcqMetaBase::AbortTransaction()
  1165. {
  1166. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1167. std::clog << "AbortTransaction: " << TransactionManager << std::endl;
  1168. for (std::vector<Item*>::iterator I = Transaction.begin();
  1169. I != Transaction.end(); ++I)
  1170. {
  1171. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1172. std::clog << " Cancel: " << (*I)->DestFile << std::endl;
  1173. // the transaction will abort, so stop anything that is idle
  1174. if ((*I)->Status == pkgAcquire::Item::StatIdle)
  1175. (*I)->Status = pkgAcquire::Item::StatDone;
  1176. }
  1177. }
  1178. /*}}}*/
  1179. bool pkgAcqMetaBase::TransactionHasError()
  1180. {
  1181. for (pkgAcquire::ItemIterator I = Transaction.begin();
  1182. I != Transaction.end(); ++I)
  1183. if((*I)->Status != pkgAcquire::Item::StatDone &&
  1184. (*I)->Status != pkgAcquire::Item::StatIdle)
  1185. return true;
  1186. return false;
  1187. }
  1188. // Acquire::CommitTransaction - Commit a transaction /*{{{*/
  1189. void pkgAcqMetaBase::CommitTransaction()
  1190. {
  1191. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1192. std::clog << "CommitTransaction: " << this << std::endl;
  1193. // move new files into place *and* remove files that are not
  1194. // part of the transaction but are still on disk
  1195. for (std::vector<Item*>::iterator I = Transaction.begin();
  1196. I != Transaction.end(); ++I)
  1197. {
  1198. if((*I)->PartialFile != "")
  1199. {
  1200. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1201. std::clog << "mv "
  1202. << (*I)->PartialFile << " -> "
  1203. << (*I)->DestFile << " "
  1204. << (*I)->DescURI()
  1205. << std::endl;
  1206. Rename((*I)->PartialFile, (*I)->DestFile);
  1207. chmod((*I)->DestFile.c_str(),0644);
  1208. } else {
  1209. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1210. std::clog << "rm "
  1211. << (*I)->DestFile
  1212. << " "
  1213. << (*I)->DescURI()
  1214. << std::endl;
  1215. unlink((*I)->DestFile.c_str());
  1216. }
  1217. // mark that this transaction is finished
  1218. (*I)->TransactionManager = 0;
  1219. }
  1220. }
  1221. /*{{{*/
  1222. bool pkgAcqMetaBase::GenerateAuthWarning(const std::string &RealURI,
  1223. const std::string &Message)
  1224. {
  1225. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1226. if(FileExists(Final))
  1227. {
  1228. Status = StatTransientNetworkError;
  1229. _error->Warning(_("An error occurred during the signature "
  1230. "verification. The repository is not updated "
  1231. "and the previous index files will be used. "
  1232. "GPG error: %s: %s\n"),
  1233. Desc.Description.c_str(),
  1234. LookupTag(Message,"Message").c_str());
  1235. RunScripts("APT::Update::Auth-Failure");
  1236. return true;
  1237. } else if (LookupTag(Message,"Message").find("NODATA") != string::npos) {
  1238. /* Invalid signature file, reject (LP: #346386) (Closes: #627642) */
  1239. _error->Error(_("GPG error: %s: %s"),
  1240. Desc.Description.c_str(),
  1241. LookupTag(Message,"Message").c_str());
  1242. Status = StatError;
  1243. return true;
  1244. } else {
  1245. _error->Warning(_("GPG error: %s: %s"),
  1246. Desc.Description.c_str(),
  1247. LookupTag(Message,"Message").c_str());
  1248. }
  1249. // gpgv method failed
  1250. ReportMirrorFailure("GPGFailure");
  1251. return false;
  1252. }
  1253. /*}}}*/
  1254. pkgAcqMetaSig::pkgAcqMetaSig(pkgAcquire *Owner, /*{{{*/
  1255. pkgAcqMetaBase *TransactionManager,
  1256. string URI,string URIDesc,string ShortDesc,
  1257. string MetaIndexFile,
  1258. const vector<IndexTarget*>* IndexTargets,
  1259. indexRecords* MetaIndexParser) :
  1260. pkgAcqMetaBase(Owner, HashStringList(), TransactionManager), RealURI(URI),
  1261. MetaIndexParser(MetaIndexParser), MetaIndexFile(MetaIndexFile),
  1262. IndexTargets(IndexTargets), AuthPass(false), IMSHit(false)
  1263. {
  1264. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1265. DestFile += URItoFileName(URI);
  1266. // remove any partial downloaded sig-file in partial/.
  1267. // it may confuse proxies and is too small to warrant a
  1268. // partial download anyway
  1269. unlink(DestFile.c_str());
  1270. // set the TransactionManager
  1271. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1272. std::clog << "New pkgAcqMetaSig with TransactionManager "
  1273. << TransactionManager << std::endl;
  1274. // Create the item
  1275. Desc.Description = URIDesc;
  1276. Desc.Owner = this;
  1277. Desc.ShortDesc = ShortDesc;
  1278. Desc.URI = URI;
  1279. QueueURI(Desc);
  1280. }
  1281. /*}}}*/
  1282. pkgAcqMetaSig::~pkgAcqMetaSig() /*{{{*/
  1283. {
  1284. }
  1285. /*}}}*/
  1286. // pkgAcqMetaSig::Custom600Headers - Insert custom request headers /*{{{*/
  1287. // ---------------------------------------------------------------------
  1288. /* The only header we use is the last-modified header. */
  1289. string pkgAcqMetaSig::Custom600Headers() const
  1290. {
  1291. string FinalFile = _config->FindDir("Dir::State::lists");
  1292. FinalFile += URItoFileName(RealURI);
  1293. struct stat Buf;
  1294. if (stat(FinalFile.c_str(),&Buf) != 0)
  1295. return "\nIndex-File: true";
  1296. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1297. }
  1298. void pkgAcqMetaSig::Done(string Message,unsigned long long Size, HashStringList const &Hashes,
  1299. pkgAcquire::MethodConfig *Cfg)
  1300. {
  1301. Item::Done(Message, Size, Hashes, Cfg);
  1302. string FileName = LookupTag(Message,"Filename");
  1303. if (FileName.empty() == true)
  1304. {
  1305. Status = StatError;
  1306. ErrorText = "Method gave a blank filename";
  1307. return;
  1308. }
  1309. if (FileName != DestFile)
  1310. {
  1311. // We have to copy it into place
  1312. Local = true;
  1313. Desc.URI = "copy:" + FileName;
  1314. QueueURI(Desc);
  1315. return;
  1316. }
  1317. if(StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  1318. IMSHit = true;
  1319. // adjust paths if its a ims-hit
  1320. if(IMSHit)
  1321. {
  1322. string FinalFile = _config->FindDir("Dir::State::lists");
  1323. FinalFile += URItoFileName(RealURI);
  1324. DestFile = PartialFile = FinalFile;
  1325. }
  1326. // queue for verify
  1327. if(AuthPass == false)
  1328. {
  1329. AuthPass = true;
  1330. Desc.URI = "gpgv:" + DestFile;
  1331. DestFile = MetaIndexFile;
  1332. QueueURI(Desc);
  1333. return;
  1334. }
  1335. // queue to copy the file in place if it was not a ims hit, on ims
  1336. // hit the file is already at the right place
  1337. if(IMSHit == false)
  1338. {
  1339. PartialFile = _config->FindDir("Dir::State::lists") + "partial/";
  1340. PartialFile += URItoFileName(RealURI);
  1341. DestFile = _config->FindDir("Dir::State::lists");
  1342. DestFile += URItoFileName(RealURI);
  1343. }
  1344. Complete = true;
  1345. }
  1346. /*}}}*/
  1347. void pkgAcqMetaSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf)/*{{{*/
  1348. {
  1349. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1350. // this ensures that any file in the lists/ dir is removed by the
  1351. // transaction
  1352. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1353. DestFile += URItoFileName(RealURI);
  1354. PartialFile = "";
  1355. // FIXME: duplicated code from pkgAcqMetaIndex
  1356. if (AuthPass == true)
  1357. {
  1358. bool Stop = GenerateAuthWarning(RealURI, Message);
  1359. if(Stop)
  1360. return;
  1361. }
  1362. // FIXME: this is used often (e.g. in pkgAcqIndexTrans) so refactor
  1363. if (Cnf->LocalOnly == true ||
  1364. StringToBool(LookupTag(Message,"Transient-Failure"),false) == false)
  1365. {
  1366. // Ignore this
  1367. Status = StatDone;
  1368. Complete = false;
  1369. Dequeue();
  1370. return;
  1371. }
  1372. Item::Failed(Message,Cnf);
  1373. }
  1374. /*}}}*/
  1375. pkgAcqMetaIndex::pkgAcqMetaIndex(pkgAcquire *Owner, /*{{{*/
  1376. pkgAcqMetaBase *TransactionManager,
  1377. string URI,string URIDesc,string ShortDesc,
  1378. string MetaIndexSigURI,string MetaIndexSigURIDesc, string MetaIndexSigShortDesc,
  1379. const vector<IndexTarget*>* IndexTargets,
  1380. indexRecords* MetaIndexParser) :
  1381. pkgAcqMetaBase(Owner, HashStringList(), TransactionManager), RealURI(URI), IndexTargets(IndexTargets),
  1382. MetaIndexParser(MetaIndexParser), AuthPass(false), IMSHit(false),
  1383. MetaIndexSigURI(MetaIndexSigURI), MetaIndexSigURIDesc(MetaIndexSigURIDesc),
  1384. MetaIndexSigShortDesc(MetaIndexSigShortDesc)
  1385. {
  1386. if(TransactionManager == NULL)
  1387. {
  1388. this->TransactionManager = this;
  1389. this->TransactionManager->Add(this);
  1390. }
  1391. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1392. std::clog << "New pkgAcqMetaIndex with TransactionManager "
  1393. << this->TransactionManager << std::endl;
  1394. Init(URIDesc, ShortDesc);
  1395. }
  1396. /*}}}*/
  1397. // pkgAcqMetaIndex::Init - Delayed constructor /*{{{*/
  1398. void pkgAcqMetaIndex::Init(std::string URIDesc, std::string ShortDesc)
  1399. {
  1400. DestFile = _config->FindDir("Dir::State::lists") + "partial/";
  1401. DestFile += URItoFileName(RealURI);
  1402. // Create the item
  1403. Desc.Description = URIDesc;
  1404. Desc.Owner = this;
  1405. Desc.ShortDesc = ShortDesc;
  1406. Desc.URI = RealURI;
  1407. // we expect more item
  1408. ExpectedAdditionalItems = IndexTargets->size();
  1409. QueueURI(Desc);
  1410. }
  1411. // pkgAcqMetaIndex::Custom600Headers - Insert custom request headers /*{{{*/
  1412. // ---------------------------------------------------------------------
  1413. /* The only header we use is the last-modified header. */
  1414. string pkgAcqMetaIndex::Custom600Headers() const
  1415. {
  1416. string Final = _config->FindDir("Dir::State::lists");
  1417. Final += URItoFileName(RealURI);
  1418. struct stat Buf;
  1419. if (stat(Final.c_str(),&Buf) != 0)
  1420. return "\nIndex-File: true";
  1421. return "\nIndex-File: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1422. }
  1423. /*}}}*/
  1424. void pkgAcqMetaIndex::Done(string Message,unsigned long long Size,HashStringList const &Hashes, /*{{{*/
  1425. pkgAcquire::MethodConfig *Cfg)
  1426. {
  1427. Item::Done(Message,Size,Hashes,Cfg);
  1428. // MetaIndexes are done in two passes: one to download the
  1429. // metaindex with an appropriate method, and a second to verify it
  1430. // with the gpgv method
  1431. if (AuthPass == true)
  1432. {
  1433. AuthDone(Message);
  1434. // all cool, move Release file into place
  1435. Complete = true;
  1436. }
  1437. else
  1438. {
  1439. RetrievalDone(Message);
  1440. if (!Complete)
  1441. // Still more retrieving to do
  1442. return;
  1443. if (SigFile == "")
  1444. {
  1445. // load indexes, the signature will downloaded afterwards
  1446. MetaIndexParser->Load(DestFile);
  1447. QueueIndexes(true);
  1448. }
  1449. else
  1450. {
  1451. // There was a signature file, so pass it to gpgv for
  1452. // verification
  1453. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1454. std::cerr << "Metaindex acquired, queueing gpg verification ("
  1455. << SigFile << "," << DestFile << ")\n";
  1456. AuthPass = true;
  1457. Desc.URI = "gpgv:" + SigFile;
  1458. QueueURI(Desc);
  1459. Mode = "gpgv";
  1460. return;
  1461. }
  1462. }
  1463. if (Complete == true)
  1464. {
  1465. string FinalFile = _config->FindDir("Dir::State::lists");
  1466. FinalFile += URItoFileName(RealURI);
  1467. if (SigFile == DestFile)
  1468. SigFile = FinalFile;
  1469. // queue for copy in place
  1470. PartialFile = DestFile;
  1471. DestFile = FinalFile;
  1472. }
  1473. }
  1474. /*}}}*/
  1475. void pkgAcqMetaIndex::RetrievalDone(string Message) /*{{{*/
  1476. {
  1477. // We have just finished downloading a Release file (it is not
  1478. // verified yet)
  1479. string FileName = LookupTag(Message,"Filename");
  1480. if (FileName.empty() == true)
  1481. {
  1482. Status = StatError;
  1483. ErrorText = "Method gave a blank filename";
  1484. return;
  1485. }
  1486. if (FileName != DestFile)
  1487. {
  1488. Local = true;
  1489. Desc.URI = "copy:" + FileName;
  1490. QueueURI(Desc);
  1491. return;
  1492. }
  1493. // make sure to verify against the right file on I-M-S hit
  1494. IMSHit = StringToBool(LookupTag(Message,"IMS-Hit"),false);
  1495. if(IMSHit)
  1496. {
  1497. string FinalFile = _config->FindDir("Dir::State::lists");
  1498. FinalFile += URItoFileName(RealURI);
  1499. if (SigFile == DestFile)
  1500. {
  1501. SigFile = FinalFile;
  1502. #if 0
  1503. // constructor of pkgAcqMetaClearSig moved it out of the way,
  1504. // now move it back in on IMS hit for the 'old' file
  1505. string const OldClearSig = DestFile + ".reverify";
  1506. if (RealFileExists(OldClearSig) == true)
  1507. Rename(OldClearSig, FinalFile);
  1508. #endif
  1509. }
  1510. DestFile = FinalFile;
  1511. }
  1512. // queue a signature
  1513. if(SigFile != DestFile)
  1514. new pkgAcqMetaSig(Owner, TransactionManager,
  1515. MetaIndexSigURI, MetaIndexSigURIDesc,
  1516. MetaIndexSigShortDesc, DestFile, IndexTargets,
  1517. MetaIndexParser);
  1518. Complete = true;
  1519. }
  1520. /*}}}*/
  1521. void pkgAcqMetaIndex::AuthDone(string Message) /*{{{*/
  1522. {
  1523. // At this point, the gpgv method has succeeded, so there is a
  1524. // valid signature from a key in the trusted keyring. We
  1525. // perform additional verification of its contents, and use them
  1526. // to verify the indexes we are about to download
  1527. if (!MetaIndexParser->Load(DestFile))
  1528. {
  1529. Status = StatAuthError;
  1530. ErrorText = MetaIndexParser->ErrorText;
  1531. return;
  1532. }
  1533. if (!VerifyVendor(Message))
  1534. {
  1535. return;
  1536. }
  1537. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1538. std::cerr << "Signature verification succeeded: "
  1539. << DestFile << std::endl;
  1540. // we ensure this by other means
  1541. #if 0
  1542. // do not trust any previously unverified content that we may have
  1543. string LastGoodSigFile = _config->FindDir("Dir::State::lists").append("partial/").append(URItoFileName(RealURI));
  1544. if (DestFile != SigFile)
  1545. LastGoodSigFile.append(".gpg");
  1546. LastGoodSigFile.append(".reverify");
  1547. if(IMSHit == false && RealFileExists(LastGoodSigFile) == false)
  1548. {
  1549. for (vector <struct IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1550. Target != IndexTargets->end();
  1551. ++Target)
  1552. {
  1553. // remove old indexes
  1554. std::string index = _config->FindDir("Dir::State::lists") +
  1555. URItoFileName((*Target)->URI);
  1556. unlink(index.c_str());
  1557. // and also old gzipindexes
  1558. index += ".gz";
  1559. unlink(index.c_str());
  1560. }
  1561. }
  1562. #endif
  1563. // Download further indexes with verification
  1564. //
  1565. // we do not need to download indexfiles if the Release file has not
  1566. // changed because without a changed release file there are no new hashes
  1567. // and we ensure that the repository is always "complete" (i.e. all
  1568. // that is in the release file is downloaded)
  1569. if(IMSHit == false)
  1570. QueueIndexes(true);
  1571. #if 0
  1572. // is it a clearsigned MetaIndex file?
  1573. if (DestFile == SigFile)
  1574. return;
  1575. // Done, move signature file into position
  1576. string VerifiedSigFile = _config->FindDir("Dir::State::lists") +
  1577. URItoFileName(RealURI) + ".gpg";
  1578. Rename(SigFile,VerifiedSigFile);
  1579. chmod(VerifiedSigFile.c_str(),0644);
  1580. #endif
  1581. }
  1582. /*}}}*/
  1583. void pkgAcqMetaIndex::QueueIndexes(bool verify) /*{{{*/
  1584. {
  1585. bool transInRelease = false;
  1586. {
  1587. std::vector<std::string> const keys = MetaIndexParser->MetaKeys();
  1588. for (std::vector<std::string>::const_iterator k = keys.begin(); k != keys.end(); ++k)
  1589. // FIXME: Feels wrong to check for hardcoded string here, but what should we do else…
  1590. if (k->find("Translation-") != std::string::npos)
  1591. {
  1592. transInRelease = true;
  1593. break;
  1594. }
  1595. }
  1596. // at this point the real Items are loaded in the fetcher
  1597. ExpectedAdditionalItems = 0;
  1598. for (vector <IndexTarget*>::const_iterator Target = IndexTargets->begin();
  1599. Target != IndexTargets->end();
  1600. ++Target)
  1601. {
  1602. HashStringList ExpectedIndexHashes;
  1603. const indexRecords::checkSum *Record = MetaIndexParser->Lookup((*Target)->MetaKey);
  1604. bool compressedAvailable = false;
  1605. if (Record == NULL)
  1606. {
  1607. if ((*Target)->IsOptional() == true)
  1608. {
  1609. std::vector<std::string> types = APT::Configuration::getCompressionTypes();
  1610. for (std::vector<std::string>::const_iterator t = types.begin(); t != types.end(); ++t)
  1611. if (MetaIndexParser->Exists((*Target)->MetaKey + "." + *t) == true)
  1612. {
  1613. compressedAvailable = true;
  1614. break;
  1615. }
  1616. }
  1617. else if (verify == true)
  1618. {
  1619. Status = StatAuthError;
  1620. strprintf(ErrorText, _("Unable to find expected entry '%s' in Release file (Wrong sources.list entry or malformed file)"), (*Target)->MetaKey.c_str());
  1621. return;
  1622. }
  1623. }
  1624. else
  1625. {
  1626. ExpectedIndexHashes = Record->Hashes;
  1627. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1628. {
  1629. std::cerr << "Queueing: " << (*Target)->URI << std::endl
  1630. << "Expected Hash:" << std::endl;
  1631. for (HashStringList::const_iterator hs = ExpectedIndexHashes.begin(); hs != ExpectedIndexHashes.end(); ++hs)
  1632. std::cerr << "\t- " << hs->toStr() << std::endl;
  1633. std::cerr << "For: " << Record->MetaKeyFilename << std::endl;
  1634. }
  1635. if (verify == true && ExpectedIndexHashes.empty() == true && (*Target)->IsOptional() == false)
  1636. {
  1637. Status = StatAuthError;
  1638. strprintf(ErrorText, _("Unable to find hash sum for '%s' in Release file"), (*Target)->MetaKey.c_str());
  1639. return;
  1640. }
  1641. }
  1642. if ((*Target)->IsOptional() == true)
  1643. {
  1644. if (transInRelease == false || Record != NULL || compressedAvailable == true)
  1645. {
  1646. if (_config->FindB("Acquire::PDiffs",true) == true && transInRelease == true &&
  1647. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true)
  1648. new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1649. else
  1650. new pkgAcqIndexTrans(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1651. }
  1652. continue;
  1653. }
  1654. /* Queue Packages file (either diff or full packages files, depending
  1655. on the users option) - we also check if the PDiff Index file is listed
  1656. in the Meta-Index file. Ideal would be if pkgAcqDiffIndex would test this
  1657. instead, but passing the required info to it is to much hassle */
  1658. if(_config->FindB("Acquire::PDiffs",true) == true && (verify == false ||
  1659. MetaIndexParser->Exists((*Target)->MetaKey + ".diff/Index") == true))
  1660. new pkgAcqDiffIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1661. else
  1662. new pkgAcqIndex(Owner, TransactionManager, *Target, ExpectedIndexHashes, MetaIndexParser);
  1663. }
  1664. }
  1665. /*}}}*/
  1666. bool pkgAcqMetaIndex::VerifyVendor(string Message) /*{{{*/
  1667. {
  1668. string::size_type pos;
  1669. // check for missing sigs (that where not fatal because otherwise we had
  1670. // bombed earlier)
  1671. string missingkeys;
  1672. string msg = _("There is no public key available for the "
  1673. "following key IDs:\n");
  1674. pos = Message.find("NO_PUBKEY ");
  1675. if (pos != std::string::npos)
  1676. {
  1677. string::size_type start = pos+strlen("NO_PUBKEY ");
  1678. string Fingerprint = Message.substr(start, Message.find("\n")-start);
  1679. missingkeys += (Fingerprint);
  1680. }
  1681. if(!missingkeys.empty())
  1682. _error->Warning("%s", (msg + missingkeys).c_str());
  1683. string Transformed = MetaIndexParser->GetExpectedDist();
  1684. if (Transformed == "../project/experimental")
  1685. {
  1686. Transformed = "experimental";
  1687. }
  1688. pos = Transformed.rfind('/');
  1689. if (pos != string::npos)
  1690. {
  1691. Transformed = Transformed.substr(0, pos);
  1692. }
  1693. if (Transformed == ".")
  1694. {
  1695. Transformed = "";
  1696. }
  1697. if (_config->FindB("Acquire::Check-Valid-Until", true) == true &&
  1698. MetaIndexParser->GetValidUntil() > 0) {
  1699. time_t const invalid_since = time(NULL) - MetaIndexParser->GetValidUntil();
  1700. if (invalid_since > 0)
  1701. // TRANSLATOR: The first %s is the URL of the bad Release file, the second is
  1702. // the time since then the file is invalid - formated in the same way as in
  1703. // the download progress display (e.g. 7d 3h 42min 1s)
  1704. return _error->Error(
  1705. _("Release file for %s is expired (invalid since %s). "
  1706. "Updates for this repository will not be applied."),
  1707. RealURI.c_str(), TimeToStr(invalid_since).c_str());
  1708. }
  1709. if (_config->FindB("Debug::pkgAcquire::Auth", false))
  1710. {
  1711. std::cerr << "Got Codename: " << MetaIndexParser->GetDist() << std::endl;
  1712. std::cerr << "Expecting Dist: " << MetaIndexParser->GetExpectedDist() << std::endl;
  1713. std::cerr << "Transformed Dist: " << Transformed << std::endl;
  1714. }
  1715. if (MetaIndexParser->CheckDist(Transformed) == false)
  1716. {
  1717. // This might become fatal one day
  1718. // Status = StatAuthError;
  1719. // ErrorText = "Conflicting distribution; expected "
  1720. // + MetaIndexParser->GetExpectedDist() + " but got "
  1721. // + MetaIndexParser->GetDist();
  1722. // return false;
  1723. if (!Transformed.empty())
  1724. {
  1725. _error->Warning(_("Conflicting distribution: %s (expected %s but got %s)"),
  1726. Desc.Description.c_str(),
  1727. Transformed.c_str(),
  1728. MetaIndexParser->GetDist().c_str());
  1729. }
  1730. }
  1731. return true;
  1732. }
  1733. /*}}}*/
  1734. // pkgAcqMetaIndex::Failed - no Release file present or no signature file present /*{{{*/
  1735. // ---------------------------------------------------------------------
  1736. /* */
  1737. void pkgAcqMetaIndex::Failed(string Message,
  1738. pkgAcquire::MethodConfig * /*Cnf*/)
  1739. {
  1740. string Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1741. if (AuthPass == true)
  1742. {
  1743. bool Stop = GenerateAuthWarning(RealURI, Message);
  1744. if(Stop)
  1745. return;
  1746. }
  1747. /* Always move the meta index, even if gpgv failed. This ensures
  1748. * that PackageFile objects are correctly filled in */
  1749. if (FileExists(DestFile)) {
  1750. string FinalFile = _config->FindDir("Dir::State::lists");
  1751. FinalFile += URItoFileName(RealURI);
  1752. /* InRelease files become Release files, otherwise
  1753. * they would be considered as trusted later on */
  1754. if (SigFile == DestFile) {
  1755. RealURI = RealURI.replace(RealURI.rfind("InRelease"), 9,
  1756. "Release");
  1757. FinalFile = FinalFile.replace(FinalFile.rfind("InRelease"), 9,
  1758. "Release");
  1759. SigFile = FinalFile;
  1760. }
  1761. // Done, queue for rename on transaction finished
  1762. PartialFile = DestFile;
  1763. DestFile = FinalFile;
  1764. }
  1765. // warn if the repository is unsinged
  1766. _error->Warning(_("The data from '%s' is not signed. Packages "
  1767. "from that repository can not be authenticated."),
  1768. URIDesc.c_str());
  1769. // No Release file was present, or verification failed, so fall
  1770. // back to queueing Packages files without verification
  1771. QueueIndexes(false);
  1772. }
  1773. /*}}}*/
  1774. void pkgAcqMetaIndex::Finished()
  1775. {
  1776. if(_config->FindB("Debug::Acquire::Transaction", false) == true)
  1777. std::clog << "Finished: " << DestFile <<std::endl;
  1778. if(TransactionManager != NULL &&
  1779. TransactionManager->TransactionHasError() == false)
  1780. TransactionManager->CommitTransaction();
  1781. }
  1782. pkgAcqMetaClearSig::pkgAcqMetaClearSig(pkgAcquire *Owner, /*{{{*/
  1783. string const &URI, string const &URIDesc, string const &ShortDesc,
  1784. string const &MetaIndexURI, string const &MetaIndexURIDesc, string const &MetaIndexShortDesc,
  1785. string const &MetaSigURI, string const &MetaSigURIDesc, string const &MetaSigShortDesc,
  1786. const vector<IndexTarget*>* IndexTargets,
  1787. indexRecords* MetaIndexParser) :
  1788. pkgAcqMetaIndex(Owner, NULL, URI, URIDesc, ShortDesc, MetaSigURI, MetaSigURIDesc,MetaSigShortDesc, IndexTargets, MetaIndexParser),
  1789. MetaIndexURI(MetaIndexURI), MetaIndexURIDesc(MetaIndexURIDesc), MetaIndexShortDesc(MetaIndexShortDesc),
  1790. MetaSigURI(MetaSigURI), MetaSigURIDesc(MetaSigURIDesc), MetaSigShortDesc(MetaSigShortDesc)
  1791. {
  1792. SigFile = DestFile;
  1793. // index targets + (worst case:) Release/Release.gpg
  1794. ExpectedAdditionalItems = IndexTargets->size() + 2;
  1795. #if 0
  1796. // keep the old InRelease around in case of transistent network errors
  1797. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1798. if (RealFileExists(Final) == true)
  1799. {
  1800. string const LastGoodSig = DestFile + ".reverify";
  1801. Rename(Final,LastGoodSig);
  1802. }
  1803. #endif
  1804. }
  1805. /*}}}*/
  1806. pkgAcqMetaClearSig::~pkgAcqMetaClearSig() /*{{{*/
  1807. {
  1808. #if 0
  1809. // if the file was never queued undo file-changes done in the constructor
  1810. if (QueueCounter == 1 && Status == StatIdle && FileSize == 0 && Complete == false)
  1811. {
  1812. string const Final = _config->FindDir("Dir::State::lists") + URItoFileName(RealURI);
  1813. string const LastGoodSig = DestFile + ".reverify";
  1814. if (RealFileExists(Final) == false && RealFileExists(LastGoodSig) == true)
  1815. Rename(LastGoodSig, Final);
  1816. }
  1817. #endif
  1818. }
  1819. /*}}}*/
  1820. // pkgAcqMetaClearSig::Custom600Headers - Insert custom request headers /*{{{*/
  1821. // ---------------------------------------------------------------------
  1822. // FIXME: this can go away once the InRelease file is used widely
  1823. string pkgAcqMetaClearSig::Custom600Headers() const
  1824. {
  1825. string Final = _config->FindDir("Dir::State::lists");
  1826. Final += URItoFileName(RealURI);
  1827. struct stat Buf;
  1828. if (stat(Final.c_str(),&Buf) != 0)
  1829. {
  1830. if (stat(Final.c_str(),&Buf) != 0)
  1831. return "\nIndex-File: true\nFail-Ignore: true\n";
  1832. }
  1833. return "\nIndex-File: true\nFail-Ignore: true\nLast-Modified: " + TimeRFC1123(Buf.st_mtime);
  1834. }
  1835. /*}}}*/
  1836. // pkgAcqMetaClearSig::Done - We got a file /*{{{*/
  1837. // ---------------------------------------------------------------------
  1838. void pkgAcqMetaClearSig::Done(std::string Message,unsigned long long Size,
  1839. HashStringList const &Hashes,
  1840. pkgAcquire::MethodConfig *Cnf)
  1841. {
  1842. // if we expect a ClearTextSignature (InRelase), ensure that
  1843. // this is what we get and if not fail to queue a
  1844. // Release/Release.gpg, see #346386
  1845. if (FileExists(DestFile) && !StartsWithGPGClearTextSignature(DestFile))
  1846. {
  1847. pkgAcquire::Item::Failed(Message, Cnf);
  1848. ErrorText = _("Does not start with a cleartext signature");
  1849. return;
  1850. }
  1851. pkgAcqMetaIndex::Done(Message, Size, Hashes, Cnf);
  1852. }
  1853. /*}}}*/
  1854. void pkgAcqMetaClearSig::Failed(string Message,pkgAcquire::MethodConfig *Cnf) /*{{{*/
  1855. {
  1856. // we failed, we will not get additional items from this method
  1857. ExpectedAdditionalItems = 0;
  1858. if (AuthPass == false)
  1859. {
  1860. // Queue the 'old' InRelease file for removal if we try Release.gpg
  1861. // as otherwise the file will stay around and gives a false-auth
  1862. // impression (CVE-2012-0214)
  1863. string FinalFile = _config->FindDir("Dir::State::lists");
  1864. FinalFile.append(URItoFileName(RealURI));
  1865. PartialFile = "";
  1866. DestFile = FinalFile;
  1867. new pkgAcqMetaIndex(Owner, TransactionManager,
  1868. MetaIndexURI, MetaIndexURIDesc, MetaIndexShortDesc,
  1869. MetaSigURI, MetaSigURIDesc, MetaSigShortDesc,
  1870. IndexTargets, MetaIndexParser);
  1871. if (Cnf->LocalOnly == true ||
  1872. StringToBool(LookupTag(Message, "Transient-Failure"), false) == false)
  1873. Dequeue();
  1874. }
  1875. else
  1876. pkgAcqMetaIndex::Failed(Message, Cnf);
  1877. }
  1878. /*}}}*/
  1879. // AcqArchive::AcqArchive - Constructor /*{{{*/
  1880. // ---------------------------------------------------------------------
  1881. /* This just sets up the initial fetch environment and queues the first
  1882. possibilitiy */
  1883. pkgAcqArchive::pkgAcqArchive(pkgAcquire *Owner,pkgSourceList *Sources,
  1884. pkgRecords *Recs,pkgCache::VerIterator const &Version,
  1885. string &StoreFilename) :
  1886. Item(Owner, HashStringList()), Version(Version), Sources(Sources), Recs(Recs),
  1887. StoreFilename(StoreFilename), Vf(Version.FileList()),
  1888. Trusted(false)
  1889. {
  1890. Retries = _config->FindI("Acquire::Retries",0);
  1891. if (Version.Arch() == 0)
  1892. {
  1893. _error->Error(_("I wasn't able to locate a file for the %s package. "
  1894. "This might mean you need to manually fix this package. "
  1895. "(due to missing arch)"),
  1896. Version.ParentPkg().FullName().c_str());
  1897. return;
  1898. }
  1899. /* We need to find a filename to determine the extension. We make the
  1900. assumption here that all the available sources for this version share
  1901. the same extension.. */
  1902. // Skip not source sources, they do not have file fields.
  1903. for (; Vf.end() == false; ++Vf)
  1904. {
  1905. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1906. continue;
  1907. break;
  1908. }
  1909. // Does not really matter here.. we are going to fail out below
  1910. if (Vf.end() != true)
  1911. {
  1912. // If this fails to get a file name we will bomb out below.
  1913. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1914. if (_error->PendingError() == true)
  1915. return;
  1916. // Generate the final file name as: package_version_arch.foo
  1917. StoreFilename = QuoteString(Version.ParentPkg().Name(),"_:") + '_' +
  1918. QuoteString(Version.VerStr(),"_:") + '_' +
  1919. QuoteString(Version.Arch(),"_:.") +
  1920. "." + flExtension(Parse.FileName());
  1921. }
  1922. // check if we have one trusted source for the package. if so, switch
  1923. // to "TrustedOnly" mode - but only if not in AllowUnauthenticated mode
  1924. bool const allowUnauth = _config->FindB("APT::Get::AllowUnauthenticated", false);
  1925. bool const debugAuth = _config->FindB("Debug::pkgAcquire::Auth", false);
  1926. bool seenUntrusted = false;
  1927. for (pkgCache::VerFileIterator i = Version.FileList(); i.end() == false; ++i)
  1928. {
  1929. pkgIndexFile *Index;
  1930. if (Sources->FindIndex(i.File(),Index) == false)
  1931. continue;
  1932. if (debugAuth == true)
  1933. std::cerr << "Checking index: " << Index->Describe()
  1934. << "(Trusted=" << Index->IsTrusted() << ")" << std::endl;
  1935. if (Index->IsTrusted() == true)
  1936. {
  1937. Trusted = true;
  1938. if (allowUnauth == false)
  1939. break;
  1940. }
  1941. else
  1942. seenUntrusted = true;
  1943. }
  1944. // "allow-unauthenticated" restores apts old fetching behaviour
  1945. // that means that e.g. unauthenticated file:// uris are higher
  1946. // priority than authenticated http:// uris
  1947. if (allowUnauth == true && seenUntrusted == true)
  1948. Trusted = false;
  1949. // Select a source
  1950. if (QueueNext() == false && _error->PendingError() == false)
  1951. _error->Error(_("Can't find a source to download version '%s' of '%s'"),
  1952. Version.VerStr(), Version.ParentPkg().FullName(false).c_str());
  1953. }
  1954. /*}}}*/
  1955. // AcqArchive::QueueNext - Queue the next file source /*{{{*/
  1956. // ---------------------------------------------------------------------
  1957. /* This queues the next available file version for download. It checks if
  1958. the archive is already available in the cache and stashs the MD5 for
  1959. checking later. */
  1960. bool pkgAcqArchive::QueueNext()
  1961. {
  1962. for (; Vf.end() == false; ++Vf)
  1963. {
  1964. // Ignore not source sources
  1965. if ((Vf.File()->Flags & pkgCache::Flag::NotSource) != 0)
  1966. continue;
  1967. // Try to cross match against the source list
  1968. pkgIndexFile *Index;
  1969. if (Sources->FindIndex(Vf.File(),Index) == false)
  1970. continue;
  1971. // only try to get a trusted package from another source if that source
  1972. // is also trusted
  1973. if(Trusted && !Index->IsTrusted())
  1974. continue;
  1975. // Grab the text package record
  1976. pkgRecords::Parser &Parse = Recs->Lookup(Vf);
  1977. if (_error->PendingError() == true)
  1978. return false;
  1979. string PkgFile = Parse.FileName();
  1980. ExpectedHashes = Parse.Hashes();
  1981. if (PkgFile.empty() == true)
  1982. return _error->Error(_("The package index files are corrupted. No Filename: "
  1983. "field for package %s."),
  1984. Version.ParentPkg().Name());
  1985. Desc.URI = Index->ArchiveURI(PkgFile);
  1986. Desc.Description = Index->ArchiveInfo(Version);
  1987. Desc.Owner = this;
  1988. Desc.ShortDesc = Version.ParentPkg().FullName(true);
  1989. // See if we already have the file. (Legacy filenames)
  1990. FileSize = Version->Size;
  1991. string FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(PkgFile);
  1992. struct stat Buf;
  1993. if (stat(FinalFile.c_str(),&Buf) == 0)
  1994. {
  1995. // Make sure the size matches
  1996. if ((unsigned long long)Buf.st_size == Version->Size)
  1997. {
  1998. Complete = true;
  1999. Local = true;
  2000. Status = StatDone;
  2001. StoreFilename = DestFile = FinalFile;
  2002. return true;
  2003. }
  2004. /* Hmm, we have a file and its size does not match, this means it is
  2005. an old style mismatched arch */
  2006. unlink(FinalFile.c_str());
  2007. }
  2008. // Check it again using the new style output filenames
  2009. FinalFile = _config->FindDir("Dir::Cache::Archives") + flNotDir(StoreFilename);
  2010. if (stat(FinalFile.c_str(),&Buf) == 0)
  2011. {
  2012. // Make sure the size matches
  2013. if ((unsigned long long)Buf.st_size == Version->Size)
  2014. {
  2015. Complete = true;
  2016. Local = true;
  2017. Status = StatDone;
  2018. StoreFilename = DestFile = FinalFile;
  2019. return true;
  2020. }
  2021. /* Hmm, we have a file and its size does not match, this shouldn't
  2022. happen.. */
  2023. unlink(FinalFile.c_str());
  2024. }
  2025. DestFile = _config->FindDir("Dir::Cache::Archives") + "partial/" + flNotDir(StoreFilename);
  2026. // Check the destination file
  2027. if (stat(DestFile.c_str(),&Buf) == 0)
  2028. {
  2029. // Hmm, the partial file is too big, erase it
  2030. if ((unsigned long long)Buf.st_size > Version->Size)
  2031. unlink(DestFile.c_str());
  2032. else
  2033. PartialSize = Buf.st_size;
  2034. }
  2035. // Disables download of archives - useful if no real installation follows,
  2036. // e.g. if we are just interested in proposed installation order
  2037. if (_config->FindB("Debug::pkgAcqArchive::NoQueue", false) == true)
  2038. {
  2039. Complete = true;
  2040. Local = true;
  2041. Status = StatDone;
  2042. StoreFilename = DestFile = FinalFile;
  2043. return true;
  2044. }
  2045. // Create the item
  2046. Local = false;
  2047. QueueURI(Desc);
  2048. ++Vf;
  2049. return true;
  2050. }
  2051. return false;
  2052. }
  2053. /*}}}*/
  2054. // AcqArchive::Done - Finished fetching /*{{{*/
  2055. // ---------------------------------------------------------------------
  2056. /* */
  2057. void pkgAcqArchive::Done(string Message,unsigned long long Size, HashStringList const &CalcHashes,
  2058. pkgAcquire::MethodConfig *Cfg)
  2059. {
  2060. Item::Done(Message, Size, CalcHashes, Cfg);
  2061. // Check the size
  2062. if (Size != Version->Size)
  2063. {
  2064. RenameOnError(SizeMismatch);
  2065. return;
  2066. }
  2067. // FIXME: could this empty() check impose *any* sort of security issue?
  2068. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2069. {
  2070. RenameOnError(HashSumMismatch);
  2071. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2072. return;
  2073. }
  2074. // Grab the output filename
  2075. string FileName = LookupTag(Message,"Filename");
  2076. if (FileName.empty() == true)
  2077. {
  2078. Status = StatError;
  2079. ErrorText = "Method gave a blank filename";
  2080. return;
  2081. }
  2082. Complete = true;
  2083. // Reference filename
  2084. if (FileName != DestFile)
  2085. {
  2086. StoreFilename = DestFile = FileName;
  2087. Local = true;
  2088. return;
  2089. }
  2090. // Done, move it into position
  2091. string FinalFile = _config->FindDir("Dir::Cache::Archives");
  2092. FinalFile += flNotDir(StoreFilename);
  2093. Rename(DestFile,FinalFile);
  2094. StoreFilename = DestFile = FinalFile;
  2095. Complete = true;
  2096. }
  2097. /*}}}*/
  2098. // AcqArchive::Failed - Failure handler /*{{{*/
  2099. // ---------------------------------------------------------------------
  2100. /* Here we try other sources */
  2101. void pkgAcqArchive::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2102. {
  2103. ErrorText = LookupTag(Message,"Message");
  2104. /* We don't really want to retry on failed media swaps, this prevents
  2105. that. An interesting observation is that permanent failures are not
  2106. recorded. */
  2107. if (Cnf->Removable == true &&
  2108. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2109. {
  2110. // Vf = Version.FileList();
  2111. while (Vf.end() == false) ++Vf;
  2112. StoreFilename = string();
  2113. Item::Failed(Message,Cnf);
  2114. return;
  2115. }
  2116. if (QueueNext() == false)
  2117. {
  2118. // This is the retry counter
  2119. if (Retries != 0 &&
  2120. Cnf->LocalOnly == false &&
  2121. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2122. {
  2123. Retries--;
  2124. Vf = Version.FileList();
  2125. if (QueueNext() == true)
  2126. return;
  2127. }
  2128. StoreFilename = string();
  2129. Item::Failed(Message,Cnf);
  2130. }
  2131. }
  2132. /*}}}*/
  2133. // AcqArchive::IsTrusted - Determine whether this archive comes from a trusted source /*{{{*/
  2134. // ---------------------------------------------------------------------
  2135. APT_PURE bool pkgAcqArchive::IsTrusted() const
  2136. {
  2137. return Trusted;
  2138. }
  2139. /*}}}*/
  2140. // AcqArchive::Finished - Fetching has finished, tidy up /*{{{*/
  2141. // ---------------------------------------------------------------------
  2142. /* */
  2143. void pkgAcqArchive::Finished()
  2144. {
  2145. if (Status == pkgAcquire::Item::StatDone &&
  2146. Complete == true)
  2147. return;
  2148. StoreFilename = string();
  2149. }
  2150. /*}}}*/
  2151. // AcqFile::pkgAcqFile - Constructor /*{{{*/
  2152. // ---------------------------------------------------------------------
  2153. /* The file is added to the queue */
  2154. pkgAcqFile::pkgAcqFile(pkgAcquire *Owner,string URI, HashStringList const &Hashes,
  2155. unsigned long long Size,string Dsc,string ShortDesc,
  2156. const string &DestDir, const string &DestFilename,
  2157. bool IsIndexFile) :
  2158. Item(Owner, Hashes), IsIndexFile(IsIndexFile)
  2159. {
  2160. Retries = _config->FindI("Acquire::Retries",0);
  2161. if(!DestFilename.empty())
  2162. DestFile = DestFilename;
  2163. else if(!DestDir.empty())
  2164. DestFile = DestDir + "/" + flNotDir(URI);
  2165. else
  2166. DestFile = flNotDir(URI);
  2167. // Create the item
  2168. Desc.URI = URI;
  2169. Desc.Description = Dsc;
  2170. Desc.Owner = this;
  2171. // Set the short description to the archive component
  2172. Desc.ShortDesc = ShortDesc;
  2173. // Get the transfer sizes
  2174. FileSize = Size;
  2175. struct stat Buf;
  2176. if (stat(DestFile.c_str(),&Buf) == 0)
  2177. {
  2178. // Hmm, the partial file is too big, erase it
  2179. if ((Size > 0) && (unsigned long long)Buf.st_size > Size)
  2180. unlink(DestFile.c_str());
  2181. else
  2182. PartialSize = Buf.st_size;
  2183. }
  2184. QueueURI(Desc);
  2185. }
  2186. /*}}}*/
  2187. // AcqFile::Done - Item downloaded OK /*{{{*/
  2188. // ---------------------------------------------------------------------
  2189. /* */
  2190. void pkgAcqFile::Done(string Message,unsigned long long Size,HashStringList const &CalcHashes,
  2191. pkgAcquire::MethodConfig *Cnf)
  2192. {
  2193. Item::Done(Message,Size,CalcHashes,Cnf);
  2194. // Check the hash
  2195. if(ExpectedHashes.usable() && ExpectedHashes != CalcHashes)
  2196. {
  2197. RenameOnError(HashSumMismatch);
  2198. printHashSumComparision(DestFile, ExpectedHashes, CalcHashes);
  2199. return;
  2200. }
  2201. string FileName = LookupTag(Message,"Filename");
  2202. if (FileName.empty() == true)
  2203. {
  2204. Status = StatError;
  2205. ErrorText = "Method gave a blank filename";
  2206. return;
  2207. }
  2208. Complete = true;
  2209. // The files timestamp matches
  2210. if (StringToBool(LookupTag(Message,"IMS-Hit"),false) == true)
  2211. return;
  2212. // We have to copy it into place
  2213. if (FileName != DestFile)
  2214. {
  2215. Local = true;
  2216. if (_config->FindB("Acquire::Source-Symlinks",true) == false ||
  2217. Cnf->Removable == true)
  2218. {
  2219. Desc.URI = "copy:" + FileName;
  2220. QueueURI(Desc);
  2221. return;
  2222. }
  2223. // Erase the file if it is a symlink so we can overwrite it
  2224. struct stat St;
  2225. if (lstat(DestFile.c_str(),&St) == 0)
  2226. {
  2227. if (S_ISLNK(St.st_mode) != 0)
  2228. unlink(DestFile.c_str());
  2229. }
  2230. // Symlink the file
  2231. if (symlink(FileName.c_str(),DestFile.c_str()) != 0)
  2232. {
  2233. ErrorText = "Link to " + DestFile + " failure ";
  2234. Status = StatError;
  2235. Complete = false;
  2236. }
  2237. }
  2238. }
  2239. /*}}}*/
  2240. // AcqFile::Failed - Failure handler /*{{{*/
  2241. // ---------------------------------------------------------------------
  2242. /* Here we try other sources */
  2243. void pkgAcqFile::Failed(string Message,pkgAcquire::MethodConfig *Cnf)
  2244. {
  2245. ErrorText = LookupTag(Message,"Message");
  2246. // This is the retry counter
  2247. if (Retries != 0 &&
  2248. Cnf->LocalOnly == false &&
  2249. StringToBool(LookupTag(Message,"Transient-Failure"),false) == true)
  2250. {
  2251. Retries--;
  2252. QueueURI(Desc);
  2253. return;
  2254. }
  2255. Item::Failed(Message,Cnf);
  2256. }
  2257. /*}}}*/
  2258. // AcqIndex::Custom600Headers - Insert custom request headers /*{{{*/
  2259. // ---------------------------------------------------------------------
  2260. /* The only header we use is the last-modified header. */
  2261. string pkgAcqFile::Custom600Headers() const
  2262. {
  2263. if (IsIndexFile)
  2264. return "\nIndex-File: true";
  2265. return "";
  2266. }
  2267. /*}}}*/