strutl.cc 24 KB

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