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.
 
 
 
 
 
 

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