strutl.cc 28 KB

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