strutl.cc 31 KB

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