acquire-item.cc 92 KB

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