strutl.cc 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  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. string 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. char Buf[10];
  302. sprintf(Buf,"%%%02x",(int)*I);
  303. Res += Buf;
  304. }
  305. else
  306. Res += *I;
  307. }
  308. return Res;
  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. char S[300];
  349. double ASize;
  350. if (Size >= 0)
  351. ASize = Size;
  352. else
  353. ASize = -1*Size;
  354. /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
  355. ExaBytes, ZettaBytes, YottaBytes */
  356. char Ext[] = {'\0','k','M','G','T','P','E','Z','Y'};
  357. int I = 0;
  358. while (I <= 8)
  359. {
  360. if (ASize < 100 && I != 0)
  361. {
  362. sprintf(S,"%'.1f %c",ASize,Ext[I]);
  363. break;
  364. }
  365. if (ASize < 10000)
  366. {
  367. sprintf(S,"%'.0f %c",ASize,Ext[I]);
  368. break;
  369. }
  370. ASize /= 1000.0;
  371. I++;
  372. }
  373. return S;
  374. }
  375. /*}}}*/
  376. // TimeToStr - Convert the time into a string /*{{{*/
  377. // ---------------------------------------------------------------------
  378. /* Converts a number of seconds to a hms format */
  379. string TimeToStr(unsigned long Sec)
  380. {
  381. char S[300];
  382. while (1)
  383. {
  384. if (Sec > 60*60*24)
  385. {
  386. //d means days, h means hours, min means minutes, s means seconds
  387. sprintf(S,_("%lid %lih %limin %lis"),Sec/60/60/24,(Sec/60/60) % 24,(Sec/60) % 60,Sec % 60);
  388. break;
  389. }
  390. if (Sec > 60*60)
  391. {
  392. //h means hours, min means minutes, s means seconds
  393. sprintf(S,_("%lih %limin %lis"),Sec/60/60,(Sec/60) % 60,Sec % 60);
  394. break;
  395. }
  396. if (Sec > 60)
  397. {
  398. //min means minutes, s means seconds
  399. sprintf(S,_("%limin %lis"),Sec/60,Sec % 60);
  400. break;
  401. }
  402. //s means seconds
  403. sprintf(S,_("%lis"),Sec);
  404. break;
  405. }
  406. return S;
  407. }
  408. /*}}}*/
  409. // SubstVar - Substitute a string for another string /*{{{*/
  410. // ---------------------------------------------------------------------
  411. /* This replaces all occurrences of Subst with Contents in Str. */
  412. string SubstVar(const string &Str,const string &Subst,const string &Contents)
  413. {
  414. if (Subst.empty() == true)
  415. return Str;
  416. string::size_type Pos = 0;
  417. string::size_type OldPos = 0;
  418. string Temp;
  419. while (OldPos < Str.length() &&
  420. (Pos = Str.find(Subst,OldPos)) != string::npos)
  421. {
  422. if (OldPos != Pos)
  423. Temp.append(Str, OldPos, Pos - OldPos);
  424. if (Contents.empty() == false)
  425. Temp.append(Contents);
  426. OldPos = Pos + Subst.length();
  427. }
  428. if (OldPos == 0)
  429. return Str;
  430. if (OldPos >= Str.length())
  431. return Temp;
  432. return Temp + string(Str,OldPos);
  433. }
  434. string SubstVar(string Str,const struct SubstVar *Vars)
  435. {
  436. for (; Vars->Subst != 0; Vars++)
  437. Str = SubstVar(Str,Vars->Subst,*Vars->Contents);
  438. return Str;
  439. }
  440. /*}}}*/
  441. // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
  442. // ---------------------------------------------------------------------
  443. /* Returns a string with the supplied separator depth + 1 times in it */
  444. std::string OutputInDepth(const unsigned long Depth, const char* Separator)
  445. {
  446. std::string output = "";
  447. for(unsigned long d=Depth+1; d > 0; d--)
  448. output.append(Separator);
  449. return output;
  450. }
  451. /*}}}*/
  452. // URItoFileName - Convert the uri into a unique file name /*{{{*/
  453. // ---------------------------------------------------------------------
  454. /* This converts a URI into a safe filename. It quotes all unsafe characters
  455. and converts / to _ and removes the scheme identifier. The resulting
  456. file name should be unique and never occur again for a different file */
  457. string URItoFileName(const string &URI)
  458. {
  459. // Nuke 'sensitive' items
  460. ::URI U(URI);
  461. U.User.clear();
  462. U.Password.clear();
  463. U.Access.clear();
  464. // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
  465. string NewURI = QuoteString(U,"\\|{}[]<>\"^~_=!@#$%^&*");
  466. replace(NewURI.begin(),NewURI.end(),'/','_');
  467. return NewURI;
  468. }
  469. /*}}}*/
  470. // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
  471. // ---------------------------------------------------------------------
  472. /* This routine performs a base64 transformation on a string. It was ripped
  473. from wget and then patched and bug fixed.
  474. This spec can be found in rfc2045 */
  475. string Base64Encode(const string &S)
  476. {
  477. // Conversion table.
  478. static char tbl[64] = {'A','B','C','D','E','F','G','H',
  479. 'I','J','K','L','M','N','O','P',
  480. 'Q','R','S','T','U','V','W','X',
  481. 'Y','Z','a','b','c','d','e','f',
  482. 'g','h','i','j','k','l','m','n',
  483. 'o','p','q','r','s','t','u','v',
  484. 'w','x','y','z','0','1','2','3',
  485. '4','5','6','7','8','9','+','/'};
  486. // Pre-allocate some space
  487. string Final;
  488. Final.reserve((4*S.length() + 2)/3 + 2);
  489. /* Transform the 3x8 bits to 4x6 bits, as required by
  490. base64. */
  491. for (string::const_iterator I = S.begin(); I < S.end(); I += 3)
  492. {
  493. char Bits[3] = {0,0,0};
  494. Bits[0] = I[0];
  495. if (I + 1 < S.end())
  496. Bits[1] = I[1];
  497. if (I + 2 < S.end())
  498. Bits[2] = I[2];
  499. Final += tbl[Bits[0] >> 2];
  500. Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
  501. if (I + 1 >= S.end())
  502. break;
  503. Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
  504. if (I + 2 >= S.end())
  505. break;
  506. Final += tbl[Bits[2] & 0x3f];
  507. }
  508. /* Apply the padding elements, this tells how many bytes the remote
  509. end should discard */
  510. if (S.length() % 3 == 2)
  511. Final += '=';
  512. if (S.length() % 3 == 1)
  513. Final += "==";
  514. return Final;
  515. }
  516. /*}}}*/
  517. // stringcmp - Arbitrary string compare /*{{{*/
  518. // ---------------------------------------------------------------------
  519. /* This safely compares two non-null terminated strings of arbitrary
  520. length */
  521. int stringcmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  522. {
  523. for (; A != AEnd && B != BEnd; A++, B++)
  524. if (*A != *B)
  525. break;
  526. if (A == AEnd && B == BEnd)
  527. return 0;
  528. if (A == AEnd)
  529. return 1;
  530. if (B == BEnd)
  531. return -1;
  532. if (*A < *B)
  533. return -1;
  534. return 1;
  535. }
  536. #if __GNUC__ >= 3
  537. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  538. const char *B,const char *BEnd)
  539. {
  540. for (; A != AEnd && B != BEnd; A++, B++)
  541. if (*A != *B)
  542. break;
  543. if (A == AEnd && B == BEnd)
  544. return 0;
  545. if (A == AEnd)
  546. return 1;
  547. if (B == BEnd)
  548. return -1;
  549. if (*A < *B)
  550. return -1;
  551. return 1;
  552. }
  553. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  554. string::const_iterator B,string::const_iterator BEnd)
  555. {
  556. for (; A != AEnd && B != BEnd; A++, B++)
  557. if (*A != *B)
  558. break;
  559. if (A == AEnd && B == BEnd)
  560. return 0;
  561. if (A == AEnd)
  562. return 1;
  563. if (B == BEnd)
  564. return -1;
  565. if (*A < *B)
  566. return -1;
  567. return 1;
  568. }
  569. #endif
  570. /*}}}*/
  571. // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
  572. // ---------------------------------------------------------------------
  573. /* */
  574. int stringcasecmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  575. {
  576. for (; A != AEnd && B != BEnd; A++, B++)
  577. if (tolower_ascii(*A) != tolower_ascii(*B))
  578. break;
  579. if (A == AEnd && B == BEnd)
  580. return 0;
  581. if (A == AEnd)
  582. return 1;
  583. if (B == BEnd)
  584. return -1;
  585. if (tolower_ascii(*A) < tolower_ascii(*B))
  586. return -1;
  587. return 1;
  588. }
  589. #if __GNUC__ >= 3
  590. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  591. const char *B,const char *BEnd)
  592. {
  593. for (; A != AEnd && B != BEnd; A++, B++)
  594. if (tolower_ascii(*A) != tolower_ascii(*B))
  595. break;
  596. if (A == AEnd && B == BEnd)
  597. return 0;
  598. if (A == AEnd)
  599. return 1;
  600. if (B == BEnd)
  601. return -1;
  602. if (tolower_ascii(*A) < tolower_ascii(*B))
  603. return -1;
  604. return 1;
  605. }
  606. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  607. string::const_iterator B,string::const_iterator BEnd)
  608. {
  609. for (; A != AEnd && B != BEnd; A++, B++)
  610. if (tolower_ascii(*A) != tolower_ascii(*B))
  611. break;
  612. if (A == AEnd && B == BEnd)
  613. return 0;
  614. if (A == AEnd)
  615. return 1;
  616. if (B == BEnd)
  617. return -1;
  618. if (tolower_ascii(*A) < tolower_ascii(*B))
  619. return -1;
  620. return 1;
  621. }
  622. #endif
  623. /*}}}*/
  624. // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
  625. // ---------------------------------------------------------------------
  626. /* The format is like those used in package files and the method
  627. communication system */
  628. string LookupTag(const string &Message,const char *Tag,const char *Default)
  629. {
  630. // Look for a matching tag.
  631. int Length = strlen(Tag);
  632. for (string::const_iterator I = Message.begin(); I + Length < Message.end(); ++I)
  633. {
  634. // Found the tag
  635. if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
  636. {
  637. // Find the end of line and strip the leading/trailing spaces
  638. string::const_iterator J;
  639. I += Length + 1;
  640. for (; isspace(*I) != 0 && I < Message.end(); ++I);
  641. for (J = I; *J != '\n' && J < Message.end(); ++J);
  642. for (; J > I && isspace(J[-1]) != 0; --J);
  643. return string(I,J);
  644. }
  645. for (; *I != '\n' && I < Message.end(); ++I);
  646. }
  647. // Failed to find a match
  648. if (Default == 0)
  649. return string();
  650. return Default;
  651. }
  652. /*}}}*/
  653. // StringToBool - Converts a string into a boolean /*{{{*/
  654. // ---------------------------------------------------------------------
  655. /* This inspects the string to see if it is true or if it is false and
  656. then returns the result. Several varients on true/false are checked. */
  657. int StringToBool(const string &Text,int Default)
  658. {
  659. char *ParseEnd;
  660. int Res = strtol(Text.c_str(),&ParseEnd,0);
  661. // ensure that the entire string was converted by strtol to avoid
  662. // failures on "apt-cache show -a 0ad" where the "0" is converted
  663. const char *TextEnd = Text.c_str()+Text.size();
  664. if (ParseEnd == TextEnd && Res >= 0 && Res <= 1)
  665. return Res;
  666. // Check for positives
  667. if (strcasecmp(Text.c_str(),"no") == 0 ||
  668. strcasecmp(Text.c_str(),"false") == 0 ||
  669. strcasecmp(Text.c_str(),"without") == 0 ||
  670. strcasecmp(Text.c_str(),"off") == 0 ||
  671. strcasecmp(Text.c_str(),"disable") == 0)
  672. return 0;
  673. // Check for negatives
  674. if (strcasecmp(Text.c_str(),"yes") == 0 ||
  675. strcasecmp(Text.c_str(),"true") == 0 ||
  676. strcasecmp(Text.c_str(),"with") == 0 ||
  677. strcasecmp(Text.c_str(),"on") == 0 ||
  678. strcasecmp(Text.c_str(),"enable") == 0)
  679. return 1;
  680. return Default;
  681. }
  682. /*}}}*/
  683. // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
  684. // ---------------------------------------------------------------------
  685. /* This converts a time_t into a string time representation that is
  686. year 2000 complient and timezone neutral */
  687. string TimeRFC1123(time_t Date)
  688. {
  689. struct tm Conv;
  690. if (gmtime_r(&Date, &Conv) == NULL)
  691. return "";
  692. char Buf[300];
  693. const char *Day[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
  694. const char *Month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
  695. "Aug","Sep","Oct","Nov","Dec"};
  696. snprintf(Buf, sizeof(Buf), "%s, %02i %s %i %02i:%02i:%02i GMT",Day[Conv.tm_wday],
  697. Conv.tm_mday,Month[Conv.tm_mon],Conv.tm_year+1900,Conv.tm_hour,
  698. Conv.tm_min,Conv.tm_sec);
  699. return Buf;
  700. }
  701. /*}}}*/
  702. // ReadMessages - Read messages from the FD /*{{{*/
  703. // ---------------------------------------------------------------------
  704. /* This pulls full messages from the input FD into the message buffer.
  705. It assumes that messages will not pause during transit so no
  706. fancy buffering is used.
  707. In particular: this reads blocks from the input until it believes
  708. that it's run out of input text. Each block is terminated by a
  709. double newline ('\n' followed by '\n'). As noted below, there is a
  710. bug in this code: it assumes that all the blocks have been read if
  711. it doesn't see additional text in the buffer after the last one is
  712. parsed, which will cause it to lose blocks if the last block
  713. coincides with the end of the buffer.
  714. */
  715. bool ReadMessages(int Fd, vector<string> &List)
  716. {
  717. char Buffer[64000];
  718. char *End = Buffer;
  719. // Represents any left-over from the previous iteration of the
  720. // parse loop. (i.e., if a message is split across the end
  721. // of the buffer, it goes here)
  722. string PartialMessage;
  723. while (1)
  724. {
  725. int Res = read(Fd,End,sizeof(Buffer) - (End-Buffer));
  726. if (Res < 0 && errno == EINTR)
  727. continue;
  728. // Process is dead, this is kind of bad..
  729. if (Res == 0)
  730. return false;
  731. // No data
  732. if (Res < 0 && errno == EAGAIN)
  733. return true;
  734. if (Res < 0)
  735. return false;
  736. End += Res;
  737. // Look for the end of the message
  738. for (char *I = Buffer; I + 1 < End; I++)
  739. {
  740. if (I[1] != '\n' ||
  741. (I[0] != '\n' && strncmp(I, "\r\n\r\n", 4) != 0))
  742. continue;
  743. // Pull the message out
  744. string Message(Buffer,I-Buffer);
  745. PartialMessage += Message;
  746. // Fix up the buffer
  747. for (; I < End && (*I == '\n' || *I == '\r'); ++I);
  748. End -= I-Buffer;
  749. memmove(Buffer,I,End-Buffer);
  750. I = Buffer;
  751. List.push_back(PartialMessage);
  752. PartialMessage.clear();
  753. }
  754. if (End != Buffer)
  755. {
  756. // If there's text left in the buffer, store it
  757. // in PartialMessage and throw the rest of the buffer
  758. // away. This allows us to handle messages that
  759. // are longer than the static buffer size.
  760. PartialMessage += string(Buffer, End);
  761. End = Buffer;
  762. }
  763. else
  764. {
  765. // BUG ALERT: if a message block happens to end at a
  766. // multiple of 64000 characters, this will cause it to
  767. // terminate early, leading to a badly formed block and
  768. // probably crashing the method. However, this is the only
  769. // way we have to find the end of the message block. I have
  770. // an idea of how to fix this, but it will require changes
  771. // to the protocol (essentially to mark the beginning and
  772. // end of the block).
  773. //
  774. // -- dburrows 2008-04-02
  775. return true;
  776. }
  777. if (WaitFd(Fd) == false)
  778. return false;
  779. }
  780. }
  781. /*}}}*/
  782. // MonthConv - Converts a month string into a number /*{{{*/
  783. // ---------------------------------------------------------------------
  784. /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
  785. Made it a bit more robust with a few tolower_ascii though. */
  786. static int MonthConv(char *Month)
  787. {
  788. switch (tolower_ascii(*Month))
  789. {
  790. case 'a':
  791. return tolower_ascii(Month[1]) == 'p'?3:7;
  792. case 'd':
  793. return 11;
  794. case 'f':
  795. return 1;
  796. case 'j':
  797. if (tolower_ascii(Month[1]) == 'a')
  798. return 0;
  799. return tolower_ascii(Month[2]) == 'n'?5:6;
  800. case 'm':
  801. return tolower_ascii(Month[2]) == 'r'?2:4;
  802. case 'n':
  803. return 10;
  804. case 'o':
  805. return 9;
  806. case 's':
  807. return 8;
  808. // Pretend it is January..
  809. default:
  810. return 0;
  811. }
  812. }
  813. /*}}}*/
  814. // timegm - Internal timegm if the gnu version is not available /*{{{*/
  815. // ---------------------------------------------------------------------
  816. /* Converts struct tm to time_t, assuming the data in tm is UTC rather
  817. than local timezone (mktime assumes the latter).
  818. This function is a nonstandard GNU extension that is also present on
  819. the BSDs and maybe other systems. For others we follow the advice of
  820. the manpage of timegm and use his portable replacement. */
  821. #ifndef HAVE_TIMEGM
  822. static time_t timegm(struct tm *t)
  823. {
  824. char *tz = getenv("TZ");
  825. setenv("TZ", "", 1);
  826. tzset();
  827. time_t ret = mktime(t);
  828. if (tz)
  829. setenv("TZ", tz, 1);
  830. else
  831. unsetenv("TZ");
  832. tzset();
  833. return ret;
  834. }
  835. #endif
  836. /*}}}*/
  837. // FullDateToTime - Converts a HTTP1.1 full date strings into a time_t /*{{{*/
  838. // ---------------------------------------------------------------------
  839. /* tries to parses a full date as specified in RFC2616 Section 3.3.1
  840. with one exception: All timezones (%Z) are accepted but the protocol
  841. says that it MUST be GMT, but this one is equal to UTC which we will
  842. encounter from time to time (e.g. in Release files) so we accept all
  843. here and just assume it is GMT (or UTC) later on */
  844. bool RFC1123StrToTime(const char* const str,time_t &time)
  845. {
  846. struct tm Tm;
  847. setlocale (LC_ALL,"C");
  848. bool const invalid =
  849. // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
  850. (strptime(str, "%a, %d %b %Y %H:%M:%S %Z", &Tm) == NULL &&
  851. // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
  852. strptime(str, "%A, %d-%b-%y %H:%M:%S %Z", &Tm) == NULL &&
  853. // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
  854. strptime(str, "%a %b %d %H:%M:%S %Y", &Tm) == NULL);
  855. setlocale (LC_ALL,"");
  856. if (invalid == true)
  857. return false;
  858. time = timegm(&Tm);
  859. return true;
  860. }
  861. /*}}}*/
  862. // FTPMDTMStrToTime - Converts a ftp modification date into a time_t /*{{{*/
  863. // ---------------------------------------------------------------------
  864. /* */
  865. bool FTPMDTMStrToTime(const char* const str,time_t &time)
  866. {
  867. struct tm Tm;
  868. // MDTM includes no whitespaces but recommend and ignored by strptime
  869. if (strptime(str, "%Y %m %d %H %M %S", &Tm) == NULL)
  870. return false;
  871. time = timegm(&Tm);
  872. return true;
  873. }
  874. /*}}}*/
  875. // StrToTime - Converts a string into a time_t /*{{{*/
  876. // ---------------------------------------------------------------------
  877. /* This handles all 3 popular time formats including RFC 1123, RFC 1036
  878. and the C library asctime format. It requires the GNU library function
  879. 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
  880. reason the C library does not provide any such function :< This also
  881. handles the weird, but unambiguous FTP time format*/
  882. bool StrToTime(const string &Val,time_t &Result)
  883. {
  884. struct tm Tm;
  885. char Month[10];
  886. // Skip the day of the week
  887. const char *I = strchr(Val.c_str(), ' ');
  888. // Handle RFC 1123 time
  889. Month[0] = 0;
  890. if (sscanf(I," %2d %3s %4d %2d:%2d:%2d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
  891. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  892. {
  893. // Handle RFC 1036 time
  894. if (sscanf(I," %2d-%3s-%3d %2d:%2d:%2d GMT",&Tm.tm_mday,Month,
  895. &Tm.tm_year,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) == 6)
  896. Tm.tm_year += 1900;
  897. else
  898. {
  899. // asctime format
  900. if (sscanf(I," %3s %2d %2d:%2d:%2d %4d",Month,&Tm.tm_mday,
  901. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
  902. {
  903. // 'ftp' time
  904. if (sscanf(Val.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm.tm_year,&Tm.tm_mon,
  905. &Tm.tm_mday,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  906. return false;
  907. Tm.tm_mon--;
  908. }
  909. }
  910. }
  911. Tm.tm_isdst = 0;
  912. if (Month[0] != 0)
  913. Tm.tm_mon = MonthConv(Month);
  914. else
  915. Tm.tm_mon = 0; // we don't have a month, so pick something
  916. Tm.tm_year -= 1900;
  917. // Convert to local time and then to GMT
  918. Result = timegm(&Tm);
  919. return true;
  920. }
  921. /*}}}*/
  922. // StrToNum - Convert a fixed length string to a number /*{{{*/
  923. // ---------------------------------------------------------------------
  924. /* This is used in decoding the crazy fixed length string headers in
  925. tar and ar files. */
  926. bool StrToNum(const char *Str,unsigned long &Res,unsigned Len,unsigned Base)
  927. {
  928. char S[30];
  929. if (Len >= sizeof(S))
  930. return false;
  931. memcpy(S,Str,Len);
  932. S[Len] = 0;
  933. // All spaces is a zero
  934. Res = 0;
  935. unsigned I;
  936. for (I = 0; S[I] == ' '; I++);
  937. if (S[I] == 0)
  938. return true;
  939. char *End;
  940. Res = strtoul(S,&End,Base);
  941. if (End == S)
  942. return false;
  943. return true;
  944. }
  945. /*}}}*/
  946. // StrToNum - Convert a fixed length string to a number /*{{{*/
  947. // ---------------------------------------------------------------------
  948. /* This is used in decoding the crazy fixed length string headers in
  949. tar and ar files. */
  950. bool StrToNum(const char *Str,unsigned long long &Res,unsigned Len,unsigned Base)
  951. {
  952. char S[30];
  953. if (Len >= sizeof(S))
  954. return false;
  955. memcpy(S,Str,Len);
  956. S[Len] = 0;
  957. // All spaces is a zero
  958. Res = 0;
  959. unsigned I;
  960. for (I = 0; S[I] == ' '; I++);
  961. if (S[I] == 0)
  962. return true;
  963. char *End;
  964. Res = strtoull(S,&End,Base);
  965. if (End == S)
  966. return false;
  967. return true;
  968. }
  969. /*}}}*/
  970. // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
  971. // ---------------------------------------------------------------------
  972. /* This is used in decoding the 256bit encoded fixed length fields in
  973. tar files */
  974. bool Base256ToNum(const char *Str,unsigned long long &Res,unsigned int Len)
  975. {
  976. if ((Str[0] & 0x80) == 0)
  977. return false;
  978. else
  979. {
  980. Res = Str[0] & 0x7F;
  981. for(unsigned int i = 1; i < Len; ++i)
  982. Res = (Res<<8) + Str[i];
  983. return true;
  984. }
  985. }
  986. /*}}}*/
  987. // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
  988. // ---------------------------------------------------------------------
  989. /* This is used in decoding the 256bit encoded fixed length fields in
  990. tar files */
  991. bool Base256ToNum(const char *Str,unsigned long &Res,unsigned int Len)
  992. {
  993. unsigned long long Num;
  994. bool rc;
  995. rc = Base256ToNum(Str, Num, Len);
  996. Res = Num;
  997. if (Res != Num)
  998. return false;
  999. return rc;
  1000. }
  1001. /*}}}*/
  1002. // HexDigit - Convert a hex character into an integer /*{{{*/
  1003. // ---------------------------------------------------------------------
  1004. /* Helper for Hex2Num */
  1005. static int HexDigit(int c)
  1006. {
  1007. if (c >= '0' && c <= '9')
  1008. return c - '0';
  1009. if (c >= 'a' && c <= 'f')
  1010. return c - 'a' + 10;
  1011. if (c >= 'A' && c <= 'F')
  1012. return c - 'A' + 10;
  1013. return 0;
  1014. }
  1015. /*}}}*/
  1016. // Hex2Num - Convert a long hex number into a buffer /*{{{*/
  1017. // ---------------------------------------------------------------------
  1018. /* The length of the buffer must be exactly 1/2 the length of the string. */
  1019. bool Hex2Num(const string &Str,unsigned char *Num,unsigned int Length)
  1020. {
  1021. if (Str.length() != Length*2)
  1022. return false;
  1023. // Convert each digit. We store it in the same order as the string
  1024. int J = 0;
  1025. for (string::const_iterator I = Str.begin(); I != Str.end();J++, I += 2)
  1026. {
  1027. if (isxdigit(*I) == 0 || isxdigit(I[1]) == 0)
  1028. return false;
  1029. Num[J] = HexDigit(I[0]) << 4;
  1030. Num[J] += HexDigit(I[1]);
  1031. }
  1032. return true;
  1033. }
  1034. /*}}}*/
  1035. // TokSplitString - Split a string up by a given token /*{{{*/
  1036. // ---------------------------------------------------------------------
  1037. /* This is intended to be a faster splitter, it does not use dynamic
  1038. memories. Input is changed to insert nulls at each token location. */
  1039. bool TokSplitString(char Tok,char *Input,char **List,
  1040. unsigned long ListMax)
  1041. {
  1042. // Strip any leading spaces
  1043. char *Start = Input;
  1044. char *Stop = Start + strlen(Start);
  1045. for (; *Start != 0 && isspace(*Start) != 0; Start++);
  1046. unsigned long Count = 0;
  1047. char *Pos = Start;
  1048. while (Pos != Stop)
  1049. {
  1050. // Skip to the next Token
  1051. for (; Pos != Stop && *Pos != Tok; Pos++);
  1052. // Back remove spaces
  1053. char *End = Pos;
  1054. for (; End > Start && (End[-1] == Tok || isspace(End[-1]) != 0); End--);
  1055. *End = 0;
  1056. List[Count++] = Start;
  1057. if (Count >= ListMax)
  1058. {
  1059. List[Count-1] = 0;
  1060. return false;
  1061. }
  1062. // Advance pos
  1063. for (; Pos != Stop && (*Pos == Tok || isspace(*Pos) != 0 || *Pos == 0); Pos++);
  1064. Start = Pos;
  1065. }
  1066. List[Count] = 0;
  1067. return true;
  1068. }
  1069. /*}}}*/
  1070. // VectorizeString - Split a string up into a vector of strings /*{{{*/
  1071. // ---------------------------------------------------------------------
  1072. /* This can be used to split a given string up into a vector, so the
  1073. propose is the same as in the method above and this one is a bit slower
  1074. also, but the advantage is that we have an iteratable vector */
  1075. vector<string> VectorizeString(string const &haystack, char const &split)
  1076. {
  1077. vector<string> exploded;
  1078. if (haystack.empty() == true)
  1079. return exploded;
  1080. string::const_iterator start = haystack.begin();
  1081. string::const_iterator end = start;
  1082. do {
  1083. for (; end != haystack.end() && *end != split; ++end);
  1084. exploded.push_back(string(start, end));
  1085. start = end + 1;
  1086. } while (end != haystack.end() && (++end) != haystack.end());
  1087. return exploded;
  1088. }
  1089. /*}}}*/
  1090. // StringSplit - split a string into a string vector by token /*{{{*/
  1091. // ---------------------------------------------------------------------
  1092. /* See header for details.
  1093. */
  1094. vector<string> StringSplit(std::string const &s, std::string const &sep,
  1095. unsigned int maxsplit)
  1096. {
  1097. vector<string> split;
  1098. size_t start, pos;
  1099. // no seperator given, this is bogus
  1100. if(sep.size() == 0)
  1101. return split;
  1102. start = pos = 0;
  1103. while (pos != string::npos)
  1104. {
  1105. pos = s.find(sep, start);
  1106. split.push_back(s.substr(start, pos-start));
  1107. // if maxsplit is reached, the remaining string is the last item
  1108. if(split.size() >= maxsplit)
  1109. {
  1110. split[split.size()-1] = s.substr(start);
  1111. break;
  1112. }
  1113. start = pos+sep.size();
  1114. }
  1115. return split;
  1116. }
  1117. /*}}}*/
  1118. // RegexChoice - Simple regex list/list matcher /*{{{*/
  1119. // ---------------------------------------------------------------------
  1120. /* */
  1121. unsigned long RegexChoice(RxChoiceList *Rxs,const char **ListBegin,
  1122. const char **ListEnd)
  1123. {
  1124. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  1125. R->Hit = false;
  1126. unsigned long Hits = 0;
  1127. for (; ListBegin < ListEnd; ++ListBegin)
  1128. {
  1129. // Check if the name is a regex
  1130. const char *I;
  1131. bool Regex = true;
  1132. for (I = *ListBegin; *I != 0; I++)
  1133. if (*I == '.' || *I == '?' || *I == '*' || *I == '|')
  1134. break;
  1135. if (*I == 0)
  1136. Regex = false;
  1137. // Compile the regex pattern
  1138. regex_t Pattern;
  1139. if (Regex == true)
  1140. if (regcomp(&Pattern,*ListBegin,REG_EXTENDED | REG_ICASE |
  1141. REG_NOSUB) != 0)
  1142. Regex = false;
  1143. // Search the list
  1144. bool Done = false;
  1145. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  1146. {
  1147. if (R->Str[0] == 0)
  1148. continue;
  1149. if (strcasecmp(R->Str,*ListBegin) != 0)
  1150. {
  1151. if (Regex == false)
  1152. continue;
  1153. if (regexec(&Pattern,R->Str,0,0,0) != 0)
  1154. continue;
  1155. }
  1156. Done = true;
  1157. if (R->Hit == false)
  1158. Hits++;
  1159. R->Hit = true;
  1160. }
  1161. if (Regex == true)
  1162. regfree(&Pattern);
  1163. if (Done == false)
  1164. _error->Warning(_("Selection %s not found"),*ListBegin);
  1165. }
  1166. return Hits;
  1167. }
  1168. /*}}}*/
  1169. // {str,io}printf - C format string outputter to C++ strings/iostreams /*{{{*/
  1170. // ---------------------------------------------------------------------
  1171. /* This is used to make the internationalization strings easier to translate
  1172. and to allow reordering of parameters */
  1173. static bool iovprintf(ostream &out, const char *format,
  1174. va_list &args, ssize_t &size) {
  1175. char *S = (char*)malloc(size);
  1176. ssize_t const n = vsnprintf(S, size, format, args);
  1177. if (n > -1 && n < size) {
  1178. out << S;
  1179. free(S);
  1180. return true;
  1181. } else {
  1182. if (n > -1)
  1183. size = n + 1;
  1184. else
  1185. size *= 2;
  1186. }
  1187. free(S);
  1188. return false;
  1189. }
  1190. void ioprintf(ostream &out,const char *format,...)
  1191. {
  1192. va_list args;
  1193. ssize_t size = 400;
  1194. while (true) {
  1195. va_start(args,format);
  1196. if (iovprintf(out, format, args, size) == true)
  1197. return;
  1198. va_end(args);
  1199. }
  1200. }
  1201. void strprintf(string &out,const char *format,...)
  1202. {
  1203. va_list args;
  1204. ssize_t size = 400;
  1205. std::ostringstream outstr;
  1206. while (true) {
  1207. va_start(args,format);
  1208. if (iovprintf(outstr, format, args, size) == true)
  1209. break;
  1210. va_end(args);
  1211. }
  1212. out = outstr.str();
  1213. }
  1214. /*}}}*/
  1215. // safe_snprintf - Safer snprintf /*{{{*/
  1216. // ---------------------------------------------------------------------
  1217. /* This is a snprintf that will never (ever) go past 'End' and returns a
  1218. pointer to the end of the new string. The returned string is always null
  1219. terminated unless Buffer == end. This is a better alterantive to using
  1220. consecutive snprintfs. */
  1221. char *safe_snprintf(char *Buffer,char *End,const char *Format,...)
  1222. {
  1223. va_list args;
  1224. int Did;
  1225. if (End <= Buffer)
  1226. return End;
  1227. va_start(args,Format);
  1228. Did = vsnprintf(Buffer,End - Buffer,Format,args);
  1229. va_end(args);
  1230. if (Did < 0 || Buffer + Did > End)
  1231. return End;
  1232. return Buffer + Did;
  1233. }
  1234. /*}}}*/
  1235. // StripEpoch - Remove the version "epoch" from a version string /*{{{*/
  1236. // ---------------------------------------------------------------------
  1237. string StripEpoch(const string &VerStr)
  1238. {
  1239. size_t i = VerStr.find(":");
  1240. if (i == string::npos)
  1241. return VerStr;
  1242. return VerStr.substr(i+1);
  1243. }
  1244. /*}}}*/
  1245. // tolower_ascii - tolower() function that ignores the locale /*{{{*/
  1246. // ---------------------------------------------------------------------
  1247. /* This little function is the most called method we have and tries
  1248. therefore to do the absolut minimum - and is notable faster than
  1249. standard tolower/toupper and as a bonus avoids problems with different
  1250. locales - we only operate on ascii chars anyway. */
  1251. int tolower_ascii(int const c)
  1252. {
  1253. if (c >= 'A' && c <= 'Z')
  1254. return c + 32;
  1255. return c;
  1256. }
  1257. /*}}}*/
  1258. // CheckDomainList - See if Host is in a , separate list /*{{{*/
  1259. // ---------------------------------------------------------------------
  1260. /* The domain list is a comma separate list of domains that are suffix
  1261. matched against the argument */
  1262. bool CheckDomainList(const string &Host,const string &List)
  1263. {
  1264. string::const_iterator Start = List.begin();
  1265. for (string::const_iterator Cur = List.begin(); Cur <= List.end(); ++Cur)
  1266. {
  1267. if (Cur < List.end() && *Cur != ',')
  1268. continue;
  1269. // Match the end of the string..
  1270. if ((Host.size() >= (unsigned)(Cur - Start)) &&
  1271. Cur - Start != 0 &&
  1272. stringcasecmp(Host.end() - (Cur - Start),Host.end(),Start,Cur) == 0)
  1273. return true;
  1274. Start = Cur + 1;
  1275. }
  1276. return false;
  1277. }
  1278. /*}}}*/
  1279. // strv_length - Return the length of a NULL-terminated string array /*{{{*/
  1280. // ---------------------------------------------------------------------
  1281. /* */
  1282. size_t strv_length(const char **str_array)
  1283. {
  1284. size_t i;
  1285. for (i=0; str_array[i] != NULL; i++)
  1286. /* nothing */
  1287. ;
  1288. return i;
  1289. }
  1290. // DeEscapeString - unescape (\0XX and \xXX) from a string /*{{{*/
  1291. // ---------------------------------------------------------------------
  1292. /* */
  1293. string DeEscapeString(const string &input)
  1294. {
  1295. char tmp[3];
  1296. string::const_iterator it;
  1297. string output;
  1298. for (it = input.begin(); it != input.end(); ++it)
  1299. {
  1300. // just copy non-escape chars
  1301. if (*it != '\\')
  1302. {
  1303. output += *it;
  1304. continue;
  1305. }
  1306. // deal with double escape
  1307. if (*it == '\\' &&
  1308. (it + 1 < input.end()) && it[1] == '\\')
  1309. {
  1310. // copy
  1311. output += *it;
  1312. // advance iterator one step further
  1313. ++it;
  1314. continue;
  1315. }
  1316. // ensure we have a char to read
  1317. if (it + 1 == input.end())
  1318. continue;
  1319. // read it
  1320. ++it;
  1321. switch (*it)
  1322. {
  1323. case '0':
  1324. if (it + 2 <= input.end()) {
  1325. tmp[0] = it[1];
  1326. tmp[1] = it[2];
  1327. tmp[2] = 0;
  1328. output += (char)strtol(tmp, 0, 8);
  1329. it += 2;
  1330. }
  1331. break;
  1332. case 'x':
  1333. if (it + 2 <= input.end()) {
  1334. tmp[0] = it[1];
  1335. tmp[1] = it[2];
  1336. tmp[2] = 0;
  1337. output += (char)strtol(tmp, 0, 16);
  1338. it += 2;
  1339. }
  1340. break;
  1341. default:
  1342. // FIXME: raise exception here?
  1343. break;
  1344. }
  1345. }
  1346. return output;
  1347. }
  1348. /*}}}*/
  1349. // URI::CopyFrom - Copy from an object /*{{{*/
  1350. // ---------------------------------------------------------------------
  1351. /* This parses the URI into all of its components */
  1352. void URI::CopyFrom(const string &U)
  1353. {
  1354. string::const_iterator I = U.begin();
  1355. // Locate the first colon, this separates the scheme
  1356. for (; I < U.end() && *I != ':' ; ++I);
  1357. string::const_iterator FirstColon = I;
  1358. /* Determine if this is a host type URI with a leading double //
  1359. and then search for the first single / */
  1360. string::const_iterator SingleSlash = I;
  1361. if (I + 3 < U.end() && I[1] == '/' && I[2] == '/')
  1362. SingleSlash += 3;
  1363. /* Find the / indicating the end of the hostname, ignoring /'s in the
  1364. square brackets */
  1365. bool InBracket = false;
  1366. for (; SingleSlash < U.end() && (*SingleSlash != '/' || InBracket == true); ++SingleSlash)
  1367. {
  1368. if (*SingleSlash == '[')
  1369. InBracket = true;
  1370. if (InBracket == true && *SingleSlash == ']')
  1371. InBracket = false;
  1372. }
  1373. if (SingleSlash > U.end())
  1374. SingleSlash = U.end();
  1375. // We can now write the access and path specifiers
  1376. Access.assign(U.begin(),FirstColon);
  1377. if (SingleSlash != U.end())
  1378. Path.assign(SingleSlash,U.end());
  1379. if (Path.empty() == true)
  1380. Path = "/";
  1381. // Now we attempt to locate a user:pass@host fragment
  1382. if (FirstColon + 2 <= U.end() && FirstColon[1] == '/' && FirstColon[2] == '/')
  1383. FirstColon += 3;
  1384. else
  1385. FirstColon += 1;
  1386. if (FirstColon >= U.end())
  1387. return;
  1388. if (FirstColon > SingleSlash)
  1389. FirstColon = SingleSlash;
  1390. // Find the colon...
  1391. I = FirstColon + 1;
  1392. if (I > SingleSlash)
  1393. I = SingleSlash;
  1394. for (; I < SingleSlash && *I != ':'; ++I);
  1395. string::const_iterator SecondColon = I;
  1396. // Search for the @ after the colon
  1397. for (; I < SingleSlash && *I != '@'; ++I);
  1398. string::const_iterator At = I;
  1399. // Now write the host and user/pass
  1400. if (At == SingleSlash)
  1401. {
  1402. if (FirstColon < SingleSlash)
  1403. Host.assign(FirstColon,SingleSlash);
  1404. }
  1405. else
  1406. {
  1407. Host.assign(At+1,SingleSlash);
  1408. // username and password must be encoded (RFC 3986)
  1409. User.assign(DeQuoteString(FirstColon,SecondColon));
  1410. if (SecondColon < At)
  1411. Password.assign(DeQuoteString(SecondColon+1,At));
  1412. }
  1413. // Now we parse the RFC 2732 [] hostnames.
  1414. unsigned long PortEnd = 0;
  1415. InBracket = false;
  1416. for (unsigned I = 0; I != Host.length();)
  1417. {
  1418. if (Host[I] == '[')
  1419. {
  1420. InBracket = true;
  1421. Host.erase(I,1);
  1422. continue;
  1423. }
  1424. if (InBracket == true && Host[I] == ']')
  1425. {
  1426. InBracket = false;
  1427. Host.erase(I,1);
  1428. PortEnd = I;
  1429. continue;
  1430. }
  1431. I++;
  1432. }
  1433. // Tsk, weird.
  1434. if (InBracket == true)
  1435. {
  1436. Host.clear();
  1437. return;
  1438. }
  1439. // Now we parse off a port number from the hostname
  1440. Port = 0;
  1441. string::size_type Pos = Host.rfind(':');
  1442. if (Pos == string::npos || Pos < PortEnd)
  1443. return;
  1444. Port = atoi(string(Host,Pos+1).c_str());
  1445. Host.assign(Host,0,Pos);
  1446. }
  1447. /*}}}*/
  1448. // URI::operator string - Convert the URI to a string /*{{{*/
  1449. // ---------------------------------------------------------------------
  1450. /* */
  1451. URI::operator string()
  1452. {
  1453. string Res;
  1454. if (Access.empty() == false)
  1455. Res = Access + ':';
  1456. if (Host.empty() == false)
  1457. {
  1458. if (Access.empty() == false)
  1459. Res += "//";
  1460. if (User.empty() == false)
  1461. {
  1462. // FIXME: Technically userinfo is permitted even less
  1463. // characters than these, but this is not conveniently
  1464. // expressed with a blacklist.
  1465. Res += QuoteString(User, ":/?#[]@");
  1466. if (Password.empty() == false)
  1467. Res += ":" + QuoteString(Password, ":/?#[]@");
  1468. Res += "@";
  1469. }
  1470. // Add RFC 2732 escaping characters
  1471. if (Access.empty() == false &&
  1472. (Host.find('/') != string::npos || Host.find(':') != string::npos))
  1473. Res += '[' + Host + ']';
  1474. else
  1475. Res += Host;
  1476. if (Port != 0)
  1477. {
  1478. char S[30];
  1479. sprintf(S,":%u",Port);
  1480. Res += S;
  1481. }
  1482. }
  1483. if (Path.empty() == false)
  1484. {
  1485. if (Path[0] != '/')
  1486. Res += "/" + Path;
  1487. else
  1488. Res += Path;
  1489. }
  1490. return Res;
  1491. }
  1492. /*}}}*/
  1493. // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
  1494. // ---------------------------------------------------------------------
  1495. /* */
  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::NoUserPassword - Return the schema, site and path for the URI /*{{{*/
  1506. // ---------------------------------------------------------------------
  1507. /* */
  1508. string URI::NoUserPassword(const string &URI)
  1509. {
  1510. ::URI U(URI);
  1511. U.User.clear();
  1512. U.Password.clear();
  1513. return U;
  1514. }
  1515. /*}}}*/