strutl.cc 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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(const string &Str, const char *Bad)
  216. {
  217. string Res;
  218. for (string::const_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(const 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(const string &Str,const string &Subst,const 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(const string &URI)
  352. {
  353. // Nuke 'sensitive' items
  354. ::URI U(URI);
  355. U.User.clear();
  356. U.Password.clear();
  357. U.Access.clear();
  358. // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
  359. string NewURI = QuoteString(U,"\\|{}[]<>\"^~_=!@#$%^&*");
  360. replace(NewURI.begin(),NewURI.end(),'/','_');
  361. return NewURI;
  362. }
  363. /*}}}*/
  364. // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
  365. // ---------------------------------------------------------------------
  366. /* This routine performs a base64 transformation on a string. It was ripped
  367. from wget and then patched and bug fixed.
  368. This spec can be found in rfc2045 */
  369. string Base64Encode(const string &S)
  370. {
  371. // Conversion table.
  372. static char tbl[64] = {'A','B','C','D','E','F','G','H',
  373. 'I','J','K','L','M','N','O','P',
  374. 'Q','R','S','T','U','V','W','X',
  375. 'Y','Z','a','b','c','d','e','f',
  376. 'g','h','i','j','k','l','m','n',
  377. 'o','p','q','r','s','t','u','v',
  378. 'w','x','y','z','0','1','2','3',
  379. '4','5','6','7','8','9','+','/'};
  380. // Pre-allocate some space
  381. string Final;
  382. Final.reserve((4*S.length() + 2)/3 + 2);
  383. /* Transform the 3x8 bits to 4x6 bits, as required by
  384. base64. */
  385. for (string::const_iterator I = S.begin(); I < S.end(); I += 3)
  386. {
  387. char Bits[3] = {0,0,0};
  388. Bits[0] = I[0];
  389. if (I + 1 < S.end())
  390. Bits[1] = I[1];
  391. if (I + 2 < S.end())
  392. Bits[2] = I[2];
  393. Final += tbl[Bits[0] >> 2];
  394. Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
  395. if (I + 1 >= S.end())
  396. break;
  397. Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
  398. if (I + 2 >= S.end())
  399. break;
  400. Final += tbl[Bits[2] & 0x3f];
  401. }
  402. /* Apply the padding elements, this tells how many bytes the remote
  403. end should discard */
  404. if (S.length() % 3 == 2)
  405. Final += '=';
  406. if (S.length() % 3 == 1)
  407. Final += "==";
  408. return Final;
  409. }
  410. /*}}}*/
  411. // stringcmp - Arbitary string compare /*{{{*/
  412. // ---------------------------------------------------------------------
  413. /* This safely compares two non-null terminated strings of arbitary
  414. length */
  415. int stringcmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  416. {
  417. for (; A != AEnd && B != BEnd; A++, B++)
  418. if (*A != *B)
  419. break;
  420. if (A == AEnd && B == BEnd)
  421. return 0;
  422. if (A == AEnd)
  423. return 1;
  424. if (B == BEnd)
  425. return -1;
  426. if (*A < *B)
  427. return -1;
  428. return 1;
  429. }
  430. #if __GNUC__ >= 3
  431. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  432. const char *B,const char *BEnd)
  433. {
  434. for (; A != AEnd && B != BEnd; A++, B++)
  435. if (*A != *B)
  436. break;
  437. if (A == AEnd && B == BEnd)
  438. return 0;
  439. if (A == AEnd)
  440. return 1;
  441. if (B == BEnd)
  442. return -1;
  443. if (*A < *B)
  444. return -1;
  445. return 1;
  446. }
  447. int stringcmp(string::const_iterator A,string::const_iterator AEnd,
  448. string::const_iterator B,string::const_iterator BEnd)
  449. {
  450. for (; A != AEnd && B != BEnd; A++, B++)
  451. if (*A != *B)
  452. break;
  453. if (A == AEnd && B == BEnd)
  454. return 0;
  455. if (A == AEnd)
  456. return 1;
  457. if (B == BEnd)
  458. return -1;
  459. if (*A < *B)
  460. return -1;
  461. return 1;
  462. }
  463. #endif
  464. /*}}}*/
  465. // stringcasecmp - Arbitary case insensitive string compare /*{{{*/
  466. // ---------------------------------------------------------------------
  467. /* */
  468. int stringcasecmp(const char *A,const char *AEnd,const char *B,const char *BEnd)
  469. {
  470. for (; A != AEnd && B != BEnd; A++, B++)
  471. if (toupper(*A) != toupper(*B))
  472. break;
  473. if (A == AEnd && B == BEnd)
  474. return 0;
  475. if (A == AEnd)
  476. return 1;
  477. if (B == BEnd)
  478. return -1;
  479. if (toupper(*A) < toupper(*B))
  480. return -1;
  481. return 1;
  482. }
  483. #if __GNUC__ >= 3
  484. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  485. const char *B,const char *BEnd)
  486. {
  487. for (; A != AEnd && B != BEnd; A++, B++)
  488. if (toupper(*A) != toupper(*B))
  489. break;
  490. if (A == AEnd && B == BEnd)
  491. return 0;
  492. if (A == AEnd)
  493. return 1;
  494. if (B == BEnd)
  495. return -1;
  496. if (toupper(*A) < toupper(*B))
  497. return -1;
  498. return 1;
  499. }
  500. int stringcasecmp(string::const_iterator A,string::const_iterator AEnd,
  501. string::const_iterator B,string::const_iterator BEnd)
  502. {
  503. for (; A != AEnd && B != BEnd; A++, B++)
  504. if (toupper(*A) != toupper(*B))
  505. break;
  506. if (A == AEnd && B == BEnd)
  507. return 0;
  508. if (A == AEnd)
  509. return 1;
  510. if (B == BEnd)
  511. return -1;
  512. if (toupper(*A) < toupper(*B))
  513. return -1;
  514. return 1;
  515. }
  516. #endif
  517. /*}}}*/
  518. // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
  519. // ---------------------------------------------------------------------
  520. /* The format is like those used in package files and the method
  521. communication system */
  522. string LookupTag(const string &Message,const char *Tag,const char *Default)
  523. {
  524. // Look for a matching tag.
  525. int Length = strlen(Tag);
  526. for (string::const_iterator I = Message.begin(); I + Length < Message.end(); I++)
  527. {
  528. // Found the tag
  529. if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
  530. {
  531. // Find the end of line and strip the leading/trailing spaces
  532. string::const_iterator J;
  533. I += Length + 1;
  534. for (; isspace(*I) != 0 && I < Message.end(); I++);
  535. for (J = I; *J != '\n' && J < Message.end(); J++);
  536. for (; J > I && isspace(J[-1]) != 0; J--);
  537. return string(I,J);
  538. }
  539. for (; *I != '\n' && I < Message.end(); I++);
  540. }
  541. // Failed to find a match
  542. if (Default == 0)
  543. return string();
  544. return Default;
  545. }
  546. /*}}}*/
  547. // StringToBool - Converts a string into a boolean /*{{{*/
  548. // ---------------------------------------------------------------------
  549. /* This inspects the string to see if it is true or if it is false and
  550. then returns the result. Several varients on true/false are checked. */
  551. int StringToBool(const string &Text,int Default)
  552. {
  553. char *End;
  554. int Res = strtol(Text.c_str(),&End,0);
  555. if (End != Text.c_str() && Res >= 0 && Res <= 1)
  556. return Res;
  557. // Check for positives
  558. if (strcasecmp(Text.c_str(),"no") == 0 ||
  559. strcasecmp(Text.c_str(),"false") == 0 ||
  560. strcasecmp(Text.c_str(),"without") == 0 ||
  561. strcasecmp(Text.c_str(),"off") == 0 ||
  562. strcasecmp(Text.c_str(),"disable") == 0)
  563. return 0;
  564. // Check for negatives
  565. if (strcasecmp(Text.c_str(),"yes") == 0 ||
  566. strcasecmp(Text.c_str(),"true") == 0 ||
  567. strcasecmp(Text.c_str(),"with") == 0 ||
  568. strcasecmp(Text.c_str(),"on") == 0 ||
  569. strcasecmp(Text.c_str(),"enable") == 0)
  570. return 1;
  571. return Default;
  572. }
  573. /*}}}*/
  574. // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
  575. // ---------------------------------------------------------------------
  576. /* This converts a time_t into a string time representation that is
  577. year 2000 complient and timezone neutral */
  578. string TimeRFC1123(time_t Date)
  579. {
  580. struct tm Conv = *gmtime(&Date);
  581. char Buf[300];
  582. const char *Day[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
  583. const char *Month[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
  584. "Aug","Sep","Oct","Nov","Dec"};
  585. sprintf(Buf,"%s, %02i %s %i %02i:%02i:%02i GMT",Day[Conv.tm_wday],
  586. Conv.tm_mday,Month[Conv.tm_mon],Conv.tm_year+1900,Conv.tm_hour,
  587. Conv.tm_min,Conv.tm_sec);
  588. return Buf;
  589. }
  590. /*}}}*/
  591. // ReadMessages - Read messages from the FD /*{{{*/
  592. // ---------------------------------------------------------------------
  593. /* This pulls full messages from the input FD into the message buffer.
  594. It assumes that messages will not pause during transit so no
  595. fancy buffering is used. */
  596. bool ReadMessages(int Fd, vector<string> &List)
  597. {
  598. char Buffer[64000];
  599. char *End = Buffer;
  600. while (1)
  601. {
  602. int Res = read(Fd,End,sizeof(Buffer) - (End-Buffer));
  603. if (Res < 0 && errno == EINTR)
  604. continue;
  605. // Process is dead, this is kind of bad..
  606. if (Res == 0)
  607. return false;
  608. // No data
  609. if (Res < 0 && errno == EAGAIN)
  610. return true;
  611. if (Res < 0)
  612. return false;
  613. End += Res;
  614. // Look for the end of the message
  615. for (char *I = Buffer; I + 1 < End; I++)
  616. {
  617. if (I[0] != '\n' || I[1] != '\n')
  618. continue;
  619. // Pull the message out
  620. string Message(Buffer,I-Buffer);
  621. // Fix up the buffer
  622. for (; I < End && *I == '\n'; I++);
  623. End -= I-Buffer;
  624. memmove(Buffer,I,End-Buffer);
  625. I = Buffer;
  626. List.push_back(Message);
  627. }
  628. if (End == Buffer)
  629. return true;
  630. if (WaitFd(Fd) == false)
  631. return false;
  632. }
  633. }
  634. /*}}}*/
  635. // MonthConv - Converts a month string into a number /*{{{*/
  636. // ---------------------------------------------------------------------
  637. /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
  638. Made it a bit more robust with a few touppers though. */
  639. static int MonthConv(char *Month)
  640. {
  641. switch (toupper(*Month))
  642. {
  643. case 'A':
  644. return toupper(Month[1]) == 'P'?3:7;
  645. case 'D':
  646. return 11;
  647. case 'F':
  648. return 1;
  649. case 'J':
  650. if (toupper(Month[1]) == 'A')
  651. return 0;
  652. return toupper(Month[2]) == 'N'?5:6;
  653. case 'M':
  654. return toupper(Month[2]) == 'R'?2:4;
  655. case 'N':
  656. return 10;
  657. case 'O':
  658. return 9;
  659. case 'S':
  660. return 8;
  661. // Pretend it is January..
  662. default:
  663. return 0;
  664. }
  665. }
  666. /*}}}*/
  667. // timegm - Internal timegm function if gnu is not available /*{{{*/
  668. // ---------------------------------------------------------------------
  669. /* Ripped this evil little function from wget - I prefer the use of
  670. GNU timegm if possible as this technique will have interesting problems
  671. with leap seconds, timezones and other.
  672. Converts struct tm to time_t, assuming the data in tm is UTC rather
  673. than local timezone (mktime assumes the latter).
  674. Contributed by Roger Beeman <beeman@cisco.com>, with the help of
  675. Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
  676. /* Turned it into an autoconf check, because GNU is not the only thing which
  677. can provide timegm. -- 2002-09-22, Joel Baker */
  678. #ifndef HAVE_TIMEGM // Now with autoconf!
  679. static time_t timegm(struct tm *t)
  680. {
  681. time_t tl, tb;
  682. tl = mktime (t);
  683. if (tl == -1)
  684. return -1;
  685. tb = mktime (gmtime (&tl));
  686. return (tl <= tb ? (tl + (tl - tb)) : (tl - (tb - tl)));
  687. }
  688. #endif
  689. /*}}}*/
  690. // StrToTime - Converts a string into a time_t /*{{{*/
  691. // ---------------------------------------------------------------------
  692. /* This handles all 3 populare time formats including RFC 1123, RFC 1036
  693. and the C library asctime format. It requires the GNU library function
  694. 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
  695. reason the C library does not provide any such function :< This also
  696. handles the weird, but unambiguous FTP time format*/
  697. bool StrToTime(const string &Val,time_t &Result)
  698. {
  699. struct tm Tm;
  700. char Month[10];
  701. const char *I = Val.c_str();
  702. // Skip the day of the week
  703. for (;*I != 0 && *I != ' '; I++);
  704. // Handle RFC 1123 time
  705. Month[0] = 0;
  706. if (sscanf(I," %d %3s %d %d:%d:%d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
  707. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  708. {
  709. // Handle RFC 1036 time
  710. if (sscanf(I," %d-%3s-%d %d:%d:%d GMT",&Tm.tm_mday,Month,
  711. &Tm.tm_year,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) == 6)
  712. Tm.tm_year += 1900;
  713. else
  714. {
  715. // asctime format
  716. if (sscanf(I," %3s %d %d:%d:%d %d",Month,&Tm.tm_mday,
  717. &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
  718. {
  719. // 'ftp' time
  720. if (sscanf(Val.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm.tm_year,&Tm.tm_mon,
  721. &Tm.tm_mday,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
  722. return false;
  723. Tm.tm_mon--;
  724. }
  725. }
  726. }
  727. Tm.tm_isdst = 0;
  728. if (Month[0] != 0)
  729. Tm.tm_mon = MonthConv(Month);
  730. Tm.tm_year -= 1900;
  731. // Convert to local time and then to GMT
  732. Result = timegm(&Tm);
  733. return true;
  734. }
  735. /*}}}*/
  736. // StrToNum - Convert a fixed length string to a number /*{{{*/
  737. // ---------------------------------------------------------------------
  738. /* This is used in decoding the crazy fixed length string headers in
  739. tar and ar files. */
  740. bool StrToNum(const char *Str,unsigned long &Res,unsigned Len,unsigned Base)
  741. {
  742. char S[30];
  743. if (Len >= sizeof(S))
  744. return false;
  745. memcpy(S,Str,Len);
  746. S[Len] = 0;
  747. // All spaces is a zero
  748. Res = 0;
  749. unsigned I;
  750. for (I = 0; S[I] == ' '; I++);
  751. if (S[I] == 0)
  752. return true;
  753. char *End;
  754. Res = strtoul(S,&End,Base);
  755. if (End == S)
  756. return false;
  757. return true;
  758. }
  759. /*}}}*/
  760. // HexDigit - Convert a hex character into an integer /*{{{*/
  761. // ---------------------------------------------------------------------
  762. /* Helper for Hex2Num */
  763. static int HexDigit(int c)
  764. {
  765. if (c >= '0' && c <= '9')
  766. return c - '0';
  767. if (c >= 'a' && c <= 'f')
  768. return c - 'a' + 10;
  769. if (c >= 'A' && c <= 'F')
  770. return c - 'A' + 10;
  771. return 0;
  772. }
  773. /*}}}*/
  774. // Hex2Num - Convert a long hex number into a buffer /*{{{*/
  775. // ---------------------------------------------------------------------
  776. /* The length of the buffer must be exactly 1/2 the length of the string. */
  777. bool Hex2Num(const string &Str,unsigned char *Num,unsigned int Length)
  778. {
  779. if (Str.length() != Length*2)
  780. return false;
  781. // Convert each digit. We store it in the same order as the string
  782. int J = 0;
  783. for (string::const_iterator I = Str.begin(); I != Str.end();J++, I += 2)
  784. {
  785. if (isxdigit(*I) == 0 || isxdigit(I[1]) == 0)
  786. return false;
  787. Num[J] = HexDigit(I[0]) << 4;
  788. Num[J] += HexDigit(I[1]);
  789. }
  790. return true;
  791. }
  792. /*}}}*/
  793. // TokSplitString - Split a string up by a given token /*{{{*/
  794. // ---------------------------------------------------------------------
  795. /* This is intended to be a faster splitter, it does not use dynamic
  796. memories. Input is changed to insert nulls at each token location. */
  797. bool TokSplitString(char Tok,char *Input,char **List,
  798. unsigned long ListMax)
  799. {
  800. // Strip any leading spaces
  801. char *Start = Input;
  802. char *Stop = Start + strlen(Start);
  803. for (; *Start != 0 && isspace(*Start) != 0; Start++);
  804. unsigned long Count = 0;
  805. char *Pos = Start;
  806. while (Pos != Stop)
  807. {
  808. // Skip to the next Token
  809. for (; Pos != Stop && *Pos != Tok; Pos++);
  810. // Back remove spaces
  811. char *End = Pos;
  812. for (; End > Start && (End[-1] == Tok || isspace(End[-1]) != 0); End--);
  813. *End = 0;
  814. List[Count++] = Start;
  815. if (Count >= ListMax)
  816. {
  817. List[Count-1] = 0;
  818. return false;
  819. }
  820. // Advance pos
  821. for (; Pos != Stop && (*Pos == Tok || isspace(*Pos) != 0 || *Pos == 0); Pos++);
  822. Start = Pos;
  823. }
  824. List[Count] = 0;
  825. return true;
  826. }
  827. /*}}}*/
  828. // RegexChoice - Simple regex list/list matcher /*{{{*/
  829. // ---------------------------------------------------------------------
  830. /* */
  831. unsigned long RegexChoice(RxChoiceList *Rxs,const char **ListBegin,
  832. const char **ListEnd)
  833. {
  834. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  835. R->Hit = false;
  836. unsigned long Hits = 0;
  837. for (; ListBegin != ListEnd; ListBegin++)
  838. {
  839. // Check if the name is a regex
  840. const char *I;
  841. bool Regex = true;
  842. for (I = *ListBegin; *I != 0; I++)
  843. if (*I == '.' || *I == '?' || *I == '*' || *I == '|')
  844. break;
  845. if (*I == 0)
  846. Regex = false;
  847. // Compile the regex pattern
  848. regex_t Pattern;
  849. if (Regex == true)
  850. if (regcomp(&Pattern,*ListBegin,REG_EXTENDED | REG_ICASE |
  851. REG_NOSUB) != 0)
  852. Regex = false;
  853. // Search the list
  854. bool Done = false;
  855. for (RxChoiceList *R = Rxs; R->Str != 0; R++)
  856. {
  857. if (R->Str[0] == 0)
  858. continue;
  859. if (strcasecmp(R->Str,*ListBegin) != 0)
  860. {
  861. if (Regex == false)
  862. continue;
  863. if (regexec(&Pattern,R->Str,0,0,0) != 0)
  864. continue;
  865. }
  866. Done = true;
  867. if (R->Hit == false)
  868. Hits++;
  869. R->Hit = true;
  870. }
  871. if (Regex == true)
  872. regfree(&Pattern);
  873. if (Done == false)
  874. _error->Warning(_("Selection %s not found"),*ListBegin);
  875. }
  876. return Hits;
  877. }
  878. /*}}}*/
  879. // ioprintf - C format string outputter to C++ iostreams /*{{{*/
  880. // ---------------------------------------------------------------------
  881. /* This is used to make the internationalization strings easier to translate
  882. and to allow reordering of parameters */
  883. void ioprintf(ostream &out,const char *format,...)
  884. {
  885. va_list args;
  886. va_start(args,format);
  887. // sprintf the description
  888. char S[400];
  889. vsnprintf(S,sizeof(S),format,args);
  890. out << S;
  891. }
  892. /*}}}*/
  893. // safe_snprintf - Safer snprintf /*{{{*/
  894. // ---------------------------------------------------------------------
  895. /* This is a snprintf that will never (ever) go past 'End' and returns a
  896. pointer to the end of the new string. The returned string is always null
  897. terminated unless Buffer == end. This is a better alterantive to using
  898. consecutive snprintfs. */
  899. char *safe_snprintf(char *Buffer,char *End,const char *Format,...)
  900. {
  901. va_list args;
  902. unsigned long Did;
  903. va_start(args,Format);
  904. if (End <= Buffer)
  905. return End;
  906. Did = vsnprintf(Buffer,End - Buffer,Format,args);
  907. if (Did < 0 || Buffer + Did > End)
  908. return End;
  909. return Buffer + Did;
  910. }
  911. /*}}}*/
  912. // CheckDomainList - See if Host is in a , seperate list /*{{{*/
  913. // ---------------------------------------------------------------------
  914. /* The domain list is a comma seperate list of domains that are suffix
  915. matched against the argument */
  916. bool CheckDomainList(const string &Host,const string &List)
  917. {
  918. string::const_iterator Start = List.begin();
  919. for (string::const_iterator Cur = List.begin(); Cur <= List.end(); Cur++)
  920. {
  921. if (Cur < List.end() && *Cur != ',')
  922. continue;
  923. // Match the end of the string..
  924. if ((Host.size() >= (unsigned)(Cur - Start)) &&
  925. Cur - Start != 0 &&
  926. stringcasecmp(Host.end() - (Cur - Start),Host.end(),Start,Cur) == 0)
  927. return true;
  928. Start = Cur + 1;
  929. }
  930. return false;
  931. }
  932. /*}}}*/
  933. // URI::CopyFrom - Copy from an object /*{{{*/
  934. // ---------------------------------------------------------------------
  935. /* This parses the URI into all of its components */
  936. void URI::CopyFrom(const string &U)
  937. {
  938. string::const_iterator I = U.begin();
  939. // Locate the first colon, this separates the scheme
  940. for (; I < U.end() && *I != ':' ; I++);
  941. string::const_iterator FirstColon = I;
  942. /* Determine if this is a host type URI with a leading double //
  943. and then search for the first single / */
  944. string::const_iterator SingleSlash = I;
  945. if (I + 3 < U.end() && I[1] == '/' && I[2] == '/')
  946. SingleSlash += 3;
  947. /* Find the / indicating the end of the hostname, ignoring /'s in the
  948. square brackets */
  949. bool InBracket = false;
  950. for (; SingleSlash < U.end() && (*SingleSlash != '/' || InBracket == true); SingleSlash++)
  951. {
  952. if (*SingleSlash == '[')
  953. InBracket = true;
  954. if (InBracket == true && *SingleSlash == ']')
  955. InBracket = false;
  956. }
  957. if (SingleSlash > U.end())
  958. SingleSlash = U.end();
  959. // We can now write the access and path specifiers
  960. Access.assign(U.begin(),FirstColon);
  961. if (SingleSlash != U.end())
  962. Path.assign(SingleSlash,U.end());
  963. if (Path.empty() == true)
  964. Path = "/";
  965. // Now we attempt to locate a user:pass@host fragment
  966. if (FirstColon + 2 <= U.end() && FirstColon[1] == '/' && FirstColon[2] == '/')
  967. FirstColon += 3;
  968. else
  969. FirstColon += 1;
  970. if (FirstColon >= U.end())
  971. return;
  972. if (FirstColon > SingleSlash)
  973. FirstColon = SingleSlash;
  974. // Find the colon...
  975. I = FirstColon + 1;
  976. if (I > SingleSlash)
  977. I = SingleSlash;
  978. for (; I < SingleSlash && *I != ':'; I++);
  979. string::const_iterator SecondColon = I;
  980. // Search for the @ after the colon
  981. for (; I < SingleSlash && *I != '@'; I++);
  982. string::const_iterator At = I;
  983. // Now write the host and user/pass
  984. if (At == SingleSlash)
  985. {
  986. if (FirstColon < SingleSlash)
  987. Host.assign(FirstColon,SingleSlash);
  988. }
  989. else
  990. {
  991. Host.assign(At+1,SingleSlash);
  992. User.assign(FirstColon,SecondColon);
  993. if (SecondColon < At)
  994. Password.assign(SecondColon+1,At);
  995. }
  996. // Now we parse the RFC 2732 [] hostnames.
  997. unsigned long PortEnd = 0;
  998. InBracket = false;
  999. for (unsigned I = 0; I != Host.length();)
  1000. {
  1001. if (Host[I] == '[')
  1002. {
  1003. InBracket = true;
  1004. Host.erase(I,1);
  1005. continue;
  1006. }
  1007. if (InBracket == true && Host[I] == ']')
  1008. {
  1009. InBracket = false;
  1010. Host.erase(I,1);
  1011. PortEnd = I;
  1012. continue;
  1013. }
  1014. I++;
  1015. }
  1016. // Tsk, weird.
  1017. if (InBracket == true)
  1018. {
  1019. Host.clear();
  1020. return;
  1021. }
  1022. // Now we parse off a port number from the hostname
  1023. Port = 0;
  1024. string::size_type Pos = Host.rfind(':');
  1025. if (Pos == string::npos || Pos < PortEnd)
  1026. return;
  1027. Port = atoi(string(Host,Pos+1).c_str());
  1028. Host.assign(Host,0,Pos);
  1029. }
  1030. /*}}}*/
  1031. // URI::operator string - Convert the URI to a string /*{{{*/
  1032. // ---------------------------------------------------------------------
  1033. /* */
  1034. URI::operator string()
  1035. {
  1036. string Res;
  1037. if (Access.empty() == false)
  1038. Res = Access + ':';
  1039. if (Host.empty() == false)
  1040. {
  1041. if (Access.empty() == false)
  1042. Res += "//";
  1043. if (User.empty() == false)
  1044. {
  1045. Res += User;
  1046. if (Password.empty() == false)
  1047. Res += ":" + Password;
  1048. Res += "@";
  1049. }
  1050. // Add RFC 2732 escaping characters
  1051. if (Access.empty() == false &&
  1052. (Host.find('/') != string::npos || Host.find(':') != string::npos))
  1053. Res += '[' + Host + ']';
  1054. else
  1055. Res += Host;
  1056. if (Port != 0)
  1057. {
  1058. char S[30];
  1059. sprintf(S,":%u",Port);
  1060. Res += S;
  1061. }
  1062. }
  1063. if (Path.empty() == false)
  1064. {
  1065. if (Path[0] != '/')
  1066. Res += "/" + Path;
  1067. else
  1068. Res += Path;
  1069. }
  1070. return Res;
  1071. }
  1072. /*}}}*/
  1073. // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
  1074. // ---------------------------------------------------------------------
  1075. /* */
  1076. string URI::SiteOnly(const string &URI)
  1077. {
  1078. ::URI U(URI);
  1079. U.User.clear();
  1080. U.Password.clear();
  1081. U.Path.clear();
  1082. U.Port = 0;
  1083. return U;
  1084. }
  1085. /*}}}*/