acquire-item.cc 87 KB

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