strutl.cc 32 KB

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