strutl.cc 45 KB

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