strutl.cc 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  1. // -*- mode: cpp; mode: fold -*-
  2. // Description /*{{{*/
  3. // $Id: strutl.cc,v 1.48 2003/07/18 14:15:11 mdz Exp $
  4. /* ######################################################################
  5. String Util - Some useful string functions.
  6. These have been collected from here and there to do all sorts of useful
  7. things to strings. They are useful in file parsers, URI handlers and
  8. especially in APT methods.
  9. This source is placed in the Public Domain, do with it what you will
  10. It was originally written by Jason Gunthorpe <jgg@gpu.srv.ualberta.ca>
  11. ##################################################################### */
  12. /*}}}*/
  13. // Includes /*{{{*/
  14. #include <config.h>
  15. #include <apt-pkg/strutl.h>
  16. #include <apt-pkg/fileutl.h>
  17. #include <apt-pkg/error.h>
  18. #include <array>
  19. #include <algorithm>
  20. #include <iomanip>
  21. #include <locale>
  22. #include <sstream>
  23. #include <string>
  24. #include <vector>
  25. #include <stddef.h>
  26. #include <stdlib.h>
  27. #include <time.h>
  28. #include <ctype.h>
  29. #include <string.h>
  30. #include <stdio.h>
  31. #include <unistd.h>
  32. #include <regex.h>
  33. #include <errno.h>
  34. #include <stdarg.h>
  35. #include <iconv.h>
  36. #include <apti18n.h>
  37. /*}}}*/
  38. using namespace std;
  39. // Strip - Remove white space from the front and back of a string /*{{{*/
  40. // ---------------------------------------------------------------------
  41. namespace APT {
  42. namespace String {
  43. std::string Strip(const std::string &str)
  44. {
  45. // ensure we have at least one character
  46. if (str.empty() == true)
  47. return str;
  48. char const * const s = str.c_str();
  49. size_t start = 0;
  50. for (; isspace(s[start]) != 0; ++start)
  51. ; // find the first not-space
  52. // string contains only whitespaces
  53. if (s[start] == '\0')
  54. return "";
  55. size_t end = str.length() - 1;
  56. for (; isspace(s[end]) != 0; --end)
  57. ; // find the last not-space
  58. return str.substr(start, end - start + 1);
  59. }
  60. bool Endswith(const std::string &s, const std::string &end)
  61. {
  62. if (end.size() > s.size())
  63. return false;
  64. return (s.compare(s.size() - end.size(), end.size(), end) == 0);
  65. }
  66. bool Startswith(const std::string &s, const std::string &start)
  67. {
  68. if (start.size() > s.size())
  69. return false;
  70. return (s.compare(0, start.size(), start) == 0);
  71. }
  72. }
  73. }
  74. /*}}}*/
  75. // UTF8ToCodeset - Convert some UTF-8 string for some codeset /*{{{*/
  76. // ---------------------------------------------------------------------
  77. /* This is handy to use before display some information for enduser */
  78. bool UTF8ToCodeset(const char *codeset, const string &orig, string *dest)
  79. {
  80. iconv_t cd;
  81. const char *inbuf;
  82. char *inptr, *outbuf;
  83. size_t insize, bufsize;
  84. dest->clear();
  85. cd = iconv_open(codeset, "UTF-8");
  86. if (cd == (iconv_t)(-1)) {
  87. // Something went wrong
  88. if (errno == EINVAL)
  89. _error->Error("conversion from 'UTF-8' to '%s' not available",
  90. codeset);
  91. else
  92. perror("iconv_open");
  93. return false;
  94. }
  95. insize = bufsize = orig.size();
  96. inbuf = orig.data();
  97. inptr = (char *)inbuf;
  98. outbuf = new char[bufsize];
  99. size_t lastError = -1;
  100. while (insize != 0)
  101. {
  102. char *outptr = outbuf;
  103. size_t outsize = bufsize;
  104. size_t const err = iconv(cd, &inptr, &insize, &outptr, &outsize);
  105. dest->append(outbuf, outptr - outbuf);
  106. if (err == (size_t)(-1))
  107. {
  108. switch (errno)
  109. {
  110. case EILSEQ:
  111. insize--;
  112. inptr++;
  113. // replace a series of unknown multibytes with a single "?"
  114. if (lastError != insize) {
  115. lastError = insize - 1;
  116. dest->append("?");
  117. }
  118. break;
  119. case EINVAL:
  120. insize = 0;
  121. break;
  122. case E2BIG:
  123. if (outptr == outbuf)
  124. {
  125. bufsize *= 2;
  126. delete[] outbuf;
  127. outbuf = new char[bufsize];
  128. }
  129. break;
  130. }
  131. }
  132. }
  133. delete[] outbuf;
  134. iconv_close(cd);
  135. return true;
  136. }
  137. /*}}}*/
  138. // strstrip - Remove white space from the front and back of a string /*{{{*/
  139. // ---------------------------------------------------------------------
  140. /* This is handy to use when parsing a file. It also removes \n's left
  141. over from fgets and company */
  142. char *_strstrip(char *String)
  143. {
  144. for (;*String != 0 && (*String == ' ' || *String == '\t'); String++);
  145. if (*String == 0)
  146. return String;
  147. return _strrstrip(String);
  148. }
  149. /*}}}*/
  150. // strrstrip - Remove white space from the back of a string /*{{{*/
  151. // ---------------------------------------------------------------------
  152. char *_strrstrip(char *String)
  153. {
  154. char *End = String + strlen(String) - 1;
  155. for (;End != String - 1 && (*End == ' ' || *End == '\t' || *End == '\n' ||
  156. *End == '\r'); End--);
  157. End++;
  158. *End = 0;
  159. return String;
  160. }
  161. /*}}}*/
  162. // strtabexpand - Converts tabs into 8 spaces /*{{{*/
  163. // ---------------------------------------------------------------------
  164. /* */
  165. char *_strtabexpand(char *String,size_t Len)
  166. {
  167. for (char *I = String; I != I + Len && *I != 0; I++)
  168. {
  169. if (*I != '\t')
  170. continue;
  171. if (I + 8 > String + Len)
  172. {
  173. *I = 0;
  174. return String;
  175. }
  176. /* Assume the start of the string is 0 and find the next 8 char
  177. division */
  178. int Len;
  179. if (String == I)
  180. Len = 1;
  181. else
  182. Len = 8 - ((String - I) % 8);
  183. Len -= 2;
  184. if (Len <= 0)
  185. {
  186. *I = ' ';
  187. continue;
  188. }
  189. memmove(I + Len,I + 1,strlen(I) + 1);
  190. for (char *J = I; J + Len != I; *I = ' ', I++);
  191. }
  192. return String;
  193. }
  194. /*}}}*/
  195. // ParseQuoteWord - Parse a single word out of a string /*{{{*/
  196. // ---------------------------------------------------------------------
  197. /* This grabs a single word, converts any % escaped characters to their
  198. proper values and advances the pointer. Double quotes are understood
  199. and striped out as well. This is for URI/URL parsing. It also can
  200. understand [] brackets.*/
  201. bool ParseQuoteWord(const char *&String,string &Res)
  202. {
  203. // Skip leading whitespace
  204. const char *C = String;
  205. for (;*C != 0 && *C == ' '; C++);
  206. if (*C == 0)
  207. return false;
  208. // Jump to the next word
  209. for (;*C != 0 && isspace(*C) == 0; C++)
  210. {
  211. if (*C == '"')
  212. {
  213. C = strchr(C + 1, '"');
  214. if (C == NULL)
  215. return false;
  216. }
  217. if (*C == '[')
  218. {
  219. C = strchr(C + 1, ']');
  220. if (C == NULL)
  221. return false;
  222. }
  223. }
  224. // Now de-quote characters
  225. char Buffer[1024];
  226. char Tmp[3];
  227. const char *Start = String;
  228. char *I;
  229. for (I = Buffer; I < Buffer + sizeof(Buffer) && Start != C; I++)
  230. {
  231. if (*Start == '%' && Start + 2 < C &&
  232. isxdigit(Start[1]) && isxdigit(Start[2]))
  233. {
  234. Tmp[0] = Start[1];
  235. Tmp[1] = Start[2];
  236. Tmp[2] = 0;
  237. *I = (char)strtol(Tmp,0,16);
  238. Start += 3;
  239. continue;
  240. }
  241. if (*Start != '"')
  242. *I = *Start;
  243. else
  244. I--;
  245. Start++;
  246. }
  247. *I = 0;
  248. Res = Buffer;
  249. // Skip ending white space
  250. for (;*C != 0 && isspace(*C) != 0; C++);
  251. String = C;
  252. return true;
  253. }
  254. /*}}}*/
  255. // ParseCWord - Parses a string like a C "" expression /*{{{*/
  256. // ---------------------------------------------------------------------
  257. /* This expects a series of space separated strings enclosed in ""'s.
  258. It concatenates the ""'s into a single string. */
  259. bool ParseCWord(const char *&String,string &Res)
  260. {
  261. // Skip leading whitespace
  262. const char *C = String;
  263. for (;*C != 0 && *C == ' '; C++);
  264. if (*C == 0)
  265. return false;
  266. char Buffer[1024];
  267. char *Buf = Buffer;
  268. if (strlen(String) >= sizeof(Buffer))
  269. return false;
  270. for (; *C != 0; C++)
  271. {
  272. if (*C == '"')
  273. {
  274. for (C++; *C != 0 && *C != '"'; C++)
  275. *Buf++ = *C;
  276. if (*C == 0)
  277. return false;
  278. continue;
  279. }
  280. if (C != String && isspace(*C) != 0 && isspace(C[-1]) != 0)
  281. continue;
  282. if (isspace(*C) == 0)
  283. return false;
  284. *Buf++ = ' ';
  285. }
  286. *Buf = 0;
  287. Res = Buffer;
  288. String = C;
  289. return true;
  290. }
  291. /*}}}*/
  292. // QuoteString - Convert a string into quoted from /*{{{*/
  293. // ---------------------------------------------------------------------
  294. /* */
  295. string QuoteString(const string &Str, const char *Bad)
  296. {
  297. std::stringstream Res;
  298. for (string::const_iterator I = Str.begin(); I != Str.end(); ++I)
  299. {
  300. if (strchr(Bad,*I) != 0 || isprint(*I) == 0 ||
  301. *I == 0x25 || // percent '%' char
  302. *I <= 0x20 || *I >= 0x7F) // control chars
  303. {
  304. ioprintf(Res, "%%%02hhx", *I);
  305. }
  306. else
  307. Res << *I;
  308. }
  309. return Res.str();
  310. }
  311. /*}}}*/
  312. // DeQuoteString - Convert a string from quoted from /*{{{*/
  313. // ---------------------------------------------------------------------
  314. /* This undoes QuoteString */
  315. string DeQuoteString(const string &Str)
  316. {
  317. return DeQuoteString(Str.begin(),Str.end());
  318. }
  319. string DeQuoteString(string::const_iterator const &begin,
  320. string::const_iterator const &end)
  321. {
  322. string Res;
  323. for (string::const_iterator I = begin; I != end; ++I)
  324. {
  325. if (*I == '%' && I + 2 < end &&
  326. isxdigit(I[1]) && isxdigit(I[2]))
  327. {
  328. char Tmp[3];
  329. Tmp[0] = I[1];
  330. Tmp[1] = I[2];
  331. Tmp[2] = 0;
  332. Res += (char)strtol(Tmp,0,16);
  333. I += 2;
  334. continue;
  335. }
  336. else
  337. Res += *I;
  338. }
  339. return Res;
  340. }
  341. /*}}}*/
  342. // SizeToStr - Convert a long into a human readable size /*{{{*/
  343. // ---------------------------------------------------------------------
  344. /* A max of 4 digits are shown before conversion to the next highest unit.
  345. The max length of the string will be 5 chars unless the size is > 10
  346. YottaBytes (E24) */
  347. string SizeToStr(double Size)
  348. {
  349. double ASize;
  350. if (Size >= 0)
  351. ASize = Size;
  352. else
  353. ASize = -1*Size;
  354. /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
  355. ExaBytes, ZettaBytes, YottaBytes */
  356. char Ext[] = {'\0','k','M','G','T','P','E','Z','Y'};
  357. int I = 0;
  358. while (I <= 8)
  359. {
  360. if (ASize < 100 && I != 0)
  361. {
  362. std::string S;
  363. strprintf(S, "%'.1f %c", ASize, Ext[I]);
  364. return S;
  365. }
  366. if (ASize < 10000)
  367. {
  368. std::string S;
  369. strprintf(S, "%'.0f %c", ASize, Ext[I]);
  370. return S;
  371. }
  372. ASize /= 1000.0;
  373. I++;
  374. }
  375. return "";
  376. }
  377. /*}}}*/
  378. // TimeToStr - Convert the time into a string /*{{{*/
  379. // ---------------------------------------------------------------------
  380. /* Converts a number of seconds to a hms format */
  381. string TimeToStr(unsigned long Sec)
  382. {
  383. std::string S;
  384. if (Sec > 60*60*24)
  385. {
  386. //TRANSLATOR: d means days, h means hours, min means minutes, s means seconds
  387. strprintf(S,_("%lid %lih %limin %lis"),Sec/60/60/24,(Sec/60/60) % 24,(Sec/60) % 60,Sec % 60);
  388. }
  389. else if (Sec > 60*60)
  390. {
  391. //TRANSLATOR: h means hours, min means minutes, s means seconds
  392. strprintf(S,_("%lih %limin %lis"),Sec/60/60,(Sec/60) % 60,Sec % 60);
  393. }
  394. else if (Sec > 60)
  395. {
  396. //TRANSLATOR: min means minutes, s means seconds
  397. strprintf(S,_("%limin %lis"),Sec/60,Sec % 60);
  398. }
  399. else
  400. {
  401. //TRANSLATOR: s means seconds
  402. strprintf(S,_("%lis"),Sec);
  403. }
  404. return S;
  405. }
  406. /*}}}*/
  407. // SubstVar - Substitute a string for another string /*{{{*/
  408. // ---------------------------------------------------------------------
  409. /* This replaces all occurrences of Subst with Contents in Str. */
  410. string SubstVar(const string &Str,const string &Subst,const string &Contents)
  411. {
  412. if (Subst.empty() == true)
  413. return Str;
  414. string::size_type Pos = 0;
  415. string::size_type OldPos = 0;
  416. string Temp;
  417. while (OldPos < Str.length() &&
  418. (Pos = Str.find(Subst,OldPos)) != string::npos)
  419. {
  420. if (OldPos != Pos)
  421. Temp.append(Str, OldPos, Pos - OldPos);
  422. if (Contents.empty() == false)
  423. Temp.append(Contents);
  424. OldPos = Pos + Subst.length();
  425. }
  426. if (OldPos == 0)
  427. return Str;
  428. if (OldPos >= Str.length())
  429. return Temp;
  430. Temp.append(Str, OldPos, string::npos);
  431. return Temp;
  432. }
  433. string SubstVar(string Str,const struct SubstVar *Vars)
  434. {
  435. for (; Vars->Subst != 0; Vars++)
  436. Str = SubstVar(Str,Vars->Subst,*Vars->Contents);
  437. return Str;
  438. }
  439. /*}}}*/
  440. // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
  441. // ---------------------------------------------------------------------
  442. /* Returns a string with the supplied separator depth + 1 times in it */
  443. std::string OutputInDepth(const unsigned long Depth, const char* Separator)
  444. {
  445. std::string output = "";
  446. for(unsigned long d=Depth+1; d > 0; d--)
  447. output.append(Separator);
  448. return output;
  449. }
  450. /*}}}*/
  451. // URItoFileName - Convert the uri into a unique file name /*{{{*/
  452. // ---------------------------------------------------------------------
  453. /* This converts a URI into a safe filename. It quotes all unsafe characters
  454. and converts / to _ and removes the scheme identifier. The resulting
  455. file name should be unique and never occur again for a different file */
  456. string URItoFileName(const string &URI)
  457. {
  458. // Nuke 'sensitive' items
  459. ::URI U(URI);
  460. U.User.clear();
  461. U.Password.clear();
  462. U.Access.clear();
  463. // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
  464. string NewURI = QuoteString(U,"\\|{}[]<>\"^~_=!@#$%^&*");
  465. replace(NewURI.begin(),NewURI.end(),'/','_');
  466. return NewURI;
  467. }
  468. /*}}}*/
  469. // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
  470. // ---------------------------------------------------------------------
  471. /* This routine performs a base64 transformation on a string. It was ripped
  472. from wget and then patched and bug fixed.
  473. This spec can be found in rfc2045 */
  474. string Base64Encode(const string &S)
  475. {
  476. // Conversion table.
  477. static char tbl[64] = {'A','B','C','D','E','F','G','H',
  478. 'I','J','K','L','M','N','O','P',
  479. 'Q','R','S','T','U','V','W','X',
  480. 'Y','Z','a','b','c','d','e','f',
  481. 'g','h','i','j','k','l','m','n',
  482. 'o','p','q','r','s','t','u','v',
  483. 'w','x','y','z','0','1','2','3',
  484. '4','5','6','7','8','9','+','/'};
  485. // Pre-allocate some space
  486. string Final;
  487. Final.reserve((4*S.length() + 2)/3 + 2);
  488. /* Transform the 3x8 bits to 4x6 bits, as required by
  489. base64. */
  490. for (string::const_iterator I = S.begin(); I < S.end(); I += 3)
  491. {
  492. char Bits[3] = {0,0,0};
  493. Bits[0] = I[0];
  494. if (I + 1 < S.end())
  495. Bits[1] = I[1];
  496. if (I + 2 < S.end())
  497. Bits[2] = I[2];
  498. Final += tbl[Bits[0] >> 2];
  499. Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
  500. if (I + 1 >= S.end())
  501. break;
  502. Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
  503. if (I + 2 >= S.end())
  504. break;
  505. Final += tbl[Bits[2] & 0x3f];
  506. }
  507. /* Apply the padding elements, this tells how many bytes the remote
  508. end should discard */
  509. if (S.length() % 3 == 2)
  510. Final += '=';
  511. if (S.length() % 3 == 1)
  512. Final += "==";
  513. return Final;
  514. }
  515. /*}}}*/
  516. // stringcmp - Arbitrary string compare /*{{{*/
  517. // ---------------------------------------------------------------------
  518. /* This safely compares two non-null terminated strings of arbitrary
  519. length */
  520. int stringcmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  521. {
  522. for (; A != AEnd && B != BEnd; A++, B++)
  523. if (*A != *B)
  524. break;
  525. if (A == AEnd && B == BEnd)
  526. return 0;
  527. if (A == AEnd)
  528. return 1;
  529. if (B == BEnd)
  530. return -1;
  531. if (*A < *B)
  532. return -1;
  533. return 1;
  534. }
  535. #if __GNUC__ >= 3
  536. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  537. const char *B,const char *BEnd)
  538. {
  539. for (; A != AEnd && B != BEnd; A++, B++)
  540. if (*A != *B)
  541. break;
  542. if (A == AEnd && B == BEnd)
  543. return 0;
  544. if (A == AEnd)
  545. return 1;
  546. if (B == BEnd)
  547. return -1;
  548. if (*A < *B)
  549. return -1;
  550. return 1;
  551. }
  552. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  553. string::const_iterator B,string::const_iterator BEnd)
  554. {
  555. for (; A != AEnd && B != BEnd; A++, B++)
  556. if (*A != *B)
  557. break;
  558. if (A == AEnd && B == BEnd)
  559. return 0;
  560. if (A == AEnd)
  561. return 1;
  562. if (B == BEnd)
  563. return -1;
  564. if (*A < *B)
  565. return -1;
  566. return 1;
  567. }
  568. #endif
  569. /*}}}*/
  570. // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
  571. // ---------------------------------------------------------------------
  572. /* */
  573. int stringcasecmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  574. {
  575. for (; A != AEnd && B != BEnd; A++, B++)
  576. if (tolower_ascii(*A) != tolower_ascii(*B))
  577. break;
  578. if (A == AEnd && B == BEnd)
  579. return 0;
  580. if (A == AEnd)
  581. return 1;
  582. if (B == BEnd)
  583. return -1;
  584. if (tolower_ascii(*A) < tolower_ascii(*B))
  585. return -1;
  586. return 1;
  587. }
  588. #if __GNUC__ >= 3
  589. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  590. const char *B,const char *BEnd)
  591. {
  592. for (; A != AEnd && B != BEnd; A++, B++)
  593. if (tolower_ascii(*A) != tolower_ascii(*B))
  594. break;
  595. if (A == AEnd && B == BEnd)
  596. return 0;
  597. if (A == AEnd)
  598. return 1;
  599. if (B == BEnd)
  600. return -1;
  601. if (tolower_ascii(*A) < tolower_ascii(*B))
  602. return -1;
  603. return 1;
  604. }
  605. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  606. string::const_iterator B,string::const_iterator BEnd)
  607. {
  608. for (; A != AEnd && B != BEnd; A++, B++)
  609. if (tolower_ascii(*A) != tolower_ascii(*B))
  610. break;
  611. if (A == AEnd && B == BEnd)
  612. return 0;
  613. if (A == AEnd)
  614. return 1;
  615. if (B == BEnd)
  616. return -1;
  617. if (tolower_ascii(*A) < tolower_ascii(*B))
  618. return -1;
  619. return 1;
  620. }
  621. #endif
  622. /*}}}*/
  623. // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
  624. // ---------------------------------------------------------------------
  625. /* The format is like those used in package files and the method
  626. communication system */
  627. string LookupTag(const string &Message,const char *Tag,const char *Default)
  628. {
  629. // Look for a matching tag.
  630. int Length = strlen(Tag);
  631. for (string::const_iterator I = Message.begin(); I + Length < Message.end(); ++I)
  632. {
  633. // Found the tag
  634. if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
  635. {
  636. // Find the end of line and strip the leading/trailing spaces
  637. string::const_iterator J;
  638. I += Length + 1;
  639. for (; isspace_ascii(*I) != 0 && I < Message.end(); ++I);
  640. for (J = I; *J != '\n' && J < Message.end(); ++J);
  641. for (; J > I && isspace_ascii(J[-1]) != 0; --J);
  642. return string(I,J);
  643. }
  644. for (; *I != '\n' && I < Message.end(); ++I);
  645. }
  646. // Failed to find a match
  647. if (Default == 0)
  648. return string();
  649. return Default;
  650. }
  651. /*}}}*/
  652. // StringToBool - Converts a string into a boolean /*{{{*/
  653. // ---------------------------------------------------------------------
  654. /* This inspects the string to see if it is true or if it is false and
  655. then returns the result. Several varients on true/false are checked. */
  656. int StringToBool(const string &Text,int Default)
  657. {
  658. char *ParseEnd;
  659. int Res = strtol(Text.c_str(),&ParseEnd,0);
  660. // ensure that the entire string was converted by strtol to avoid
  661. // failures on "apt-cache show -a 0ad" where the "0" is converted
  662. const char *TextEnd = Text.c_str()+Text.size();
  663. if (ParseEnd == TextEnd && Res >= 0 && Res <= 1)
  664. return Res;
  665. // Check for positives
  666. if (strcasecmp(Text.c_str(),"no") == 0 ||
  667. strcasecmp(Text.c_str(),"false") == 0 ||
  668. strcasecmp(Text.c_str(),"without") == 0 ||
  669. strcasecmp(Text.c_str(),"off") == 0 ||
  670. strcasecmp(Text.c_str(),"disable") == 0)
  671. return 0;
  672. // Check for negatives
  673. if (strcasecmp(Text.c_str(),"yes") == 0 ||
  674. strcasecmp(Text.c_str(),"true") == 0 ||
  675. strcasecmp(Text.c_str(),"with") == 0 ||
  676. strcasecmp(Text.c_str(),"on") == 0 ||
  677. strcasecmp(Text.c_str(),"enable") == 0)
  678. return 1;
  679. return Default;
  680. }
  681. /*}}}*/
  682. // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
  683. // ---------------------------------------------------------------------
  684. /* This converts a time_t into a string time representation that is
  685. year 2000 complient and timezone neutral */
  686. string TimeRFC1123(time_t Date)
  687. {
  688. return TimeRFC1123(Date, false);
  689. }
  690. string TimeRFC1123(time_t Date, bool const NumericTimezone)
  691. {
  692. struct tm Conv;
  693. if (gmtime_r(&Date, &Conv) == NULL)
  694. return "";
  695. auto const posix = std::locale::classic();
  696. std::ostringstream datestr;
  697. datestr.imbue(posix);
  698. APT::StringView const fmt("%a, %d %b %Y %H:%M:%S");
  699. std::use_facet<std::time_put<char>>(posix).put(
  700. std::ostreambuf_iterator<char>(datestr),
  701. datestr, ' ', &Conv, fmt.data(), fmt.data() + fmt.size());
  702. if (NumericTimezone)
  703. datestr << " +0000";
  704. else
  705. datestr << " GMT";
  706. return datestr.str();
  707. }
  708. /*}}}*/
  709. // ReadMessages - Read messages from the FD /*{{{*/
  710. // ---------------------------------------------------------------------
  711. /* This pulls full messages from the input FD into the message buffer.
  712. It assumes that messages will not pause during transit so no
  713. fancy buffering is used.
  714. In particular: this reads blocks from the input until it believes
  715. that it's run out of input text. Each block is terminated by a
  716. double newline ('\n' followed by '\n').
  717. */
  718. bool ReadMessages(int Fd, vector<string> &List)
  719. {
  720. char Buffer[64000];
  721. // Represents any left-over from the previous iteration of the
  722. // parse loop. (i.e., if a message is split across the end
  723. // of the buffer, it goes here)
  724. string PartialMessage;
  725. do {
  726. int const Res = read(Fd, Buffer, sizeof(Buffer));
  727. if (Res < 0 && errno == EINTR)
  728. continue;
  729. // process we read from has died
  730. if (Res == 0)
  731. return false;
  732. // No data
  733. #if EAGAIN != EWOULDBLOCK
  734. if (Res < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
  735. #else
  736. if (Res < 0 && errno == EAGAIN)
  737. #endif
  738. return true;
  739. if (Res < 0)
  740. return false;
  741. // extract the message(s) from the buffer
  742. char const *Start = Buffer;
  743. char const * const End = Buffer + Res;
  744. char const * NL = (char const *) memchr(Start, '\n', End - Start);
  745. if (NL == NULL)
  746. {
  747. // end of buffer: store what we have so far and read new data in
  748. PartialMessage.append(Start, End - Start);
  749. Start = End;
  750. }
  751. else
  752. ++NL;
  753. if (PartialMessage.empty() == false && Start < End)
  754. {
  755. // if we start with a new line, see if the partial message we have ended with one
  756. // so that we properly detect records ending between two read() runs
  757. // cases are: \n|\n , \r\n|\r\n and \r\n\r|\n
  758. // the case \r|\n\r\n is handled by the usual double-newline handling
  759. if ((NL - Start) == 1 || ((NL - Start) == 2 && *Start == '\r'))
  760. {
  761. if (APT::String::Endswith(PartialMessage, "\n") || APT::String::Endswith(PartialMessage, "\r\n\r"))
  762. {
  763. PartialMessage.erase(PartialMessage.find_last_not_of("\r\n") + 1);
  764. List.push_back(PartialMessage);
  765. PartialMessage.clear();
  766. while (NL < End && (*NL == '\n' || *NL == '\r')) ++NL;
  767. Start = NL;
  768. }
  769. }
  770. }
  771. while (Start < End) {
  772. char const * NL2 = (char const *) memchr(NL, '\n', End - NL);
  773. if (NL2 == NULL)
  774. {
  775. // end of buffer: store what we have so far and read new data in
  776. PartialMessage.append(Start, End - Start);
  777. break;
  778. }
  779. ++NL2;
  780. // did we find a double newline?
  781. if ((NL2 - NL) == 1 || ((NL2 - NL) == 2 && *NL == '\r'))
  782. {
  783. PartialMessage.append(Start, NL2 - Start);
  784. PartialMessage.erase(PartialMessage.find_last_not_of("\r\n") + 1);
  785. List.push_back(PartialMessage);
  786. PartialMessage.clear();
  787. while (NL2 < End && (*NL2 == '\n' || *NL2 == '\r')) ++NL2;
  788. Start = NL2;
  789. }
  790. NL = NL2;
  791. }
  792. // we have read at least one complete message and nothing left
  793. if (PartialMessage.empty() == true)
  794. return true;
  795. if (WaitFd(Fd) == false)
  796. return false;
  797. } while (true);
  798. }
  799. /*}}}*/
  800. // MonthConv - Converts a month string into a number /*{{{*/
  801. // ---------------------------------------------------------------------
  802. /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
  803. Made it a bit more robust with a few tolower_ascii though. */
  804. static int MonthConv(char const * const Month)
  805. {
  806. switch (tolower_ascii(*Month))
  807. {
  808. case 'a':
  809. return tolower_ascii(Month[1]) == 'p'?3:7;
  810. case 'd':
  811. return 11;
  812. case 'f':
  813. return 1;
  814. case 'j':
  815. if (tolower_ascii(Month[1]) == 'a')
  816. return 0;
  817. return tolower_ascii(Month[2]) == 'n'?5:6;
  818. case 'm':
  819. return tolower_ascii(Month[2]) == 'r'?2:4;
  820. case 'n':
  821. return 10;
  822. case 'o':
  823. return 9;
  824. case 's':
  825. return 8;
  826. // Pretend it is January..
  827. default:
  828. return 0;
  829. }
  830. }
  831. /*}}}*/
  832. // timegm - Internal timegm if the gnu version is not available /*{{{*/
  833. // ---------------------------------------------------------------------
  834. /* Converts struct tm to time_t, assuming the data in tm is UTC rather
  835. than local timezone (mktime assumes the latter).
  836. This function is a nonstandard GNU extension that is also present on
  837. the BSDs and maybe other systems. For others we follow the advice of
  838. the manpage of timegm and use his portable replacement. */
  839. #ifndef HAVE_TIMEGM
  840. static time_t timegm(struct tm *t)
  841. {
  842. char *tz = getenv("TZ");
  843. setenv("TZ", "", 1);
  844. tzset();
  845. time_t ret = mktime(t);
  846. if (tz)
  847. setenv("TZ", tz, 1);
  848. else
  849. unsetenv("TZ");
  850. tzset();
  851. return ret;
  852. }
  853. #endif
  854. /*}}}*/
  855. // RFC1123StrToTime - Converts a HTTP1.1 full date strings into a time_t /*{{{*/
  856. // ---------------------------------------------------------------------
  857. /* tries to parses a full date as specified in RFC7231 §7.1.1.1
  858. with one exception: HTTP/1.1 valid dates need to have GMT as timezone.
  859. As we encounter dates from UTC or with a numeric timezone in other places,
  860. we allow them here to to be able to reuse the method. Either way, a date
  861. must be in UTC or parsing will fail. Previous implementations of this
  862. method used to ignore the timezone and assume always UTC. */
  863. bool RFC1123StrToTime(const char* const str,time_t &time)
  864. {
  865. unsigned short day = 0;
  866. signed int year = 0; // yes, Y23K problem – we gonna worry then…
  867. std::string weekday, month, datespec, timespec, zone;
  868. std::istringstream ss(str);
  869. auto const &posix = std::locale::classic();
  870. ss.imbue(posix);
  871. ss >> weekday;
  872. // we only superficially check weekday, mostly to avoid accepting localized
  873. // weekdays here and take only its length to decide which datetime format we
  874. // encounter here. The date isn't stored.
  875. std::transform(weekday.begin(), weekday.end(), weekday.begin(), ::tolower);
  876. std::array<char const * const, 7> c_weekdays = {{ "sun", "mon", "tue", "wed", "thu", "fri", "sat" }};
  877. if (std::find(c_weekdays.begin(), c_weekdays.end(), weekday.substr(0,3)) == c_weekdays.end())
  878. return false;
  879. switch (weekday.length())
  880. {
  881. case 4:
  882. // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
  883. if (weekday[3] != ',')
  884. return false;
  885. ss >> day >> month >> year >> timespec >> zone;
  886. break;
  887. case 3:
  888. // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
  889. ss >> month >> day >> timespec >> year;
  890. zone = "UTC";
  891. break;
  892. case 0:
  893. case 1:
  894. case 2:
  895. return false;
  896. default:
  897. // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
  898. if (weekday[weekday.length() - 1] != ',')
  899. return false;
  900. ss >> datespec >> timespec >> zone;
  901. auto const expldate = VectorizeString(datespec, '-');
  902. if (expldate.size() != 3)
  903. return false;
  904. try {
  905. size_t pos;
  906. day = std::stoi(expldate[0], &pos);
  907. if (pos != expldate[0].length())
  908. return false;
  909. year = 1900 + std::stoi(expldate[2], &pos);
  910. if (pos != expldate[2].length())
  911. return false;
  912. strprintf(datespec, "%.4d-%.2d-%.2d", year, MonthConv(expldate[1].c_str()) + 1, day);
  913. } catch (...) {
  914. return false;
  915. }
  916. break;
  917. }
  918. if (ss.fail() || ss.bad() || !ss.eof())
  919. return false;
  920. if (zone != "GMT" && zone != "UTC" && zone != "Z") // RFC 822
  921. {
  922. // numeric timezones as a should of RFC 1123 and generally preferred
  923. try {
  924. size_t pos;
  925. auto const z = std::stoi(zone, &pos);
  926. if (z != 0 || pos != zone.length())
  927. return false;
  928. } catch (...) {
  929. return false;
  930. }
  931. }
  932. if (datespec.empty())
  933. {
  934. if (month.empty())
  935. return false;
  936. strprintf(datespec, "%.4d-%.2d-%.2d", year, MonthConv(month.c_str()) + 1, day);
  937. }
  938. std::string const datetime = datespec + ' ' + timespec;
  939. struct tm Tm;
  940. if (strptime(datetime.c_str(), "%Y-%m-%d %H:%M:%S", &Tm) == nullptr)
  941. return false;
  942. time = timegm(&Tm);
  943. return true;
  944. }
  945. /*}}}*/
  946. // FTPMDTMStrToTime - Converts a ftp modification date into a time_t /*{{{*/
  947. // ---------------------------------------------------------------------
  948. /* */
  949. bool FTPMDTMStrToTime(const char* const str,time_t &time)
  950. {
  951. struct tm Tm;
  952. // MDTM includes no whitespaces but recommend and ignored by strptime
  953. if (strptime(str, "%Y %m %d %H %M %S", &Tm) == NULL)
  954. return false;
  955. time = timegm(&Tm);
  956. return true;
  957. }
  958. /*}}}*/
  959. // StrToTime - Converts a string into a time_t /*{{{*/
  960. // ---------------------------------------------------------------------
  961. /* This handles all 3 popular time formats including RFC 1123, RFC 1036
  962. and the C library asctime format. It requires the GNU library function
  963. 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
  964. reason the C library does not provide any such function :< This also
  965. handles the weird, but unambiguous FTP time format*/
  966. bool StrToTime(const string &Val,time_t &Result)
  967. {
  968. struct tm Tm;
  969. char Month[10];
  970. // Skip the day of the week
  971. const char *I = strchr(Val.c_str(), ' ');
  972. // Handle RFC 1123 time
  973. Month[0] = 0;
  974. if (sscanf(I," %2d %3s %4d %2d:%2d:%2d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
  975. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  976. {
  977. // Handle RFC 1036 time
  978. if (sscanf(I," %2d-%3s-%3d %2d:%2d:%2d GMT",&Tm.tm_mday,Month,
  979. &Tm.tm_year,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) == 6)
  980. Tm.tm_year += 1900;
  981. else
  982. {
  983. // asctime format
  984. if (sscanf(I," %3s %2d %2d:%2d:%2d %4d",Month,&Tm.tm_mday,
  985. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
  986. {
  987. // 'ftp' time
  988. if (sscanf(Val.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm.tm_year,&Tm.tm_mon,
  989. &Tm.tm_mday,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  990. return false;
  991. Tm.tm_mon--;
  992. }
  993. }
  994. }
  995. Tm.tm_isdst = 0;
  996. if (Month[0] != 0)
  997. Tm.tm_mon = MonthConv(Month);
  998. else
  999. Tm.tm_mon = 0; // we don't have a month, so pick something
  1000. Tm.tm_year -= 1900;
  1001. // Convert to local time and then to GMT
  1002. Result = timegm(&Tm);
  1003. return true;
  1004. }
  1005. /*}}}*/
  1006. // StrToNum - Convert a fixed length string to a number /*{{{*/
  1007. // ---------------------------------------------------------------------
  1008. /* This is used in decoding the crazy fixed length string headers in
  1009. tar and ar files. */
  1010. bool StrToNum(const char *Str,unsigned long &Res,unsigned Len,unsigned Base)
  1011. {
  1012. char S[30];
  1013. if (Len >= sizeof(S))
  1014. return false;
  1015. memcpy(S,Str,Len);
  1016. S[Len] = 0;
  1017. // All spaces is a zero
  1018. Res = 0;
  1019. unsigned I;
  1020. for (I = 0; S[I] == ' '; I++);
  1021. if (S[I] == 0)
  1022. return true;
  1023. char *End;
  1024. Res = strtoul(S,&End,Base);
  1025. if (End == S)
  1026. return false;
  1027. return true;
  1028. }
  1029. /*}}}*/
  1030. // StrToNum - Convert a fixed length string to a number /*{{{*/
  1031. // ---------------------------------------------------------------------
  1032. /* This is used in decoding the crazy fixed length string headers in
  1033. tar and ar files. */
  1034. bool StrToNum(const char *Str,unsigned long long &Res,unsigned Len,unsigned Base)
  1035. {
  1036. char S[30];
  1037. if (Len >= sizeof(S))
  1038. return false;
  1039. memcpy(S,Str,Len);
  1040. S[Len] = 0;
  1041. // All spaces is a zero
  1042. Res = 0;
  1043. unsigned I;
  1044. for (I = 0; S[I] == ' '; I++);
  1045. if (S[I] == 0)
  1046. return true;
  1047. char *End;
  1048. Res = strtoull(S,&End,Base);
  1049. if (End == S)
  1050. return false;
  1051. return true;
  1052. }
  1053. /*}}}*/
  1054. // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
  1055. // ---------------------------------------------------------------------
  1056. /* This is used in decoding the 256bit encoded fixed length fields in
  1057. tar files */
  1058. bool Base256ToNum(const char *Str,unsigned long long &Res,unsigned int Len)
  1059. {
  1060. if ((Str[0] & 0x80) == 0)
  1061. return false;
  1062. else
  1063. {
  1064. Res = Str[0] & 0x7F;
  1065. for(unsigned int i = 1; i < Len; ++i)
  1066. Res = (Res<<8) + Str[i];
  1067. return true;
  1068. }
  1069. }
  1070. /*}}}*/
  1071. // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
  1072. // ---------------------------------------------------------------------
  1073. /* This is used in decoding the 256bit encoded fixed length fields in
  1074. tar files */
  1075. bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len)
  1076. {
  1077. unsigned long long Num = 0;
  1078. bool rc;
  1079. rc = Base256ToNum(Str, Num, Len);
  1080. // rudimentary check for overflow (Res = ulong, Num = ulonglong)
  1081. Res = Num;
  1082. if (Res != Num)
  1083. return false;
  1084. return rc;
  1085. }
  1086. /*}}}*/
  1087. // HexDigit - Convert a hex character into an integer /*{{{*/
  1088. // ---------------------------------------------------------------------
  1089. /* Helper for Hex2Num */
  1090. static int HexDigit(int c)
  1091. {
  1092. if (c >= '0' && c <= '9')
  1093. return c - '0';
  1094. if (c >= 'a' && c <= 'f')
  1095. return c - 'a' + 10;
  1096. if (c >= 'A' && c <= 'F')
  1097. return c - 'A' + 10;
  1098. return -1;
  1099. }
  1100. /*}}}*/
  1101. // Hex2Num - Convert a long hex number into a buffer /*{{{*/
  1102. // ---------------------------------------------------------------------
  1103. /* The length of the buffer must be exactly 1/2 the length of the string. */
  1104. bool Hex2Num(const string &Str,unsigned char *Num,unsigned int Length)
  1105. {
  1106. return Hex2Num(APT::StringView(Str), Num, Length);
  1107. }
  1108. bool Hex2Num(const APT::StringView Str,unsigned char *Num,unsigned int Length)
  1109. {
  1110. if (Str.length() != Length*2)
  1111. return false;
  1112. // Convert each digit. We store it in the same order as the string
  1113. int J = 0;
  1114. for (auto I = Str.begin(); I != Str.end();J++, I += 2)
  1115. {
  1116. int first_half = HexDigit(I[0]);
  1117. int second_half;
  1118. if (first_half < 0)
  1119. return false;
  1120. second_half = HexDigit(I[1]);
  1121. if (second_half < 0)
  1122. return false;
  1123. Num[J] = first_half << 4;
  1124. Num[J] += second_half;
  1125. }
  1126. return true;
  1127. }
  1128. /*}}}*/
  1129. // TokSplitString - Split a string up by a given token /*{{{*/
  1130. // ---------------------------------------------------------------------
  1131. /* This is intended to be a faster splitter, it does not use dynamic
  1132. memories. Input is changed to insert nulls at each token location. */
  1133. bool TokSplitString(char Tok,char *Input,char **List,
  1134. unsigned long ListMax)
  1135. {
  1136. // Strip any leading spaces
  1137. char *Start = Input;
  1138. char *Stop = Start + strlen(Start);
  1139. for (; *Start != 0 && isspace(*Start) != 0; Start++);
  1140. unsigned long Count = 0;
  1141. char *Pos = Start;
  1142. while (Pos != Stop)
  1143. {
  1144. // Skip to the next Token
  1145. for (; Pos != Stop && *Pos != Tok; Pos++);
  1146. // Back remove spaces
  1147. char *End = Pos;
  1148. for (; End > Start && (End[-1] == Tok || isspace(End[-1]) != 0); End--);
  1149. *End = 0;
  1150. List[Count++] = Start;
  1151. if (Count >= ListMax)
  1152. {
  1153. List[Count-1] = 0;
  1154. return false;
  1155. }
  1156. // Advance pos
  1157. for (; Pos != Stop && (*Pos == Tok || isspace(*Pos) != 0 || *Pos == 0); Pos++);
  1158. Start = Pos;
  1159. }
  1160. List[Count] = 0;
  1161. return true;
  1162. }
  1163. /*}}}*/
  1164. // VectorizeString - Split a string up into a vector of strings /*{{{*/
  1165. // ---------------------------------------------------------------------
  1166. /* This can be used to split a given string up into a vector, so the
  1167. propose is the same as in the method above and this one is a bit slower
  1168. also, but the advantage is that we have an iteratable vector */
  1169. vector<string> VectorizeString(string const &haystack, char const &split)
  1170. {
  1171. vector<string> exploded;
  1172. if (haystack.empty() == true)
  1173. return exploded;
  1174. string::const_iterator start = haystack.begin();
  1175. string::const_iterator end = start;
  1176. do {
  1177. for (; end != haystack.end() && *end != split; ++end);
  1178. exploded.push_back(string(start, end));
  1179. start = end + 1;
  1180. } while (end != haystack.end() && (++end) != haystack.end());
  1181. return exploded;
  1182. }
  1183. /*}}}*/
  1184. // StringSplit - split a string into a string vector by token /*{{{*/
  1185. // ---------------------------------------------------------------------
  1186. /* See header for details.
  1187. */
  1188. vector<string> StringSplit(std::string const &s, std::string const &sep,
  1189. unsigned int maxsplit)
  1190. {
  1191. vector<string> split;
  1192. size_t start, pos;
  1193. // no separator given, this is bogus
  1194. if(sep.size() == 0)
  1195. return split;
  1196. start = pos = 0;
  1197. while (pos != string::npos)
  1198. {
  1199. pos = s.find(sep, start);
  1200. split.push_back(s.substr(start, pos-start));
  1201. // if maxsplit is reached, the remaining string is the last item
  1202. if(split.size() >= maxsplit)
  1203. {
  1204. split[split.size()-1] = s.substr(start);
  1205. break;
  1206. }
  1207. start = pos+sep.size();
  1208. }
  1209. return split;
  1210. }
  1211. /*}}}*/
  1212. // RegexChoice - Simple regex list/list matcher /*{{{*/
  1213. // ---------------------------------------------------------------------
  1214. /* */
  1215. unsigned long RegexChoice(RxChoiceList *Rxs,const char **ListBegin,
  1216. const char **ListEnd)
  1217. {
  1218. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  1219. R->Hit = false;
  1220. unsigned long Hits = 0;
  1221. for (; ListBegin < ListEnd; ++ListBegin)
  1222. {
  1223. // Check if the name is a regex
  1224. const char *I;
  1225. bool Regex = true;
  1226. for (I = *ListBegin; *I != 0; I++)
  1227. if (*I == '.' || *I == '?' || *I == '*' || *I == '|')
  1228. break;
  1229. if (*I == 0)
  1230. Regex = false;
  1231. // Compile the regex pattern
  1232. regex_t Pattern;
  1233. if (Regex == true)
  1234. if (regcomp(&Pattern,*ListBegin,REG_EXTENDED | REG_ICASE |
  1235. REG_NOSUB) != 0)
  1236. Regex = false;
  1237. // Search the list
  1238. bool Done = false;
  1239. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  1240. {
  1241. if (R->Str[0] == 0)
  1242. continue;
  1243. if (strcasecmp(R->Str,*ListBegin) != 0)
  1244. {
  1245. if (Regex == false)
  1246. continue;
  1247. if (regexec(&Pattern,R->Str,0,0,0) != 0)
  1248. continue;
  1249. }
  1250. Done = true;
  1251. if (R->Hit == false)
  1252. Hits++;
  1253. R->Hit = true;
  1254. }
  1255. if (Regex == true)
  1256. regfree(&Pattern);
  1257. if (Done == false)
  1258. _error->Warning(_("Selection %s not found"),*ListBegin);
  1259. }
  1260. return Hits;
  1261. }
  1262. /*}}}*/
  1263. // {str,io}printf - C format string outputter to C++ strings/iostreams /*{{{*/
  1264. // ---------------------------------------------------------------------
  1265. /* This is used to make the internationalization strings easier to translate
  1266. and to allow reordering of parameters */
  1267. static bool iovprintf(ostream &out, const char *format,
  1268. va_list &args, ssize_t &size) {
  1269. char *S = (char*)malloc(size);
  1270. ssize_t const n = vsnprintf(S, size, format, args);
  1271. if (n > -1 && n < size) {
  1272. out << S;
  1273. free(S);
  1274. return true;
  1275. } else {
  1276. if (n > -1)
  1277. size = n + 1;
  1278. else
  1279. size *= 2;
  1280. }
  1281. free(S);
  1282. return false;
  1283. }
  1284. void ioprintf(ostream &out,const char *format,...)
  1285. {
  1286. va_list args;
  1287. ssize_t size = 400;
  1288. while (true) {
  1289. bool ret;
  1290. va_start(args,format);
  1291. ret = iovprintf(out, format, args, size);
  1292. va_end(args);
  1293. if (ret == true)
  1294. return;
  1295. }
  1296. }
  1297. void strprintf(string &out,const char *format,...)
  1298. {
  1299. va_list args;
  1300. ssize_t size = 400;
  1301. std::ostringstream outstr;
  1302. while (true) {
  1303. bool ret;
  1304. va_start(args,format);
  1305. ret = iovprintf(outstr, format, args, size);
  1306. va_end(args);
  1307. if (ret == true)
  1308. break;
  1309. }
  1310. out = outstr.str();
  1311. }
  1312. /*}}}*/
  1313. // safe_snprintf - Safer snprintf /*{{{*/
  1314. // ---------------------------------------------------------------------
  1315. /* This is a snprintf that will never (ever) go past 'End' and returns a
  1316. pointer to the end of the new string. The returned string is always null
  1317. terminated unless Buffer == end. This is a better alterantive to using
  1318. consecutive snprintfs. */
  1319. char *safe_snprintf(char *Buffer,char *End,const char *Format,...)
  1320. {
  1321. va_list args;
  1322. int Did;
  1323. if (End <= Buffer)
  1324. return End;
  1325. va_start(args,Format);
  1326. Did = vsnprintf(Buffer,End - Buffer,Format,args);
  1327. va_end(args);
  1328. if (Did < 0 || Buffer + Did > End)
  1329. return End;
  1330. return Buffer + Did;
  1331. }
  1332. /*}}}*/
  1333. // StripEpoch - Remove the version "epoch" from a version string /*{{{*/
  1334. // ---------------------------------------------------------------------
  1335. string StripEpoch(const string &VerStr)
  1336. {
  1337. size_t i = VerStr.find(":");
  1338. if (i == string::npos)
  1339. return VerStr;
  1340. return VerStr.substr(i+1);
  1341. }
  1342. /*}}}*/
  1343. // tolower_ascii - tolower() function that ignores the locale /*{{{*/
  1344. // ---------------------------------------------------------------------
  1345. /* This little function is the most called method we have and tries
  1346. therefore to do the absolut minimum - and is notable faster than
  1347. standard tolower/toupper and as a bonus avoids problems with different
  1348. locales - we only operate on ascii chars anyway. */
  1349. #undef tolower_ascii
  1350. int tolower_ascii(int const c) APT_CONST APT_COLD;
  1351. int tolower_ascii(int const c)
  1352. {
  1353. return tolower_ascii_inline(c);
  1354. }
  1355. /*}}}*/
  1356. // isspace_ascii - isspace() function that ignores the locale /*{{{*/
  1357. // ---------------------------------------------------------------------
  1358. /* This little function is one of the most called methods we have and tries
  1359. therefore to do the absolut minimum - and is notable faster than
  1360. standard isspace() and as a bonus avoids problems with different
  1361. locales - we only operate on ascii chars anyway. */
  1362. #undef isspace_ascii
  1363. int isspace_ascii(int const c) APT_CONST APT_COLD;
  1364. int isspace_ascii(int const c)
  1365. {
  1366. return isspace_ascii_inline(c);
  1367. }
  1368. /*}}}*/
  1369. // CheckDomainList - See if Host is in a , separate list /*{{{*/
  1370. // ---------------------------------------------------------------------
  1371. /* The domain list is a comma separate list of domains that are suffix
  1372. matched against the argument */
  1373. bool CheckDomainList(const string &Host,const string &List)
  1374. {
  1375. string::const_iterator Start = List.begin();
  1376. for (string::const_iterator Cur = List.begin(); Cur <= List.end(); ++Cur)
  1377. {
  1378. if (Cur < List.end() && *Cur != ',')
  1379. continue;
  1380. // Match the end of the string..
  1381. if ((Host.size() >= (unsigned)(Cur - Start)) &&
  1382. Cur - Start != 0 &&
  1383. stringcasecmp(Host.end() - (Cur - Start),Host.end(),Start,Cur) == 0)
  1384. return true;
  1385. Start = Cur + 1;
  1386. }
  1387. return false;
  1388. }
  1389. /*}}}*/
  1390. // strv_length - Return the length of a NULL-terminated string array /*{{{*/
  1391. // ---------------------------------------------------------------------
  1392. /* */
  1393. size_t strv_length(const char **str_array)
  1394. {
  1395. size_t i;
  1396. for (i=0; str_array[i] != NULL; i++)
  1397. /* nothing */
  1398. ;
  1399. return i;
  1400. }
  1401. /*}}}*/
  1402. // DeEscapeString - unescape (\0XX and \xXX) from a string /*{{{*/
  1403. // ---------------------------------------------------------------------
  1404. /* */
  1405. string DeEscapeString(const string &input)
  1406. {
  1407. char tmp[3];
  1408. string::const_iterator it;
  1409. string output;
  1410. for (it = input.begin(); it != input.end(); ++it)
  1411. {
  1412. // just copy non-escape chars
  1413. if (*it != '\\')
  1414. {
  1415. output += *it;
  1416. continue;
  1417. }
  1418. // deal with double escape
  1419. if (*it == '\\' &&
  1420. (it + 1 < input.end()) && it[1] == '\\')
  1421. {
  1422. // copy
  1423. output += *it;
  1424. // advance iterator one step further
  1425. ++it;
  1426. continue;
  1427. }
  1428. // ensure we have a char to read
  1429. if (it + 1 == input.end())
  1430. continue;
  1431. // read it
  1432. ++it;
  1433. switch (*it)
  1434. {
  1435. case '0':
  1436. if (it + 2 <= input.end()) {
  1437. tmp[0] = it[1];
  1438. tmp[1] = it[2];
  1439. tmp[2] = 0;
  1440. output += (char)strtol(tmp, 0, 8);
  1441. it += 2;
  1442. }
  1443. break;
  1444. case 'x':
  1445. if (it + 2 <= input.end()) {
  1446. tmp[0] = it[1];
  1447. tmp[1] = it[2];
  1448. tmp[2] = 0;
  1449. output += (char)strtol(tmp, 0, 16);
  1450. it += 2;
  1451. }
  1452. break;
  1453. default:
  1454. // FIXME: raise exception here?
  1455. break;
  1456. }
  1457. }
  1458. return output;
  1459. }
  1460. /*}}}*/
  1461. // URI::CopyFrom - Copy from an object /*{{{*/
  1462. // ---------------------------------------------------------------------
  1463. /* This parses the URI into all of its components */
  1464. void URI::CopyFrom(const string &U)
  1465. {
  1466. string::const_iterator I = U.begin();
  1467. // Locate the first colon, this separates the scheme
  1468. for (; I < U.end() && *I != ':' ; ++I);
  1469. string::const_iterator FirstColon = I;
  1470. /* Determine if this is a host type URI with a leading double //
  1471. and then search for the first single / */
  1472. string::const_iterator SingleSlash = I;
  1473. if (I + 3 < U.end() && I[1] == '/' && I[2] == '/')
  1474. SingleSlash += 3;
  1475. /* Find the / indicating the end of the hostname, ignoring /'s in the
  1476. square brackets */
  1477. bool InBracket = false;
  1478. for (; SingleSlash < U.end() && (*SingleSlash != '/' || InBracket == true); ++SingleSlash)
  1479. {
  1480. if (*SingleSlash == '[')
  1481. InBracket = true;
  1482. if (InBracket == true && *SingleSlash == ']')
  1483. InBracket = false;
  1484. }
  1485. if (SingleSlash > U.end())
  1486. SingleSlash = U.end();
  1487. // We can now write the access and path specifiers
  1488. Access.assign(U.begin(),FirstColon);
  1489. if (SingleSlash != U.end())
  1490. Path.assign(SingleSlash,U.end());
  1491. if (Path.empty() == true)
  1492. Path = "/";
  1493. // Now we attempt to locate a user:pass@host fragment
  1494. if (FirstColon + 2 <= U.end() && FirstColon[1] == '/' && FirstColon[2] == '/')
  1495. FirstColon += 3;
  1496. else
  1497. FirstColon += 1;
  1498. if (FirstColon >= U.end())
  1499. return;
  1500. if (FirstColon > SingleSlash)
  1501. FirstColon = SingleSlash;
  1502. // Find the colon...
  1503. I = FirstColon + 1;
  1504. if (I > SingleSlash)
  1505. I = SingleSlash;
  1506. // Search for the @ separating user:pass from host
  1507. auto const RevAt = std::find(
  1508. std::string::const_reverse_iterator(SingleSlash),
  1509. std::string::const_reverse_iterator(I), '@');
  1510. string::const_iterator const At = RevAt.base() == I ? SingleSlash : std::prev(RevAt.base());
  1511. // and then look for the colon between user and pass
  1512. string::const_iterator const SecondColon = std::find(I, At, ':');
  1513. // Now write the host and user/pass
  1514. if (At == SingleSlash)
  1515. {
  1516. if (FirstColon < SingleSlash)
  1517. Host.assign(FirstColon,SingleSlash);
  1518. }
  1519. else
  1520. {
  1521. Host.assign(At+1,SingleSlash);
  1522. // username and password must be encoded (RFC 3986)
  1523. User.assign(DeQuoteString(FirstColon,SecondColon));
  1524. if (SecondColon < At)
  1525. Password.assign(DeQuoteString(SecondColon+1,At));
  1526. }
  1527. // Now we parse the RFC 2732 [] hostnames.
  1528. unsigned long PortEnd = 0;
  1529. InBracket = false;
  1530. for (unsigned I = 0; I != Host.length();)
  1531. {
  1532. if (Host[I] == '[')
  1533. {
  1534. InBracket = true;
  1535. Host.erase(I,1);
  1536. continue;
  1537. }
  1538. if (InBracket == true && Host[I] == ']')
  1539. {
  1540. InBracket = false;
  1541. Host.erase(I,1);
  1542. PortEnd = I;
  1543. continue;
  1544. }
  1545. I++;
  1546. }
  1547. // Tsk, weird.
  1548. if (InBracket == true)
  1549. {
  1550. Host.clear();
  1551. return;
  1552. }
  1553. // Now we parse off a port number from the hostname
  1554. Port = 0;
  1555. string::size_type Pos = Host.rfind(':');
  1556. if (Pos == string::npos || Pos < PortEnd)
  1557. return;
  1558. Port = atoi(string(Host,Pos+1).c_str());
  1559. Host.assign(Host,0,Pos);
  1560. }
  1561. /*}}}*/
  1562. // URI::operator string - Convert the URI to a string /*{{{*/
  1563. // ---------------------------------------------------------------------
  1564. /* */
  1565. URI::operator string()
  1566. {
  1567. std::stringstream Res;
  1568. if (Access.empty() == false)
  1569. Res << Access << ':';
  1570. if (Host.empty() == false)
  1571. {
  1572. if (Access.empty() == false)
  1573. Res << "//";
  1574. if (User.empty() == false)
  1575. {
  1576. // FIXME: Technically userinfo is permitted even less
  1577. // characters than these, but this is not conveniently
  1578. // expressed with a blacklist.
  1579. Res << QuoteString(User, ":/?#[]@");
  1580. if (Password.empty() == false)
  1581. Res << ":" << QuoteString(Password, ":/?#[]@");
  1582. Res << "@";
  1583. }
  1584. // Add RFC 2732 escaping characters
  1585. if (Access.empty() == false && Host.find_first_of("/:") != string::npos)
  1586. Res << '[' << Host << ']';
  1587. else
  1588. Res << Host;
  1589. if (Port != 0)
  1590. Res << ':' << std::to_string(Port);
  1591. }
  1592. if (Path.empty() == false)
  1593. {
  1594. if (Path[0] != '/')
  1595. Res << "/" << Path;
  1596. else
  1597. Res << Path;
  1598. }
  1599. return Res.str();
  1600. }
  1601. /*}}}*/
  1602. // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
  1603. string URI::SiteOnly(const string &URI)
  1604. {
  1605. ::URI U(URI);
  1606. U.User.clear();
  1607. U.Password.clear();
  1608. U.Path.clear();
  1609. return U;
  1610. }
  1611. /*}}}*/
  1612. // URI::ArchiveOnly - Return the schema, site and cleaned path for the URI /*{{{*/
  1613. string URI::ArchiveOnly(const string &URI)
  1614. {
  1615. ::URI U(URI);
  1616. U.User.clear();
  1617. U.Password.clear();
  1618. if (U.Path.empty() == false && U.Path[U.Path.length() - 1] == '/')
  1619. U.Path.erase(U.Path.length() - 1);
  1620. return U;
  1621. }
  1622. /*}}}*/
  1623. // URI::NoUserPassword - Return the schema, site and path for the URI /*{{{*/
  1624. string URI::NoUserPassword(const string &URI)
  1625. {
  1626. ::URI U(URI);
  1627. U.User.clear();
  1628. U.Password.clear();
  1629. return U;
  1630. }
  1631. /*}}}*/