strutl.cc 42 KB

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