You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1700 lines
46 KiB

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