acquire-item.cc 67 KB

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