strutl.cc 44 KB

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