strutl.cc 31 KB

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