strutl.cc 49 KB

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