You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1257 lines
33 KiB

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