acquire-item.cc 62 KB

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