tagfile.cc 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: tagfile.cc,v 1.37.2.2 2003/12/31 16:02:30 mdz Exp $
  4. /* ######################################################################
  5. Fast scanner for RFC-822 type header information
  6. This uses a rotating buffer to load the package information into.
  7. The scanner runs over it and isolates and indexes a single section.
  8. ##################################################################### */
  9. /*}}}*/
  10. // Include Files /*{{{*/
  11. #include<config.h>
  12. #include <apt-pkg/tagfile.h>
  13. #include <apt-pkg/tagfile-keys.h>
  14. #include <apt-pkg/error.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/string_view.h>
  18. #include <list>
  19. #include <string>
  20. #include <stdio.h>
  21. #include <ctype.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <apti18n.h>
  25. /*}}}*/
  26. using std::string;
  27. using APT::StringView;
  28. class APT_HIDDEN pkgTagFilePrivate /*{{{*/
  29. {
  30. public:
  31. void Reset(FileFd * const pFd, unsigned long long const pSize, pkgTagFile::Flags const pFlags)
  32. {
  33. if (Buffer != NULL)
  34. free(Buffer);
  35. Buffer = NULL;
  36. Fd = pFd;
  37. Flags = pFlags;
  38. Start = NULL;
  39. End = NULL;
  40. Done = false;
  41. iOffset = 0;
  42. Size = pSize;
  43. isCommentedLine = false;
  44. chunks.clear();
  45. }
  46. pkgTagFilePrivate(FileFd * const pFd, unsigned long long const Size, pkgTagFile::Flags const pFlags) : Buffer(NULL)
  47. {
  48. Reset(pFd, Size, pFlags);
  49. }
  50. FileFd * Fd;
  51. pkgTagFile::Flags Flags;
  52. char *Buffer;
  53. char *Start;
  54. char *End;
  55. bool Done;
  56. unsigned long long iOffset;
  57. unsigned long long Size;
  58. bool isCommentedLine;
  59. struct FileChunk
  60. {
  61. bool const good;
  62. size_t length;
  63. FileChunk(bool const pgood, size_t const plength) : good(pgood), length(plength) {}
  64. };
  65. std::list<FileChunk> chunks;
  66. ~pkgTagFilePrivate()
  67. {
  68. if (Buffer != NULL)
  69. free(Buffer);
  70. }
  71. };
  72. /*}}}*/
  73. class APT_HIDDEN pkgTagSectionPrivate /*{{{*/
  74. {
  75. public:
  76. pkgTagSectionPrivate()
  77. {
  78. }
  79. struct TagData {
  80. unsigned int StartTag;
  81. unsigned int EndTag;
  82. unsigned int StartValue;
  83. unsigned int NextInBucket;
  84. explicit TagData(unsigned int const StartTag) : StartTag(StartTag), EndTag(0), StartValue(0), NextInBucket(0) {}
  85. };
  86. std::vector<TagData> Tags;
  87. };
  88. /*}}}*/
  89. static unsigned long BetaHash(const char *Text, size_t Length) /*{{{*/
  90. {
  91. /* This very simple hash function for the last 8 letters gives
  92. very good performance on the debian package files */
  93. if (Length > 8)
  94. {
  95. Text += (Length - 8);
  96. Length = 8;
  97. }
  98. unsigned long Res = 0;
  99. for (size_t i = 0; i < Length; ++i)
  100. Res = ((unsigned long)(Text[i]) & 0xDF) ^ (Res << 1);
  101. return Res & 0x7F;
  102. }
  103. /*}}}*/
  104. // TagFile::pkgTagFile - Constructor /*{{{*/
  105. pkgTagFile::pkgTagFile(FileFd * const pFd,pkgTagFile::Flags const pFlags, unsigned long long const Size)
  106. : d(new pkgTagFilePrivate(pFd, Size + 4, pFlags))
  107. {
  108. Init(pFd, pFlags, Size);
  109. }
  110. pkgTagFile::pkgTagFile(FileFd * const pFd,unsigned long long const Size)
  111. : pkgTagFile(pFd, pkgTagFile::STRICT, Size)
  112. {
  113. }
  114. void pkgTagFile::Init(FileFd * const pFd, pkgTagFile::Flags const pFlags, unsigned long long Size)
  115. {
  116. /* The size is increased by 4 because if we start with the Size of the
  117. filename we need to try to read 1 char more to see an EOF faster, 1
  118. char the end-pointer can be on and maybe 2 newlines need to be added
  119. to the end of the file -> 4 extra chars */
  120. Size += 4;
  121. d->Reset(pFd, Size, pFlags);
  122. if (d->Fd->IsOpen() == false)
  123. d->Start = d->End = d->Buffer = 0;
  124. else
  125. d->Buffer = (char*)malloc(sizeof(char) * Size);
  126. if (d->Buffer == NULL)
  127. d->Done = true;
  128. else
  129. d->Done = false;
  130. d->Start = d->End = d->Buffer;
  131. d->iOffset = 0;
  132. if (d->Done == false)
  133. Fill();
  134. }
  135. void pkgTagFile::Init(FileFd * const pFd,unsigned long long Size)
  136. {
  137. Init(pFd, pkgTagFile::STRICT, Size);
  138. }
  139. /*}}}*/
  140. // TagFile::~pkgTagFile - Destructor /*{{{*/
  141. pkgTagFile::~pkgTagFile()
  142. {
  143. delete d;
  144. }
  145. /*}}}*/
  146. // TagFile::Offset - Return the current offset in the buffer /*{{{*/
  147. APT_PURE unsigned long pkgTagFile::Offset()
  148. {
  149. return d->iOffset;
  150. }
  151. /*}}}*/
  152. // TagFile::Resize - Resize the internal buffer /*{{{*/
  153. // ---------------------------------------------------------------------
  154. /* Resize the internal buffer (double it in size). Fail if a maximum size
  155. * size is reached.
  156. */
  157. bool pkgTagFile::Resize()
  158. {
  159. // fail is the buffer grows too big
  160. if(d->Size > 1024*1024+1)
  161. return false;
  162. return Resize(d->Size * 2);
  163. }
  164. bool pkgTagFile::Resize(unsigned long long const newSize)
  165. {
  166. unsigned long long const EndSize = d->End - d->Start;
  167. // get new buffer and use it
  168. char* const newBuffer = static_cast<char*>(realloc(d->Buffer, sizeof(char) * newSize));
  169. if (newBuffer == NULL)
  170. return false;
  171. d->Buffer = newBuffer;
  172. d->Size = newSize;
  173. // update the start/end pointers to the new buffer
  174. d->Start = d->Buffer;
  175. d->End = d->Start + EndSize;
  176. return true;
  177. }
  178. /*}}}*/
  179. // TagFile::Step - Advance to the next section /*{{{*/
  180. // ---------------------------------------------------------------------
  181. /* If the Section Scanner fails we refill the buffer and try again.
  182. * If that fails too, double the buffer size and try again until a
  183. * maximum buffer is reached.
  184. */
  185. bool pkgTagFile::Step(pkgTagSection &Tag)
  186. {
  187. if(Tag.Scan(d->Start,d->End - d->Start) == false)
  188. {
  189. do
  190. {
  191. if (Fill() == false)
  192. return false;
  193. if(Tag.Scan(d->Start,d->End - d->Start, false))
  194. break;
  195. if (Resize() == false)
  196. return _error->Error(_("Unable to parse package file %s (%d)"),
  197. d->Fd->Name().c_str(), 1);
  198. } while (Tag.Scan(d->Start,d->End - d->Start, false) == false);
  199. }
  200. size_t tagSize = Tag.size();
  201. d->Start += tagSize;
  202. if ((d->Flags & pkgTagFile::SUPPORT_COMMENTS) == 0)
  203. d->iOffset += tagSize;
  204. else
  205. {
  206. auto first = d->chunks.begin();
  207. for (; first != d->chunks.end(); ++first)
  208. {
  209. if (first->good == false)
  210. d->iOffset += first->length;
  211. else
  212. {
  213. if (tagSize < first->length)
  214. {
  215. first->length -= tagSize;
  216. d->iOffset += tagSize;
  217. break;
  218. }
  219. else
  220. {
  221. tagSize -= first->length;
  222. d->iOffset += first->length;
  223. }
  224. }
  225. }
  226. d->chunks.erase(d->chunks.begin(), first);
  227. }
  228. Tag.Trim();
  229. return true;
  230. }
  231. /*}}}*/
  232. // TagFile::Fill - Top up the buffer /*{{{*/
  233. // ---------------------------------------------------------------------
  234. /* This takes the bit at the end of the buffer and puts it at the start
  235. then fills the rest from the file */
  236. static bool FillBuffer(pkgTagFilePrivate * const d)
  237. {
  238. unsigned long long Actual = 0;
  239. // See if only a bit of the file is left
  240. unsigned long long const dataSize = d->Size - ((d->End - d->Buffer) + 1);
  241. if (d->Fd->Read(d->End, dataSize, &Actual) == false)
  242. return false;
  243. if (Actual != dataSize)
  244. d->Done = true;
  245. d->End += Actual;
  246. return true;
  247. }
  248. static void RemoveCommentsFromBuffer(pkgTagFilePrivate * const d)
  249. {
  250. // look for valid comments in the buffer
  251. char * good_start = nullptr, * bad_start = nullptr;
  252. char * current = d->Start;
  253. if (d->isCommentedLine == false)
  254. {
  255. if (d->Start == d->Buffer)
  256. {
  257. // the start of the buffer is a newline as a record can't start
  258. // in the middle of a line by definition.
  259. if (*d->Start == '#')
  260. {
  261. d->isCommentedLine = true;
  262. ++current;
  263. if (current > d->End)
  264. d->chunks.emplace_back(false, 1);
  265. }
  266. }
  267. if (d->isCommentedLine == false)
  268. good_start = d->Start;
  269. else
  270. bad_start = d->Start;
  271. }
  272. else
  273. bad_start = d->Start;
  274. std::vector<std::pair<char*, size_t>> good_parts;
  275. while (current <= d->End)
  276. {
  277. size_t const restLength = (d->End - current);
  278. if (d->isCommentedLine == false)
  279. {
  280. current = static_cast<char*>(memchr(current, '#', restLength));
  281. if (current == nullptr)
  282. {
  283. size_t const goodLength = d->End - good_start;
  284. d->chunks.emplace_back(true, goodLength);
  285. if (good_start != d->Start)
  286. good_parts.push_back(std::make_pair(good_start, goodLength));
  287. break;
  288. }
  289. bad_start = current;
  290. --current;
  291. // ensure that this is really a comment and not a '#' in the middle of a line
  292. if (*current == '\n')
  293. {
  294. size_t const goodLength = (current - good_start) + 1;
  295. d->chunks.emplace_back(true, goodLength);
  296. good_parts.push_back(std::make_pair(good_start, goodLength));
  297. good_start = nullptr;
  298. d->isCommentedLine = true;
  299. }
  300. current += 2;
  301. }
  302. else // the current line is a comment
  303. {
  304. current = static_cast<char*>(memchr(current, '\n', restLength));
  305. if (current == nullptr)
  306. {
  307. d->chunks.emplace_back(false, (d->End - bad_start));
  308. break;
  309. }
  310. ++current;
  311. // is the next line a comment, too?
  312. if (current >= d->End || *current != '#')
  313. {
  314. d->chunks.emplace_back(false, (current - bad_start));
  315. good_start = current;
  316. bad_start = nullptr;
  317. d->isCommentedLine = false;
  318. }
  319. ++current;
  320. }
  321. }
  322. if (good_parts.empty() == false)
  323. {
  324. // we found comments, so move later parts over them
  325. current = d->Start;
  326. for (auto const &good: good_parts)
  327. {
  328. memmove(current, good.first, good.second);
  329. current += good.second;
  330. }
  331. d->End = current;
  332. }
  333. if (d->isCommentedLine == true)
  334. {
  335. // deal with a buffer containing only comments
  336. // or an (unfinished) comment at the end
  337. if (good_parts.empty() == true)
  338. d->End = d->Start;
  339. else
  340. d->Start = d->End;
  341. }
  342. else
  343. {
  344. // the buffer was all comment, but ended with the buffer
  345. if (good_parts.empty() == true && good_start >= d->End)
  346. d->End = d->Start;
  347. else
  348. d->Start = d->End;
  349. }
  350. }
  351. bool pkgTagFile::Fill()
  352. {
  353. unsigned long long const EndSize = d->End - d->Start;
  354. if (EndSize != 0)
  355. {
  356. memmove(d->Buffer,d->Start,EndSize);
  357. d->Start = d->End = d->Buffer + EndSize;
  358. }
  359. else
  360. d->Start = d->End = d->Buffer;
  361. unsigned long long Actual = 0;
  362. while (d->Done == false && d->Size > (Actual + 1))
  363. {
  364. if (FillBuffer(d) == false)
  365. return false;
  366. if ((d->Flags & pkgTagFile::SUPPORT_COMMENTS) != 0)
  367. RemoveCommentsFromBuffer(d);
  368. Actual = d->End - d->Buffer;
  369. }
  370. d->Start = d->Buffer;
  371. if (d->Done == true)
  372. {
  373. if (EndSize <= 3 && Actual == 0)
  374. return false;
  375. if (d->Size - (d->End - d->Buffer) < 4)
  376. return true;
  377. // Append a double new line if one does not exist
  378. unsigned int LineCount = 0;
  379. for (const char *E = d->End - 1; E - d->End < 6 && (*E == '\n' || *E == '\r'); E--)
  380. if (*E == '\n')
  381. ++LineCount;
  382. if (LineCount < 2)
  383. {
  384. if (static_cast<unsigned long long>(d->End - d->Buffer) >= d->Size)
  385. Resize(d->Size + 3);
  386. for (; LineCount < 2; ++LineCount)
  387. *d->End++ = '\n';
  388. }
  389. }
  390. return true;
  391. }
  392. /*}}}*/
  393. // TagFile::Jump - Jump to a pre-recorded location in the file /*{{{*/
  394. // ---------------------------------------------------------------------
  395. /* This jumps to a pre-recorded file location and reads the record
  396. that is there */
  397. bool pkgTagFile::Jump(pkgTagSection &Tag,unsigned long long Offset)
  398. {
  399. if ((d->Flags & pkgTagFile::SUPPORT_COMMENTS) == 0 &&
  400. // We are within a buffer space of the next hit..
  401. Offset >= d->iOffset && d->iOffset + (d->End - d->Start) > Offset)
  402. {
  403. unsigned long long Dist = Offset - d->iOffset;
  404. d->Start += Dist;
  405. d->iOffset += Dist;
  406. // if we have seen the end, don't ask for more
  407. if (d->Done == true)
  408. return Tag.Scan(d->Start, d->End - d->Start);
  409. else
  410. return Step(Tag);
  411. }
  412. // Reposition and reload..
  413. d->iOffset = Offset;
  414. d->Done = false;
  415. if (d->Fd->Seek(Offset) == false)
  416. return false;
  417. d->End = d->Start = d->Buffer;
  418. d->isCommentedLine = false;
  419. d->chunks.clear();
  420. if (Fill() == false)
  421. return false;
  422. if (Tag.Scan(d->Start, d->End - d->Start) == true)
  423. return true;
  424. // This appends a double new line (for the real eof handling)
  425. if (Fill() == false)
  426. return false;
  427. if (Tag.Scan(d->Start, d->End - d->Start, false) == false)
  428. return _error->Error(_("Unable to parse package file %s (%d)"),d->Fd->Name().c_str(), 2);
  429. return true;
  430. }
  431. /*}}}*/
  432. // pkgTagSection::pkgTagSection - Constructor /*{{{*/
  433. // ---------------------------------------------------------------------
  434. /* */
  435. APT_IGNORE_DEPRECATED_PUSH
  436. pkgTagSection::pkgTagSection()
  437. : Section(0), d(new pkgTagSectionPrivate()), Stop(0)
  438. {
  439. memset(&AlphaIndexes, 0, sizeof(AlphaIndexes));
  440. memset(&BetaIndexes, 0, sizeof(BetaIndexes));
  441. }
  442. APT_IGNORE_DEPRECATED_POP
  443. /*}}}*/
  444. // TagSection::Scan - Scan for the end of the header information /*{{{*/
  445. bool pkgTagSection::Scan(const char *Start,unsigned long MaxLength, bool const Restart)
  446. {
  447. Section = Start;
  448. const char *End = Start + MaxLength;
  449. if (Restart == false && d->Tags.empty() == false)
  450. {
  451. Stop = Section + d->Tags.back().StartTag;
  452. if (End <= Stop)
  453. return false;
  454. Stop = (const char *)memchr(Stop,'\n',End - Stop);
  455. if (Stop == NULL)
  456. return false;
  457. ++Stop;
  458. }
  459. else
  460. {
  461. Stop = Section;
  462. if (d->Tags.empty() == false)
  463. {
  464. memset(&AlphaIndexes, 0, sizeof(AlphaIndexes));
  465. memset(&BetaIndexes, 0, sizeof(BetaIndexes));
  466. d->Tags.clear();
  467. }
  468. d->Tags.reserve(0x100);
  469. }
  470. unsigned int TagCount = d->Tags.size();
  471. if (Stop == 0)
  472. return false;
  473. pkgTagSectionPrivate::TagData lastTagData(0);
  474. lastTagData.EndTag = 0;
  475. Key lastTagKey = Key::Unknown;
  476. unsigned int lastTagHash = 0;
  477. while (Stop < End)
  478. {
  479. TrimRecord(true,End);
  480. // this can happen when TrimRecord trims away the entire Record
  481. // (e.g. because it just contains comments)
  482. if(Stop == End)
  483. return true;
  484. // Start a new index and add it to the hash
  485. if (isspace_ascii(Stop[0]) == 0)
  486. {
  487. // store the last found tag
  488. if (lastTagData.EndTag != 0)
  489. {
  490. if (lastTagKey != Key::Unknown) {
  491. AlphaIndexes[static_cast<size_t>(lastTagKey)] = TagCount;
  492. } else {
  493. if (BetaIndexes[lastTagHash] != 0)
  494. lastTagData.NextInBucket = BetaIndexes[lastTagHash];
  495. APT_IGNORE_DEPRECATED_PUSH
  496. BetaIndexes[lastTagHash] = TagCount;
  497. APT_IGNORE_DEPRECATED_POP
  498. }
  499. d->Tags.push_back(lastTagData);
  500. }
  501. APT_IGNORE_DEPRECATED(++TagCount;)
  502. lastTagData = pkgTagSectionPrivate::TagData(Stop - Section);
  503. // find the colon separating tag and value
  504. char const * Colon = (char const *) memchr(Stop, ':', End - Stop);
  505. if (Colon == NULL)
  506. return false;
  507. // find the end of the tag (which might or might not be the colon)
  508. char const * EndTag = Colon;
  509. --EndTag;
  510. for (; EndTag > Stop && isspace_ascii(*EndTag) != 0; --EndTag)
  511. ;
  512. ++EndTag;
  513. lastTagData.EndTag = EndTag - Section;
  514. lastTagKey = pkgTagHash(Stop, EndTag - Stop);
  515. if (lastTagKey == Key::Unknown)
  516. lastTagHash = BetaHash(Stop, EndTag - Stop);
  517. // find the beginning of the value
  518. Stop = Colon + 1;
  519. for (; Stop < End && isspace_ascii(*Stop) != 0; ++Stop)
  520. if (*Stop == '\n' && Stop[1] != ' ')
  521. break;
  522. if (Stop >= End)
  523. return false;
  524. lastTagData.StartValue = Stop - Section;
  525. }
  526. Stop = (const char *)memchr(Stop,'\n',End - Stop);
  527. if (Stop == 0)
  528. return false;
  529. for (; Stop+1 < End && Stop[1] == '\r'; Stop++)
  530. /* nothing */
  531. ;
  532. // Double newline marks the end of the record
  533. if (Stop+1 < End && Stop[1] == '\n')
  534. {
  535. if (lastTagData.EndTag != 0)
  536. {
  537. if (lastTagKey != Key::Unknown) {
  538. AlphaIndexes[static_cast<size_t>(lastTagKey)] = TagCount;
  539. } else {
  540. if (BetaIndexes[lastTagHash] != 0)
  541. lastTagData.NextInBucket = BetaIndexes[lastTagHash];
  542. APT_IGNORE_DEPRECATED(BetaIndexes[lastTagHash] = TagCount;)
  543. }
  544. d->Tags.push_back(lastTagData);
  545. }
  546. pkgTagSectionPrivate::TagData const td(Stop - Section);
  547. d->Tags.push_back(td);
  548. TrimRecord(false,End);
  549. return true;
  550. }
  551. Stop++;
  552. }
  553. return false;
  554. }
  555. /*}}}*/
  556. // TagSection::TrimRecord - Trim off any garbage before/after a record /*{{{*/
  557. // ---------------------------------------------------------------------
  558. /* There should be exactly 2 newline at the end of the record, no more. */
  559. void pkgTagSection::TrimRecord(bool BeforeRecord, const char*& End)
  560. {
  561. if (BeforeRecord == true)
  562. return;
  563. for (; Stop < End && (Stop[0] == '\n' || Stop[0] == '\r'); Stop++);
  564. }
  565. /*}}}*/
  566. // TagSection::Trim - Trim off any trailing garbage /*{{{*/
  567. // ---------------------------------------------------------------------
  568. /* There should be exactly 1 newline at the end of the buffer, no more. */
  569. void pkgTagSection::Trim()
  570. {
  571. for (; Stop > Section + 2 && (Stop[-2] == '\n' || Stop[-2] == '\r'); Stop--);
  572. }
  573. /*}}}*/
  574. // TagSection::Exists - return True if a tag exists /*{{{*/
  575. bool pkgTagSection::Exists(StringView Tag) const
  576. {
  577. unsigned int tmp;
  578. return Find(Tag, tmp);
  579. }
  580. /*}}}*/
  581. // TagSection::Find - Locate a tag /*{{{*/
  582. // ---------------------------------------------------------------------
  583. /* This searches the section for a tag that matches the given string. */
  584. bool pkgTagSection::Find(Key key,unsigned int &Pos) const
  585. {
  586. auto Bucket = AlphaIndexes[static_cast<size_t>(key)];
  587. Pos = Bucket - 1;
  588. return Bucket != 0;
  589. }
  590. bool pkgTagSection::Find(StringView TagView,unsigned int &Pos) const
  591. {
  592. const char * const Tag = TagView.data();
  593. size_t const Length = TagView.length();
  594. auto key = pkgTagHash(Tag, Length);
  595. if (key != Key::Unknown)
  596. return Find(key, Pos);
  597. unsigned int Bucket = BetaIndexes[BetaHash(Tag, Length)];
  598. if (Bucket == 0)
  599. return false;
  600. for (; Bucket != 0; Bucket = d->Tags[Bucket - 1].NextInBucket)
  601. {
  602. if ((d->Tags[Bucket - 1].EndTag - d->Tags[Bucket - 1].StartTag) != Length)
  603. continue;
  604. char const * const St = Section + d->Tags[Bucket - 1].StartTag;
  605. if (strncasecmp(Tag,St,Length) != 0)
  606. continue;
  607. Pos = Bucket - 1;
  608. return true;
  609. }
  610. Pos = 0;
  611. return false;
  612. }
  613. bool pkgTagSection::FindInternal(unsigned int Pos, const char *&Start,
  614. const char *&End) const
  615. {
  616. Start = Section + d->Tags[Pos].StartValue;
  617. // Strip off the gunk from the end
  618. End = Section + d->Tags[Pos + 1].StartTag;
  619. if (unlikely(Start > End))
  620. return _error->Error("Internal parsing error");
  621. for (; isspace_ascii(End[-1]) != 0 && End > Start; --End);
  622. return true;
  623. }
  624. bool pkgTagSection::Find(StringView Tag,const char *&Start,
  625. const char *&End) const
  626. {
  627. unsigned int Pos;
  628. return Find(Tag, Pos) && FindInternal(Pos, Start, End);
  629. }
  630. bool pkgTagSection::Find(Key key,const char *&Start,
  631. const char *&End) const
  632. {
  633. unsigned int Pos;
  634. return Find(key, Pos) && FindInternal(Pos, Start, End);
  635. }
  636. /*}}}*/
  637. // TagSection::FindS - Find a string /*{{{*/
  638. StringView pkgTagSection::Find(StringView Tag) const
  639. {
  640. const char *Start;
  641. const char *End;
  642. if (Find(Tag,Start,End) == false)
  643. return StringView();
  644. return StringView(Start, End - Start);
  645. }
  646. StringView pkgTagSection::Find(Key key) const
  647. {
  648. const char *Start;
  649. const char *End;
  650. if (Find(key,Start,End) == false)
  651. return StringView();
  652. return StringView(Start, End - Start);
  653. }
  654. /*}}}*/
  655. // TagSection::FindRawS - Find a string /*{{{*/
  656. StringView pkgTagSection::FindRawInternal(unsigned int Pos) const
  657. {
  658. char const *Start = (char const *) memchr(Section + d->Tags[Pos].EndTag, ':', d->Tags[Pos].StartValue - d->Tags[Pos].EndTag);
  659. ++Start;
  660. char const *End = Section + d->Tags[Pos + 1].StartTag;
  661. if (unlikely(Start > End))
  662. return "";
  663. for (; isspace_ascii(End[-1]) != 0 && End > Start; --End);
  664. return StringView(Start, End - Start);
  665. }
  666. StringView pkgTagSection::FindRaw(StringView Tag) const
  667. {
  668. unsigned int Pos;
  669. return Find(Tag, Pos) ? FindRawInternal(Pos) : "";
  670. }
  671. StringView pkgTagSection::FindRaw(Key key) const
  672. {
  673. unsigned int Pos;
  674. return Find(key, Pos) ? FindRawInternal(Pos) : "";
  675. }
  676. /*}}}*/
  677. // TagSection::FindI - Find an integer /*{{{*/
  678. // ---------------------------------------------------------------------
  679. /* */
  680. signed int pkgTagSection::FindIInternal(unsigned int Pos,signed long Default) const
  681. {
  682. const char *Start;
  683. const char *Stop;
  684. if (FindInternal(Pos,Start,Stop) == false)
  685. return Default;
  686. // Copy it into a temp buffer so we can use strtol
  687. char S[300];
  688. if ((unsigned)(Stop - Start) >= sizeof(S))
  689. return Default;
  690. strncpy(S,Start,Stop-Start);
  691. S[Stop - Start] = 0;
  692. errno = 0;
  693. char *End;
  694. signed long Result = strtol(S,&End,10);
  695. if (errno == ERANGE ||
  696. Result < std::numeric_limits<int>::min() || Result > std::numeric_limits<int>::max()) {
  697. errno = ERANGE;
  698. _error->Error(_("Cannot convert %s to integer: out of range"), S);
  699. }
  700. if (S == End)
  701. return Default;
  702. return Result;
  703. }
  704. signed int pkgTagSection::FindI(Key key,signed long Default) const
  705. {
  706. unsigned int Pos;
  707. return Find(key, Pos) ? FindIInternal(Pos) : Default;
  708. }
  709. signed int pkgTagSection::FindI(StringView Tag,signed long Default) const
  710. {
  711. unsigned int Pos;
  712. return Find(Tag, Pos) ? FindIInternal(Pos, Default) : Default;
  713. }
  714. /*}}}*/
  715. // TagSection::FindULL - Find an unsigned long long integer /*{{{*/
  716. // ---------------------------------------------------------------------
  717. /* */
  718. unsigned long long pkgTagSection::FindULLInternal(unsigned int Pos, unsigned long long const &Default) const
  719. {
  720. const char *Start;
  721. const char *Stop;
  722. if (FindInternal(Pos,Start,Stop) == false)
  723. return Default;
  724. // Copy it into a temp buffer so we can use strtoull
  725. char S[100];
  726. if ((unsigned)(Stop - Start) >= sizeof(S))
  727. return Default;
  728. strncpy(S,Start,Stop-Start);
  729. S[Stop - Start] = 0;
  730. char *End;
  731. unsigned long long Result = strtoull(S,&End,10);
  732. if (S == End)
  733. return Default;
  734. return Result;
  735. }
  736. unsigned long long pkgTagSection::FindULL(Key key, unsigned long long const &Default) const
  737. {
  738. unsigned int Pos;
  739. return Find(key, Pos) ? FindULLInternal(Pos, Default) : Default;
  740. }
  741. unsigned long long pkgTagSection::FindULL(StringView Tag, unsigned long long const &Default) const
  742. {
  743. unsigned int Pos;
  744. return Find(Tag, Pos) ? FindULLInternal(Pos, Default) : Default;
  745. }
  746. /*}}}*/
  747. // TagSection::FindB - Find boolean value /*{{{*/
  748. // ---------------------------------------------------------------------
  749. /* */
  750. bool pkgTagSection::FindBInternal(unsigned int Pos, bool Default) const
  751. {
  752. const char *Start, *Stop;
  753. if (FindInternal(Pos, Start, Stop) == false)
  754. return Default;
  755. return StringToBool(string(Start, Stop));
  756. }
  757. bool pkgTagSection::FindB(Key key, bool Default) const
  758. {
  759. unsigned int Pos;
  760. return Find(key, Pos) ? FindBInternal(Pos, Default): Default;
  761. }
  762. bool pkgTagSection::FindB(StringView Tag, bool Default) const
  763. {
  764. unsigned int Pos;
  765. return Find(Tag, Pos) ? FindBInternal(Pos, Default) : Default;
  766. }
  767. /*}}}*/
  768. // TagSection::FindFlag - Locate a yes/no type flag /*{{{*/
  769. // ---------------------------------------------------------------------
  770. /* The bits marked in Flag are masked on/off in Flags */
  771. bool pkgTagSection::FindFlagInternal(unsigned int Pos, uint8_t &Flags,
  772. uint8_t const Flag) const
  773. {
  774. const char *Start;
  775. const char *Stop;
  776. if (FindInternal(Pos,Start,Stop) == false)
  777. return true;
  778. return FindFlag(Flags, Flag, Start, Stop);
  779. }
  780. bool pkgTagSection::FindFlag(Key key, uint8_t &Flags,
  781. uint8_t const Flag) const
  782. {
  783. unsigned int Pos;
  784. if (Find(key,Pos) == false)
  785. return true;
  786. return FindFlagInternal(Pos, Flags, Flag);
  787. }
  788. bool pkgTagSection::FindFlag(StringView Tag, uint8_t &Flags,
  789. uint8_t const Flag) const
  790. {
  791. unsigned int Pos;
  792. if (Find(Tag,Pos) == false)
  793. return true;
  794. return FindFlagInternal(Pos, Flags, Flag);
  795. }
  796. bool pkgTagSection::FindFlag(uint8_t &Flags, uint8_t const Flag,
  797. char const* const Start, char const* const Stop)
  798. {
  799. switch (StringToBool(string(Start, Stop)))
  800. {
  801. case 0:
  802. Flags &= ~Flag;
  803. return true;
  804. case 1:
  805. Flags |= Flag;
  806. return true;
  807. default:
  808. _error->Warning("Unknown flag value: %s",string(Start,Stop).c_str());
  809. return true;
  810. }
  811. return true;
  812. }
  813. bool pkgTagSection::FindFlagInternal(unsigned int Pos,unsigned long &Flags,
  814. unsigned long Flag) const
  815. {
  816. const char *Start;
  817. const char *Stop;
  818. if (FindInternal(Pos,Start,Stop) == false)
  819. return true;
  820. return FindFlag(Flags, Flag, Start, Stop);
  821. }
  822. bool pkgTagSection::FindFlag(Key key,unsigned long &Flags,
  823. unsigned long Flag) const
  824. {
  825. unsigned int Pos;
  826. return Find(key, Pos) ? FindFlagInternal(Pos, Flags, Flag) : true;
  827. }
  828. bool pkgTagSection::FindFlag(StringView Tag,unsigned long &Flags,
  829. unsigned long Flag) const
  830. {
  831. unsigned int Pos;
  832. return Find(Tag, Pos) ? FindFlagInternal(Pos, Flags, Flag) : true;
  833. }
  834. bool pkgTagSection::FindFlag(unsigned long &Flags, unsigned long Flag,
  835. char const* Start, char const* Stop)
  836. {
  837. switch (StringToBool(string(Start, Stop)))
  838. {
  839. case 0:
  840. Flags &= ~Flag;
  841. return true;
  842. case 1:
  843. Flags |= Flag;
  844. return true;
  845. default:
  846. _error->Warning("Unknown flag value: %s",string(Start,Stop).c_str());
  847. return true;
  848. }
  849. return true;
  850. }
  851. /*}}}*/
  852. void pkgTagSection::Get(const char *&Start,const char *&Stop,unsigned int I) const/*{{{*/
  853. {
  854. Start = Section + d->Tags[I].StartTag;
  855. Stop = Section + d->Tags[I+1].StartTag;
  856. }
  857. /*}}}*/
  858. APT_PURE unsigned int pkgTagSection::Count() const { /*{{{*/
  859. if (d->Tags.empty() == true)
  860. return 0;
  861. // the last element is just marking the end and isn't a real one
  862. return d->Tags.size() - 1;
  863. }
  864. /*}}}*/
  865. // TagSection::Write - Ordered (re)writing of fields /*{{{*/
  866. pkgTagSection::Tag pkgTagSection::Tag::Remove(std::string const &Name)
  867. {
  868. return Tag(REMOVE, Name, "");
  869. }
  870. pkgTagSection::Tag pkgTagSection::Tag::Rename(std::string const &OldName, std::string const &NewName)
  871. {
  872. return Tag(RENAME, OldName, NewName);
  873. }
  874. pkgTagSection::Tag pkgTagSection::Tag::Rewrite(std::string const &Name, std::string const &Data)
  875. {
  876. if (Data.empty() == true)
  877. return Tag(REMOVE, Name, "");
  878. else
  879. return Tag(REWRITE, Name, Data);
  880. }
  881. static bool WriteTag(FileFd &File, std::string Tag, StringView Value)
  882. {
  883. if (Value.empty() || isspace_ascii(Value[0]) != 0)
  884. Tag.append(":");
  885. else
  886. Tag.append(": ");
  887. Tag.append(Value.data(), Value.length());
  888. Tag.append("\n");
  889. return File.Write(Tag.c_str(), Tag.length());
  890. }
  891. static bool RewriteTags(FileFd &File, pkgTagSection const * const This, char const * const Tag,
  892. std::vector<pkgTagSection::Tag>::const_iterator &R,
  893. std::vector<pkgTagSection::Tag>::const_iterator const &REnd)
  894. {
  895. size_t const TagLen = strlen(Tag);
  896. for (; R != REnd; ++R)
  897. {
  898. std::string data;
  899. if (R->Name.length() == TagLen && strncasecmp(R->Name.c_str(), Tag, R->Name.length()) == 0)
  900. {
  901. if (R->Action != pkgTagSection::Tag::REWRITE)
  902. break;
  903. data = R->Data;
  904. }
  905. else if(R->Action == pkgTagSection::Tag::RENAME && R->Data.length() == TagLen &&
  906. strncasecmp(R->Data.c_str(), Tag, R->Data.length()) == 0)
  907. data = This->FindRaw(R->Name.c_str()).to_string();
  908. else
  909. continue;
  910. return WriteTag(File, Tag, data);
  911. }
  912. return true;
  913. }
  914. bool pkgTagSection::Write(FileFd &File, char const * const * const Order, std::vector<Tag> const &Rewrite) const
  915. {
  916. // first pass: Write everything we have an order for
  917. if (Order != NULL)
  918. {
  919. for (unsigned int I = 0; Order[I] != 0; ++I)
  920. {
  921. std::vector<Tag>::const_iterator R = Rewrite.begin();
  922. if (RewriteTags(File, this, Order[I], R, Rewrite.end()) == false)
  923. return false;
  924. if (R != Rewrite.end())
  925. continue;
  926. if (Exists(Order[I]) == false)
  927. continue;
  928. if (WriteTag(File, Order[I], FindRaw(Order[I])) == false)
  929. return false;
  930. }
  931. }
  932. // second pass: See if we have tags which aren't ordered
  933. if (d->Tags.empty() == false)
  934. {
  935. for (std::vector<pkgTagSectionPrivate::TagData>::const_iterator T = d->Tags.begin(); T != d->Tags.end() - 1; ++T)
  936. {
  937. char const * const fieldname = Section + T->StartTag;
  938. size_t fieldnamelen = T->EndTag - T->StartTag;
  939. if (Order != NULL)
  940. {
  941. unsigned int I = 0;
  942. for (; Order[I] != 0; ++I)
  943. {
  944. if (fieldnamelen == strlen(Order[I]) && strncasecmp(fieldname, Order[I], fieldnamelen) == 0)
  945. break;
  946. }
  947. if (Order[I] != 0)
  948. continue;
  949. }
  950. std::string const name(fieldname, fieldnamelen);
  951. std::vector<Tag>::const_iterator R = Rewrite.begin();
  952. if (RewriteTags(File, this, name.c_str(), R, Rewrite.end()) == false)
  953. return false;
  954. if (R != Rewrite.end())
  955. continue;
  956. if (WriteTag(File, name, FindRaw(name)) == false)
  957. return false;
  958. }
  959. }
  960. // last pass: see if there are any rewrites remaining we haven't done yet
  961. for (std::vector<Tag>::const_iterator R = Rewrite.begin(); R != Rewrite.end(); ++R)
  962. {
  963. if (R->Action == Tag::REMOVE)
  964. continue;
  965. std::string const name = ((R->Action == Tag::RENAME) ? R->Data : R->Name);
  966. if (Exists(name.c_str()))
  967. continue;
  968. if (Order != NULL)
  969. {
  970. unsigned int I = 0;
  971. for (; Order[I] != 0; ++I)
  972. {
  973. if (strncasecmp(name.c_str(), Order[I], name.length()) == 0 && name.length() == strlen(Order[I]))
  974. break;
  975. }
  976. if (Order[I] != 0)
  977. continue;
  978. }
  979. if (WriteTag(File, name, ((R->Action == Tag::RENAME) ? FindRaw(R->Name) : R->Data)) == false)
  980. return false;
  981. }
  982. return true;
  983. }
  984. /*}}}*/
  985. void pkgUserTagSection::TrimRecord(bool /*BeforeRecord*/, const char* &End)/*{{{*/
  986. {
  987. for (; Stop < End && (Stop[0] == '\n' || Stop[0] == '\r' || Stop[0] == '#'); Stop++)
  988. if (Stop[0] == '#')
  989. Stop = (const char*) memchr(Stop,'\n',End-Stop);
  990. }
  991. /*}}}*/
  992. #include "tagfile-order.c"
  993. // TFRewrite - Rewrite a control record /*{{{*/
  994. // ---------------------------------------------------------------------
  995. /* This writes the control record to stdout rewriting it as necessary. The
  996. override map item specificies the rewriting rules to follow. This also
  997. takes the time to sort the feild list. */
  998. APT_IGNORE_DEPRECATED_PUSH
  999. bool TFRewrite(FILE *Output,pkgTagSection const &Tags,const char *Order[],
  1000. TFRewriteData *Rewrite)
  1001. {
  1002. unsigned char Visited[256]; // Bit 1 is Order, Bit 2 is Rewrite
  1003. for (unsigned I = 0; I != 256; I++)
  1004. Visited[I] = 0;
  1005. // Set new tag up as necessary.
  1006. for (unsigned int J = 0; Rewrite != 0 && Rewrite[J].Tag != 0; J++)
  1007. {
  1008. if (Rewrite[J].NewTag == 0)
  1009. Rewrite[J].NewTag = Rewrite[J].Tag;
  1010. }
  1011. // Write all all of the tags, in order.
  1012. if (Order != NULL)
  1013. {
  1014. for (unsigned int I = 0; Order[I] != 0; I++)
  1015. {
  1016. bool Rewritten = false;
  1017. // See if this is a field that needs to be rewritten
  1018. for (unsigned int J = 0; Rewrite != 0 && Rewrite[J].Tag != 0; J++)
  1019. {
  1020. if (strcasecmp(Rewrite[J].Tag,Order[I]) == 0)
  1021. {
  1022. Visited[J] |= 2;
  1023. if (Rewrite[J].Rewrite != 0 && Rewrite[J].Rewrite[0] != 0)
  1024. {
  1025. if (isspace_ascii(Rewrite[J].Rewrite[0]))
  1026. fprintf(Output,"%s:%s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1027. else
  1028. fprintf(Output,"%s: %s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1029. }
  1030. Rewritten = true;
  1031. break;
  1032. }
  1033. }
  1034. // See if it is in the fragment
  1035. unsigned Pos;
  1036. if (Tags.Find(StringView(Order[I]),Pos) == false)
  1037. continue;
  1038. Visited[Pos] |= 1;
  1039. if (Rewritten == true)
  1040. continue;
  1041. /* Write out this element, taking a moment to rewrite the tag
  1042. in case of changes of case. */
  1043. const char *Start;
  1044. const char *Stop;
  1045. Tags.Get(Start,Stop,Pos);
  1046. if (fputs(Order[I],Output) < 0)
  1047. return _error->Errno("fputs","IO Error to output");
  1048. Start += strlen(Order[I]);
  1049. if (fwrite(Start,Stop - Start,1,Output) != 1)
  1050. return _error->Errno("fwrite","IO Error to output");
  1051. if (Stop[-1] != '\n')
  1052. fprintf(Output,"\n");
  1053. }
  1054. }
  1055. // Now write all the old tags that were missed.
  1056. for (unsigned int I = 0; I != Tags.Count(); I++)
  1057. {
  1058. if ((Visited[I] & 1) == 1)
  1059. continue;
  1060. const char *Start;
  1061. const char *Stop;
  1062. Tags.Get(Start,Stop,I);
  1063. const char *End = Start;
  1064. for (; End < Stop && *End != ':'; End++);
  1065. // See if this is a field that needs to be rewritten
  1066. bool Rewritten = false;
  1067. for (unsigned int J = 0; Rewrite != 0 && Rewrite[J].Tag != 0; J++)
  1068. {
  1069. if (stringcasecmp(Start,End,Rewrite[J].Tag) == 0)
  1070. {
  1071. Visited[J] |= 2;
  1072. if (Rewrite[J].Rewrite != 0 && Rewrite[J].Rewrite[0] != 0)
  1073. {
  1074. if (isspace_ascii(Rewrite[J].Rewrite[0]))
  1075. fprintf(Output,"%s:%s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1076. else
  1077. fprintf(Output,"%s: %s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1078. }
  1079. Rewritten = true;
  1080. break;
  1081. }
  1082. }
  1083. if (Rewritten == true)
  1084. continue;
  1085. // Write out this element
  1086. if (fwrite(Start,Stop - Start,1,Output) != 1)
  1087. return _error->Errno("fwrite","IO Error to output");
  1088. if (Stop[-1] != '\n')
  1089. fprintf(Output,"\n");
  1090. }
  1091. // Now write all the rewrites that were missed
  1092. for (unsigned int J = 0; Rewrite != 0 && Rewrite[J].Tag != 0; J++)
  1093. {
  1094. if ((Visited[J] & 2) == 2)
  1095. continue;
  1096. if (Rewrite[J].Rewrite != 0 && Rewrite[J].Rewrite[0] != 0)
  1097. {
  1098. if (isspace_ascii(Rewrite[J].Rewrite[0]))
  1099. fprintf(Output,"%s:%s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1100. else
  1101. fprintf(Output,"%s: %s\n",Rewrite[J].NewTag,Rewrite[J].Rewrite);
  1102. }
  1103. }
  1104. return true;
  1105. }
  1106. APT_IGNORE_DEPRECATED_POP
  1107. /*}}}*/
  1108. pkgTagSection::~pkgTagSection() { delete d; }