strutl.cc 31 KB

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