1 // -*- mode: cpp; mode: fold -*-
3 // $Id: strutl.cc,v 1.48 2003/07/18 14:15:11 mdz Exp $
4 /* ######################################################################
6 String Util - Some useful string functions.
8 These have been collected from here and there to do all sorts of useful
9 things to strings. They are useful in file parsers, URI handlers and
10 especially in APT methods.
12 This source is placed in the Public Domain, do with it what you will
13 It was originally written by Jason Gunthorpe <jgg@gpu.srv.ualberta.ca>
15 ##################################################################### */
20 #include <apt-pkg/strutl.h>
21 #include <apt-pkg/fileutl.h>
22 #include <apt-pkg/error.h>
44 // Strip - Remove white space from the front and back of a string /*{{{*/
45 // ---------------------------------------------------------------------
48 std::string
Strip(const std::string
&str
)
50 // ensure we have at least one character
51 if (str
.empty() == true)
54 char const * const s
= str
.c_str();
56 for (; isspace(s
[start
]) != 0; ++start
)
57 ; // find the first not-space
59 // string contains only whitespaces
63 size_t end
= str
.length() - 1;
64 for (; isspace(s
[end
]) != 0; --end
)
65 ; // find the last not-space
67 return str
.substr(start
, end
- start
+ 1);
70 bool Endswith(const std::string
&s
, const std::string
&end
)
72 if (end
.size() > s
.size())
74 return (s
.substr(s
.size() - end
.size(), s
.size()) == end
);
80 // UTF8ToCodeset - Convert some UTF-8 string for some codeset /*{{{*/
81 // ---------------------------------------------------------------------
82 /* This is handy to use before display some information for enduser */
83 bool UTF8ToCodeset(const char *codeset
, const string
&orig
, string
*dest
)
88 size_t insize
, bufsize
;
91 cd
= iconv_open(codeset
, "UTF-8");
92 if (cd
== (iconv_t
)(-1)) {
93 // Something went wrong
95 _error
->Error("conversion from 'UTF-8' to '%s' not available",
103 insize
= bufsize
= orig
.size();
105 inptr
= (char *)inbuf
;
106 outbuf
= new char[bufsize
];
107 size_t lastError
= -1;
111 char *outptr
= outbuf
;
112 size_t outsize
= bufsize
;
113 size_t const err
= iconv(cd
, &inptr
, &insize
, &outptr
, &outsize
);
114 dest
->append(outbuf
, outptr
- outbuf
);
115 if (err
== (size_t)(-1))
122 // replace a series of unknown multibytes with a single "?"
123 if (lastError
!= insize
) {
124 lastError
= insize
- 1;
132 if (outptr
== outbuf
)
136 outbuf
= new char[bufsize
];
150 // strstrip - Remove white space from the front and back of a string /*{{{*/
151 // ---------------------------------------------------------------------
152 /* This is handy to use when parsing a file. It also removes \n's left
153 over from fgets and company */
154 char *_strstrip(char *String
)
156 for (;*String
!= 0 && (*String
== ' ' || *String
== '\t'); String
++);
160 return _strrstrip(String
);
163 // strrstrip - Remove white space from the back of a string /*{{{*/
164 // ---------------------------------------------------------------------
165 char *_strrstrip(char *String
)
167 char *End
= String
+ strlen(String
) - 1;
168 for (;End
!= String
- 1 && (*End
== ' ' || *End
== '\t' || *End
== '\n' ||
169 *End
== '\r'); End
--);
175 // strtabexpand - Converts tabs into 8 spaces /*{{{*/
176 // ---------------------------------------------------------------------
178 char *_strtabexpand(char *String
,size_t Len
)
180 for (char *I
= String
; I
!= I
+ Len
&& *I
!= 0; I
++)
184 if (I
+ 8 > String
+ Len
)
190 /* Assume the start of the string is 0 and find the next 8 char
196 Len
= 8 - ((String
- I
) % 8);
204 memmove(I
+ Len
,I
+ 1,strlen(I
) + 1);
205 for (char *J
= I
; J
+ Len
!= I
; *I
= ' ', I
++);
210 // ParseQuoteWord - Parse a single word out of a string /*{{{*/
211 // ---------------------------------------------------------------------
212 /* This grabs a single word, converts any % escaped characters to their
213 proper values and advances the pointer. Double quotes are understood
214 and striped out as well. This is for URI/URL parsing. It also can
215 understand [] brackets.*/
216 bool ParseQuoteWord(const char *&String
,string
&Res
)
218 // Skip leading whitespace
219 const char *C
= String
;
220 for (;*C
!= 0 && *C
== ' '; C
++);
224 // Jump to the next word
225 for (;*C
!= 0 && isspace(*C
) == 0; C
++)
229 C
= strchr(C
+ 1, '"');
235 C
= strchr(C
+ 1, ']');
241 // Now de-quote characters
244 const char *Start
= String
;
246 for (I
= Buffer
; I
< Buffer
+ sizeof(Buffer
) && Start
!= C
; I
++)
248 if (*Start
== '%' && Start
+ 2 < C
&&
249 isxdigit(Start
[1]) && isxdigit(Start
[2]))
254 *I
= (char)strtol(Tmp
,0,16);
267 // Skip ending white space
268 for (;*C
!= 0 && isspace(*C
) != 0; C
++);
273 // ParseCWord - Parses a string like a C "" expression /*{{{*/
274 // ---------------------------------------------------------------------
275 /* This expects a series of space separated strings enclosed in ""'s.
276 It concatenates the ""'s into a single string. */
277 bool ParseCWord(const char *&String
,string
&Res
)
279 // Skip leading whitespace
280 const char *C
= String
;
281 for (;*C
!= 0 && *C
== ' '; C
++);
287 if (strlen(String
) >= sizeof(Buffer
))
294 for (C
++; *C
!= 0 && *C
!= '"'; C
++)
303 if (C
!= String
&& isspace(*C
) != 0 && isspace(C
[-1]) != 0)
305 if (isspace(*C
) == 0)
315 // QuoteString - Convert a string into quoted from /*{{{*/
316 // ---------------------------------------------------------------------
318 string
QuoteString(const string
&Str
, const char *Bad
)
321 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end(); ++I
)
323 if (strchr(Bad
,*I
) != 0 || isprint(*I
) == 0 ||
324 *I
== 0x25 || // percent '%' char
325 *I
<= 0x20 || *I
>= 0x7F) // control chars
328 sprintf(Buf
,"%%%02x",(int)*I
);
337 // DeQuoteString - Convert a string from quoted from /*{{{*/
338 // ---------------------------------------------------------------------
339 /* This undoes QuoteString */
340 string
DeQuoteString(const string
&Str
)
342 return DeQuoteString(Str
.begin(),Str
.end());
344 string
DeQuoteString(string::const_iterator
const &begin
,
345 string::const_iterator
const &end
)
348 for (string::const_iterator I
= begin
; I
!= end
; ++I
)
350 if (*I
== '%' && I
+ 2 < end
&&
351 isxdigit(I
[1]) && isxdigit(I
[2]))
357 Res
+= (char)strtol(Tmp
,0,16);
368 // SizeToStr - Convert a long into a human readable size /*{{{*/
369 // ---------------------------------------------------------------------
370 /* A max of 4 digits are shown before conversion to the next highest unit.
371 The max length of the string will be 5 chars unless the size is > 10
373 string
SizeToStr(double Size
)
382 /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
383 ExaBytes, ZettaBytes, YottaBytes */
384 char Ext
[] = {'\0','k','M','G','T','P','E','Z','Y'};
388 if (ASize
< 100 && I
!= 0)
390 sprintf(S
,"%'.1f %c",ASize
,Ext
[I
]);
396 sprintf(S
,"%'.0f %c",ASize
,Ext
[I
]);
406 // TimeToStr - Convert the time into a string /*{{{*/
407 // ---------------------------------------------------------------------
408 /* Converts a number of seconds to a hms format */
409 string
TimeToStr(unsigned long Sec
)
417 //d means days, h means hours, min means minutes, s means seconds
418 sprintf(S
,_("%lid %lih %limin %lis"),Sec
/60/60/24,(Sec
/60/60) % 24,(Sec
/60) % 60,Sec
% 60);
424 //h means hours, min means minutes, s means seconds
425 sprintf(S
,_("%lih %limin %lis"),Sec
/60/60,(Sec
/60) % 60,Sec
% 60);
431 //min means minutes, s means seconds
432 sprintf(S
,_("%limin %lis"),Sec
/60,Sec
% 60);
437 sprintf(S
,_("%lis"),Sec
);
444 // SubstVar - Substitute a string for another string /*{{{*/
445 // ---------------------------------------------------------------------
446 /* This replaces all occurrences of Subst with Contents in Str. */
447 string
SubstVar(const string
&Str
,const string
&Subst
,const string
&Contents
)
449 if (Subst
.empty() == true)
452 string::size_type Pos
= 0;
453 string::size_type OldPos
= 0;
456 while (OldPos
< Str
.length() &&
457 (Pos
= Str
.find(Subst
,OldPos
)) != string::npos
)
460 Temp
.append(Str
, OldPos
, Pos
- OldPos
);
461 if (Contents
.empty() == false)
462 Temp
.append(Contents
);
463 OldPos
= Pos
+ Subst
.length();
469 if (OldPos
>= Str
.length())
471 return Temp
+ string(Str
,OldPos
);
473 string
SubstVar(string Str
,const struct SubstVar
*Vars
)
475 for (; Vars
->Subst
!= 0; Vars
++)
476 Str
= SubstVar(Str
,Vars
->Subst
,*Vars
->Contents
);
480 // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
481 // ---------------------------------------------------------------------
482 /* Returns a string with the supplied separator depth + 1 times in it */
483 std::string
OutputInDepth(const unsigned long Depth
, const char* Separator
)
485 std::string output
= "";
486 for(unsigned long d
=Depth
+1; d
> 0; d
--)
487 output
.append(Separator
);
491 // URItoFileName - Convert the uri into a unique file name /*{{{*/
492 // ---------------------------------------------------------------------
493 /* This converts a URI into a safe filename. It quotes all unsafe characters
494 and converts / to _ and removes the scheme identifier. The resulting
495 file name should be unique and never occur again for a different file */
496 string
URItoFileName(const string
&URI
)
498 // Nuke 'sensitive' items
504 // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
505 string NewURI
= QuoteString(U
,"\\|{}[]<>\"^~_=!@#$%^&*");
506 replace(NewURI
.begin(),NewURI
.end(),'/','_');
510 // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
511 // ---------------------------------------------------------------------
512 /* This routine performs a base64 transformation on a string. It was ripped
513 from wget and then patched and bug fixed.
515 This spec can be found in rfc2045 */
516 string
Base64Encode(const string
&S
)
519 static char tbl
[64] = {'A','B','C','D','E','F','G','H',
520 'I','J','K','L','M','N','O','P',
521 'Q','R','S','T','U','V','W','X',
522 'Y','Z','a','b','c','d','e','f',
523 'g','h','i','j','k','l','m','n',
524 'o','p','q','r','s','t','u','v',
525 'w','x','y','z','0','1','2','3',
526 '4','5','6','7','8','9','+','/'};
528 // Pre-allocate some space
530 Final
.reserve((4*S
.length() + 2)/3 + 2);
532 /* Transform the 3x8 bits to 4x6 bits, as required by
534 for (string::const_iterator I
= S
.begin(); I
< S
.end(); I
+= 3)
536 char Bits
[3] = {0,0,0};
543 Final
+= tbl
[Bits
[0] >> 2];
544 Final
+= tbl
[((Bits
[0] & 3) << 4) + (Bits
[1] >> 4)];
546 if (I
+ 1 >= S
.end())
549 Final
+= tbl
[((Bits
[1] & 0xf) << 2) + (Bits
[2] >> 6)];
551 if (I
+ 2 >= S
.end())
554 Final
+= tbl
[Bits
[2] & 0x3f];
557 /* Apply the padding elements, this tells how many bytes the remote
558 end should discard */
559 if (S
.length() % 3 == 2)
561 if (S
.length() % 3 == 1)
567 // stringcmp - Arbitrary string compare /*{{{*/
568 // ---------------------------------------------------------------------
569 /* This safely compares two non-null terminated strings of arbitrary
571 int stringcmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
573 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
577 if (A
== AEnd
&& B
== BEnd
)
589 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
590 const char *B
,const char *BEnd
)
592 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
596 if (A
== AEnd
&& B
== BEnd
)
606 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
607 string::const_iterator B
,string::const_iterator BEnd
)
609 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
613 if (A
== AEnd
&& B
== BEnd
)
625 // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
626 // ---------------------------------------------------------------------
628 int stringcasecmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
630 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
631 if (tolower_ascii(*A
) != tolower_ascii(*B
))
634 if (A
== AEnd
&& B
== BEnd
)
640 if (tolower_ascii(*A
) < tolower_ascii(*B
))
645 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
646 const char *B
,const char *BEnd
)
648 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
649 if (tolower_ascii(*A
) != tolower_ascii(*B
))
652 if (A
== AEnd
&& B
== BEnd
)
658 if (tolower_ascii(*A
) < tolower_ascii(*B
))
662 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
663 string::const_iterator B
,string::const_iterator BEnd
)
665 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
666 if (tolower_ascii(*A
) != tolower_ascii(*B
))
669 if (A
== AEnd
&& B
== BEnd
)
675 if (tolower_ascii(*A
) < tolower_ascii(*B
))
681 // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
682 // ---------------------------------------------------------------------
683 /* The format is like those used in package files and the method
684 communication system */
685 string
LookupTag(const string
&Message
,const char *Tag
,const char *Default
)
687 // Look for a matching tag.
688 int Length
= strlen(Tag
);
689 for (string::const_iterator I
= Message
.begin(); I
+ Length
< Message
.end(); ++I
)
692 if (I
[Length
] == ':' && stringcasecmp(I
,I
+Length
,Tag
) == 0)
694 // Find the end of line and strip the leading/trailing spaces
695 string::const_iterator J
;
697 for (; isspace(*I
) != 0 && I
< Message
.end(); ++I
);
698 for (J
= I
; *J
!= '\n' && J
< Message
.end(); ++J
);
699 for (; J
> I
&& isspace(J
[-1]) != 0; --J
);
704 for (; *I
!= '\n' && I
< Message
.end(); ++I
);
707 // Failed to find a match
713 // StringToBool - Converts a string into a boolean /*{{{*/
714 // ---------------------------------------------------------------------
715 /* This inspects the string to see if it is true or if it is false and
716 then returns the result. Several varients on true/false are checked. */
717 int StringToBool(const string
&Text
,int Default
)
720 int Res
= strtol(Text
.c_str(),&ParseEnd
,0);
721 // ensure that the entire string was converted by strtol to avoid
722 // failures on "apt-cache show -a 0ad" where the "0" is converted
723 const char *TextEnd
= Text
.c_str()+Text
.size();
724 if (ParseEnd
== TextEnd
&& Res
>= 0 && Res
<= 1)
727 // Check for positives
728 if (strcasecmp(Text
.c_str(),"no") == 0 ||
729 strcasecmp(Text
.c_str(),"false") == 0 ||
730 strcasecmp(Text
.c_str(),"without") == 0 ||
731 strcasecmp(Text
.c_str(),"off") == 0 ||
732 strcasecmp(Text
.c_str(),"disable") == 0)
735 // Check for negatives
736 if (strcasecmp(Text
.c_str(),"yes") == 0 ||
737 strcasecmp(Text
.c_str(),"true") == 0 ||
738 strcasecmp(Text
.c_str(),"with") == 0 ||
739 strcasecmp(Text
.c_str(),"on") == 0 ||
740 strcasecmp(Text
.c_str(),"enable") == 0)
746 // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
747 // ---------------------------------------------------------------------
748 /* This converts a time_t into a string time representation that is
749 year 2000 complient and timezone neutral */
750 string
TimeRFC1123(time_t Date
)
753 if (gmtime_r(&Date
, &Conv
) == NULL
)
757 const char *Day
[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
758 const char *Month
[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
759 "Aug","Sep","Oct","Nov","Dec"};
761 snprintf(Buf
, sizeof(Buf
), "%s, %02i %s %i %02i:%02i:%02i GMT",Day
[Conv
.tm_wday
],
762 Conv
.tm_mday
,Month
[Conv
.tm_mon
],Conv
.tm_year
+1900,Conv
.tm_hour
,
763 Conv
.tm_min
,Conv
.tm_sec
);
767 // ReadMessages - Read messages from the FD /*{{{*/
768 // ---------------------------------------------------------------------
769 /* This pulls full messages from the input FD into the message buffer.
770 It assumes that messages will not pause during transit so no
771 fancy buffering is used.
773 In particular: this reads blocks from the input until it believes
774 that it's run out of input text. Each block is terminated by a
775 double newline ('\n' followed by '\n'). As noted below, there is a
776 bug in this code: it assumes that all the blocks have been read if
777 it doesn't see additional text in the buffer after the last one is
778 parsed, which will cause it to lose blocks if the last block
779 coincides with the end of the buffer.
781 bool ReadMessages(int Fd
, vector
<string
> &List
)
785 // Represents any left-over from the previous iteration of the
786 // parse loop. (i.e., if a message is split across the end
787 // of the buffer, it goes here)
788 string PartialMessage
;
792 int Res
= read(Fd
,End
,sizeof(Buffer
) - (End
-Buffer
));
793 if (Res
< 0 && errno
== EINTR
)
796 // Process is dead, this is kind of bad..
801 if (Res
< 0 && errno
== EAGAIN
)
808 // Look for the end of the message
809 for (char *I
= Buffer
; I
+ 1 < End
; I
++)
812 (I
[0] != '\n' && strncmp(I
, "\r\n\r\n", 4) != 0))
815 // Pull the message out
816 string
Message(Buffer
,I
-Buffer
);
817 PartialMessage
+= Message
;
820 for (; I
< End
&& (*I
== '\n' || *I
== '\r'); ++I
);
822 memmove(Buffer
,I
,End
-Buffer
);
825 List
.push_back(PartialMessage
);
826 PartialMessage
.clear();
830 // If there's text left in the buffer, store it
831 // in PartialMessage and throw the rest of the buffer
832 // away. This allows us to handle messages that
833 // are longer than the static buffer size.
834 PartialMessage
+= string(Buffer
, End
);
839 // BUG ALERT: if a message block happens to end at a
840 // multiple of 64000 characters, this will cause it to
841 // terminate early, leading to a badly formed block and
842 // probably crashing the method. However, this is the only
843 // way we have to find the end of the message block. I have
844 // an idea of how to fix this, but it will require changes
845 // to the protocol (essentially to mark the beginning and
846 // end of the block).
848 // -- dburrows 2008-04-02
852 if (WaitFd(Fd
) == false)
857 // MonthConv - Converts a month string into a number /*{{{*/
858 // ---------------------------------------------------------------------
859 /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
860 Made it a bit more robust with a few tolower_ascii though. */
861 static int MonthConv(char *Month
)
863 switch (tolower_ascii(*Month
))
866 return tolower_ascii(Month
[1]) == 'p'?3:7;
872 if (tolower_ascii(Month
[1]) == 'a')
874 return tolower_ascii(Month
[2]) == 'n'?5:6;
876 return tolower_ascii(Month
[2]) == 'r'?2:4;
884 // Pretend it is January..
890 // timegm - Internal timegm if the gnu version is not available /*{{{*/
891 // ---------------------------------------------------------------------
892 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
893 than local timezone (mktime assumes the latter).
895 This function is a nonstandard GNU extension that is also present on
896 the BSDs and maybe other systems. For others we follow the advice of
897 the manpage of timegm and use his portable replacement. */
899 static time_t timegm(struct tm
*t
)
901 char *tz
= getenv("TZ");
904 time_t ret
= mktime(t
);
914 // FullDateToTime - Converts a HTTP1.1 full date strings into a time_t /*{{{*/
915 // ---------------------------------------------------------------------
916 /* tries to parses a full date as specified in RFC2616 Section 3.3.1
917 with one exception: All timezones (%Z) are accepted but the protocol
918 says that it MUST be GMT, but this one is equal to UTC which we will
919 encounter from time to time (e.g. in Release files) so we accept all
920 here and just assume it is GMT (or UTC) later on */
921 bool RFC1123StrToTime(const char* const str
,time_t &time
)
924 setlocale (LC_ALL
,"C");
926 // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
927 (strptime(str
, "%a, %d %b %Y %H:%M:%S %Z", &Tm
) == NULL
&&
928 // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
929 strptime(str
, "%A, %d-%b-%y %H:%M:%S %Z", &Tm
) == NULL
&&
930 // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
931 strptime(str
, "%a %b %d %H:%M:%S %Y", &Tm
) == NULL
);
932 setlocale (LC_ALL
,"");
940 // FTPMDTMStrToTime - Converts a ftp modification date into a time_t /*{{{*/
941 // ---------------------------------------------------------------------
943 bool FTPMDTMStrToTime(const char* const str
,time_t &time
)
946 // MDTM includes no whitespaces but recommend and ignored by strptime
947 if (strptime(str
, "%Y %m %d %H %M %S", &Tm
) == NULL
)
954 // StrToTime - Converts a string into a time_t /*{{{*/
955 // ---------------------------------------------------------------------
956 /* This handles all 3 popular time formats including RFC 1123, RFC 1036
957 and the C library asctime format. It requires the GNU library function
958 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
959 reason the C library does not provide any such function :< This also
960 handles the weird, but unambiguous FTP time format*/
961 bool StrToTime(const string
&Val
,time_t &Result
)
966 // Skip the day of the week
967 const char *I
= strchr(Val
.c_str(), ' ');
969 // Handle RFC 1123 time
971 if (sscanf(I
," %2d %3s %4d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,&Tm
.tm_year
,
972 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
974 // Handle RFC 1036 time
975 if (sscanf(I
," %2d-%3s-%3d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,
976 &Tm
.tm_year
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) == 6)
981 if (sscanf(I
," %3s %2d %2d:%2d:%2d %4d",Month
,&Tm
.tm_mday
,
982 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
,&Tm
.tm_year
) != 6)
985 if (sscanf(Val
.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm
.tm_year
,&Tm
.tm_mon
,
986 &Tm
.tm_mday
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
995 Tm
.tm_mon
= MonthConv(Month
);
997 Tm
.tm_mon
= 0; // we don't have a month, so pick something
1000 // Convert to local time and then to GMT
1001 Result
= timegm(&Tm
);
1005 // StrToNum - Convert a fixed length string to a number /*{{{*/
1006 // ---------------------------------------------------------------------
1007 /* This is used in decoding the crazy fixed length string headers in
1008 tar and ar files. */
1009 bool StrToNum(const char *Str
,unsigned long &Res
,unsigned Len
,unsigned Base
)
1012 if (Len
>= sizeof(S
))
1017 // All spaces is a zero
1020 for (I
= 0; S
[I
] == ' '; I
++);
1025 Res
= strtoul(S
,&End
,Base
);
1032 // StrToNum - Convert a fixed length string to a number /*{{{*/
1033 // ---------------------------------------------------------------------
1034 /* This is used in decoding the crazy fixed length string headers in
1035 tar and ar files. */
1036 bool StrToNum(const char *Str
,unsigned long long &Res
,unsigned Len
,unsigned Base
)
1039 if (Len
>= sizeof(S
))
1044 // All spaces is a zero
1047 for (I
= 0; S
[I
] == ' '; I
++);
1052 Res
= strtoull(S
,&End
,Base
);
1060 // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
1061 // ---------------------------------------------------------------------
1062 /* This is used in decoding the 256bit encoded fixed length fields in
1064 bool Base256ToNum(const char *Str
,unsigned long &Res
,unsigned int Len
)
1066 if ((Str
[0] & 0x80) == 0)
1070 Res
= Str
[0] & 0x7F;
1071 for(unsigned int i
= 1; i
< Len
; ++i
)
1072 Res
= (Res
<<8) + Str
[i
];
1077 // HexDigit - Convert a hex character into an integer /*{{{*/
1078 // ---------------------------------------------------------------------
1079 /* Helper for Hex2Num */
1080 static int HexDigit(int c
)
1082 if (c
>= '0' && c
<= '9')
1084 if (c
>= 'a' && c
<= 'f')
1085 return c
- 'a' + 10;
1086 if (c
>= 'A' && c
<= 'F')
1087 return c
- 'A' + 10;
1091 // Hex2Num - Convert a long hex number into a buffer /*{{{*/
1092 // ---------------------------------------------------------------------
1093 /* The length of the buffer must be exactly 1/2 the length of the string. */
1094 bool Hex2Num(const string
&Str
,unsigned char *Num
,unsigned int Length
)
1096 if (Str
.length() != Length
*2)
1099 // Convert each digit. We store it in the same order as the string
1101 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end();J
++, I
+= 2)
1103 if (isxdigit(*I
) == 0 || isxdigit(I
[1]) == 0)
1106 Num
[J
] = HexDigit(I
[0]) << 4;
1107 Num
[J
] += HexDigit(I
[1]);
1113 // TokSplitString - Split a string up by a given token /*{{{*/
1114 // ---------------------------------------------------------------------
1115 /* This is intended to be a faster splitter, it does not use dynamic
1116 memories. Input is changed to insert nulls at each token location. */
1117 bool TokSplitString(char Tok
,char *Input
,char **List
,
1118 unsigned long ListMax
)
1120 // Strip any leading spaces
1121 char *Start
= Input
;
1122 char *Stop
= Start
+ strlen(Start
);
1123 for (; *Start
!= 0 && isspace(*Start
) != 0; Start
++);
1125 unsigned long Count
= 0;
1129 // Skip to the next Token
1130 for (; Pos
!= Stop
&& *Pos
!= Tok
; Pos
++);
1132 // Back remove spaces
1134 for (; End
> Start
&& (End
[-1] == Tok
|| isspace(End
[-1]) != 0); End
--);
1137 List
[Count
++] = Start
;
1138 if (Count
>= ListMax
)
1145 for (; Pos
!= Stop
&& (*Pos
== Tok
|| isspace(*Pos
) != 0 || *Pos
== 0); Pos
++);
1153 // VectorizeString - Split a string up into a vector of strings /*{{{*/
1154 // ---------------------------------------------------------------------
1155 /* This can be used to split a given string up into a vector, so the
1156 propose is the same as in the method above and this one is a bit slower
1157 also, but the advantage is that we have an iteratable vector */
1158 vector
<string
> VectorizeString(string
const &haystack
, char const &split
)
1160 vector
<string
> exploded
;
1161 if (haystack
.empty() == true)
1163 string::const_iterator start
= haystack
.begin();
1164 string::const_iterator end
= start
;
1166 for (; end
!= haystack
.end() && *end
!= split
; ++end
);
1167 exploded
.push_back(string(start
, end
));
1169 } while (end
!= haystack
.end() && (++end
) != haystack
.end());
1173 // StringSplit - split a string into a string vector by token /*{{{*/
1174 // ---------------------------------------------------------------------
1175 /* See header for details.
1177 vector
<string
> StringSplit(std::string
const &s
, std::string
const &sep
,
1178 unsigned int maxsplit
)
1180 vector
<string
> split
;
1183 // no seperator given, this is bogus
1188 while (pos
!= string::npos
)
1190 pos
= s
.find(sep
, start
);
1191 split
.push_back(s
.substr(start
, pos
-start
));
1193 // if maxsplit is reached, the remaining string is the last item
1194 if(split
.size() >= maxsplit
)
1196 split
[split
.size()-1] = s
.substr(start
);
1199 start
= pos
+sep
.size();
1204 // RegexChoice - Simple regex list/list matcher /*{{{*/
1205 // ---------------------------------------------------------------------
1207 unsigned long RegexChoice(RxChoiceList
*Rxs
,const char **ListBegin
,
1208 const char **ListEnd
)
1210 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1213 unsigned long Hits
= 0;
1214 for (; ListBegin
< ListEnd
; ++ListBegin
)
1216 // Check if the name is a regex
1219 for (I
= *ListBegin
; *I
!= 0; I
++)
1220 if (*I
== '.' || *I
== '?' || *I
== '*' || *I
== '|')
1225 // Compile the regex pattern
1228 if (regcomp(&Pattern
,*ListBegin
,REG_EXTENDED
| REG_ICASE
|
1234 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1239 if (strcasecmp(R
->Str
,*ListBegin
) != 0)
1243 if (regexec(&Pattern
,R
->Str
,0,0,0) != 0)
1248 if (R
->Hit
== false)
1258 _error
->Warning(_("Selection %s not found"),*ListBegin
);
1264 // {str,io}printf - C format string outputter to C++ strings/iostreams /*{{{*/
1265 // ---------------------------------------------------------------------
1266 /* This is used to make the internationalization strings easier to translate
1267 and to allow reordering of parameters */
1268 static bool iovprintf(ostream
&out
, const char *format
,
1269 va_list &args
, ssize_t
&size
) {
1270 char *S
= (char*)malloc(size
);
1271 ssize_t
const n
= vsnprintf(S
, size
, format
, args
);
1272 if (n
> -1 && n
< size
) {
1285 void ioprintf(ostream
&out
,const char *format
,...)
1290 va_start(args
,format
);
1291 if (iovprintf(out
, format
, args
, size
) == true)
1296 void strprintf(string
&out
,const char *format
,...)
1300 std::ostringstream outstr
;
1302 va_start(args
,format
);
1303 if (iovprintf(outstr
, format
, args
, size
) == true)
1310 // safe_snprintf - Safer snprintf /*{{{*/
1311 // ---------------------------------------------------------------------
1312 /* This is a snprintf that will never (ever) go past 'End' and returns a
1313 pointer to the end of the new string. The returned string is always null
1314 terminated unless Buffer == end. This is a better alterantive to using
1315 consecutive snprintfs. */
1316 char *safe_snprintf(char *Buffer
,char *End
,const char *Format
,...)
1323 va_start(args
,Format
);
1324 Did
= vsnprintf(Buffer
,End
- Buffer
,Format
,args
);
1327 if (Did
< 0 || Buffer
+ Did
> End
)
1329 return Buffer
+ Did
;
1332 // StripEpoch - Remove the version "epoch" from a version string /*{{{*/
1333 // ---------------------------------------------------------------------
1334 string
StripEpoch(const string
&VerStr
)
1336 size_t i
= VerStr
.find(":");
1337 if (i
== string::npos
)
1339 return VerStr
.substr(i
+1);
1342 // tolower_ascii - tolower() function that ignores the locale /*{{{*/
1343 // ---------------------------------------------------------------------
1344 /* This little function is the most called method we have and tries
1345 therefore to do the absolut minimum - and is notable faster than
1346 standard tolower/toupper and as a bonus avoids problems with different
1347 locales - we only operate on ascii chars anyway. */
1348 int tolower_ascii(int const c
)
1350 if (c
>= 'A' && c
<= 'Z')
1356 // CheckDomainList - See if Host is in a , separate list /*{{{*/
1357 // ---------------------------------------------------------------------
1358 /* The domain list is a comma separate list of domains that are suffix
1359 matched against the argument */
1360 bool CheckDomainList(const string
&Host
,const string
&List
)
1362 string::const_iterator Start
= List
.begin();
1363 for (string::const_iterator Cur
= List
.begin(); Cur
<= List
.end(); ++Cur
)
1365 if (Cur
< List
.end() && *Cur
!= ',')
1368 // Match the end of the string..
1369 if ((Host
.size() >= (unsigned)(Cur
- Start
)) &&
1371 stringcasecmp(Host
.end() - (Cur
- Start
),Host
.end(),Start
,Cur
) == 0)
1379 // strv_length - Return the length of a NULL-terminated string array /*{{{*/
1380 // ---------------------------------------------------------------------
1382 size_t strv_length(const char **str_array
)
1385 for (i
=0; str_array
[i
] != NULL
; i
++)
1391 // DeEscapeString - unescape (\0XX and \xXX) from a string /*{{{*/
1392 // ---------------------------------------------------------------------
1394 string
DeEscapeString(const string
&input
)
1397 string::const_iterator it
;
1399 for (it
= input
.begin(); it
!= input
.end(); ++it
)
1401 // just copy non-escape chars
1408 // deal with double escape
1410 (it
+ 1 < input
.end()) && it
[1] == '\\')
1414 // advance iterator one step further
1419 // ensure we have a char to read
1420 if (it
+ 1 == input
.end())
1428 if (it
+ 2 <= input
.end()) {
1432 output
+= (char)strtol(tmp
, 0, 8);
1437 if (it
+ 2 <= input
.end()) {
1441 output
+= (char)strtol(tmp
, 0, 16);
1446 // FIXME: raise exception here?
1453 // URI::CopyFrom - Copy from an object /*{{{*/
1454 // ---------------------------------------------------------------------
1455 /* This parses the URI into all of its components */
1456 void URI::CopyFrom(const string
&U
)
1458 string::const_iterator I
= U
.begin();
1460 // Locate the first colon, this separates the scheme
1461 for (; I
< U
.end() && *I
!= ':' ; ++I
);
1462 string::const_iterator FirstColon
= I
;
1464 /* Determine if this is a host type URI with a leading double //
1465 and then search for the first single / */
1466 string::const_iterator SingleSlash
= I
;
1467 if (I
+ 3 < U
.end() && I
[1] == '/' && I
[2] == '/')
1470 /* Find the / indicating the end of the hostname, ignoring /'s in the
1472 bool InBracket
= false;
1473 for (; SingleSlash
< U
.end() && (*SingleSlash
!= '/' || InBracket
== true); ++SingleSlash
)
1475 if (*SingleSlash
== '[')
1477 if (InBracket
== true && *SingleSlash
== ']')
1481 if (SingleSlash
> U
.end())
1482 SingleSlash
= U
.end();
1484 // We can now write the access and path specifiers
1485 Access
.assign(U
.begin(),FirstColon
);
1486 if (SingleSlash
!= U
.end())
1487 Path
.assign(SingleSlash
,U
.end());
1488 if (Path
.empty() == true)
1491 // Now we attempt to locate a user:pass@host fragment
1492 if (FirstColon
+ 2 <= U
.end() && FirstColon
[1] == '/' && FirstColon
[2] == '/')
1496 if (FirstColon
>= U
.end())
1499 if (FirstColon
> SingleSlash
)
1500 FirstColon
= SingleSlash
;
1502 // Find the colon...
1504 if (I
> SingleSlash
)
1506 for (; I
< SingleSlash
&& *I
!= ':'; ++I
);
1507 string::const_iterator SecondColon
= I
;
1509 // Search for the @ after the colon
1510 for (; I
< SingleSlash
&& *I
!= '@'; ++I
);
1511 string::const_iterator At
= I
;
1513 // Now write the host and user/pass
1514 if (At
== SingleSlash
)
1516 if (FirstColon
< SingleSlash
)
1517 Host
.assign(FirstColon
,SingleSlash
);
1521 Host
.assign(At
+1,SingleSlash
);
1522 // username and password must be encoded (RFC 3986)
1523 User
.assign(DeQuoteString(FirstColon
,SecondColon
));
1524 if (SecondColon
< At
)
1525 Password
.assign(DeQuoteString(SecondColon
+1,At
));
1528 // Now we parse the RFC 2732 [] hostnames.
1529 unsigned long PortEnd
= 0;
1531 for (unsigned I
= 0; I
!= Host
.length();)
1540 if (InBracket
== true && Host
[I
] == ']')
1551 if (InBracket
== true)
1557 // Now we parse off a port number from the hostname
1559 string::size_type Pos
= Host
.rfind(':');
1560 if (Pos
== string::npos
|| Pos
< PortEnd
)
1563 Port
= atoi(string(Host
,Pos
+1).c_str());
1564 Host
.assign(Host
,0,Pos
);
1567 // URI::operator string - Convert the URI to a string /*{{{*/
1568 // ---------------------------------------------------------------------
1570 URI::operator string()
1574 if (Access
.empty() == false)
1577 if (Host
.empty() == false)
1579 if (Access
.empty() == false)
1582 if (User
.empty() == false)
1584 // FIXME: Technically userinfo is permitted even less
1585 // characters than these, but this is not conveniently
1586 // expressed with a blacklist.
1587 Res
+= QuoteString(User
, ":/?#[]@");
1588 if (Password
.empty() == false)
1589 Res
+= ":" + QuoteString(Password
, ":/?#[]@");
1593 // Add RFC 2732 escaping characters
1594 if (Access
.empty() == false &&
1595 (Host
.find('/') != string::npos
|| Host
.find(':') != string::npos
))
1596 Res
+= '[' + Host
+ ']';
1603 sprintf(S
,":%u",Port
);
1608 if (Path
.empty() == false)
1619 // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
1620 // ---------------------------------------------------------------------
1622 string
URI::SiteOnly(const string
&URI
)
1631 // URI::NoUserPassword - Return the schema, site and path for the URI /*{{{*/
1632 // ---------------------------------------------------------------------
1634 string
URI::NoUserPassword(const string
&URI
)