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>
39 // Strip - Remove white space from the front and back of a string /*{{{*/
40 // ---------------------------------------------------------------------
43 std::string
Strip(const std::string
&s
)
45 size_t start
= s
.find_first_not_of(" \t\n");
47 if (start
== string::npos
)
49 size_t end
= s
.find_last_not_of(" \t\n");
50 return s
.substr(start
, end
-start
+1);
53 bool Endswith(const std::string
&s
, const std::string
&end
)
55 if (end
.size() > s
.size())
57 return (s
.substr(s
.size() - end
.size(), s
.size()) == end
);
63 // UTF8ToCodeset - Convert some UTF-8 string for some codeset /*{{{*/
64 // ---------------------------------------------------------------------
65 /* This is handy to use before display some information for enduser */
66 bool UTF8ToCodeset(const char *codeset
, const string
&orig
, string
*dest
)
71 size_t insize
, bufsize
;
74 cd
= iconv_open(codeset
, "UTF-8");
75 if (cd
== (iconv_t
)(-1)) {
76 // Something went wrong
78 _error
->Error("conversion from 'UTF-8' to '%s' not available",
86 insize
= bufsize
= orig
.size();
88 inptr
= (char *)inbuf
;
89 outbuf
= new char[bufsize
];
90 size_t lastError
= -1;
94 char *outptr
= outbuf
;
95 size_t outsize
= bufsize
;
96 size_t const err
= iconv(cd
, &inptr
, &insize
, &outptr
, &outsize
);
97 dest
->append(outbuf
, outptr
- outbuf
);
98 if (err
== (size_t)(-1))
105 // replace a series of unknown multibytes with a single "?"
106 if (lastError
!= insize
) {
107 lastError
= insize
- 1;
115 if (outptr
== outbuf
)
119 outbuf
= new char[bufsize
];
133 // strstrip - Remove white space from the front and back of a string /*{{{*/
134 // ---------------------------------------------------------------------
135 /* This is handy to use when parsing a file. It also removes \n's left
136 over from fgets and company */
137 char *_strstrip(char *String
)
139 for (;*String
!= 0 && (*String
== ' ' || *String
== '\t'); String
++);
143 return _strrstrip(String
);
146 // strrstrip - Remove white space from the back of a string /*{{{*/
147 // ---------------------------------------------------------------------
148 char *_strrstrip(char *String
)
150 char *End
= String
+ strlen(String
) - 1;
151 for (;End
!= String
- 1 && (*End
== ' ' || *End
== '\t' || *End
== '\n' ||
152 *End
== '\r'); End
--);
158 // strtabexpand - Converts tabs into 8 spaces /*{{{*/
159 // ---------------------------------------------------------------------
161 char *_strtabexpand(char *String
,size_t Len
)
163 for (char *I
= String
; I
!= I
+ Len
&& *I
!= 0; I
++)
167 if (I
+ 8 > String
+ Len
)
173 /* Assume the start of the string is 0 and find the next 8 char
179 Len
= 8 - ((String
- I
) % 8);
187 memmove(I
+ Len
,I
+ 1,strlen(I
) + 1);
188 for (char *J
= I
; J
+ Len
!= I
; *I
= ' ', I
++);
193 // ParseQuoteWord - Parse a single word out of a string /*{{{*/
194 // ---------------------------------------------------------------------
195 /* This grabs a single word, converts any % escaped characters to their
196 proper values and advances the pointer. Double quotes are understood
197 and striped out as well. This is for URI/URL parsing. It also can
198 understand [] brackets.*/
199 bool ParseQuoteWord(const char *&String
,string
&Res
)
201 // Skip leading whitespace
202 const char *C
= String
;
203 for (;*C
!= 0 && *C
== ' '; C
++);
207 // Jump to the next word
208 for (;*C
!= 0 && isspace(*C
) == 0; C
++)
212 C
= strchr(C
+ 1, '"');
218 C
= strchr(C
+ 1, ']');
224 // Now de-quote characters
227 const char *Start
= String
;
229 for (I
= Buffer
; I
< Buffer
+ sizeof(Buffer
) && Start
!= C
; I
++)
231 if (*Start
== '%' && Start
+ 2 < C
&&
232 isxdigit(Start
[1]) && isxdigit(Start
[2]))
237 *I
= (char)strtol(Tmp
,0,16);
250 // Skip ending white space
251 for (;*C
!= 0 && isspace(*C
) != 0; C
++);
256 // ParseCWord - Parses a string like a C "" expression /*{{{*/
257 // ---------------------------------------------------------------------
258 /* This expects a series of space separated strings enclosed in ""'s.
259 It concatenates the ""'s into a single string. */
260 bool ParseCWord(const char *&String
,string
&Res
)
262 // Skip leading whitespace
263 const char *C
= String
;
264 for (;*C
!= 0 && *C
== ' '; C
++);
270 if (strlen(String
) >= sizeof(Buffer
))
277 for (C
++; *C
!= 0 && *C
!= '"'; C
++)
286 if (C
!= String
&& isspace(*C
) != 0 && isspace(C
[-1]) != 0)
288 if (isspace(*C
) == 0)
298 // QuoteString - Convert a string into quoted from /*{{{*/
299 // ---------------------------------------------------------------------
301 string
QuoteString(const string
&Str
, const char *Bad
)
304 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end(); ++I
)
306 if (strchr(Bad
,*I
) != 0 || isprint(*I
) == 0 ||
307 *I
== 0x25 || // percent '%' char
308 *I
<= 0x20 || *I
>= 0x7F) // control chars
311 sprintf(Buf
,"%%%02x",(int)*I
);
320 // DeQuoteString - Convert a string from quoted from /*{{{*/
321 // ---------------------------------------------------------------------
322 /* This undoes QuoteString */
323 string
DeQuoteString(const string
&Str
)
325 return DeQuoteString(Str
.begin(),Str
.end());
327 string
DeQuoteString(string::const_iterator
const &begin
,
328 string::const_iterator
const &end
)
331 for (string::const_iterator I
= begin
; I
!= end
; ++I
)
333 if (*I
== '%' && I
+ 2 < end
&&
334 isxdigit(I
[1]) && isxdigit(I
[2]))
340 Res
+= (char)strtol(Tmp
,0,16);
351 // SizeToStr - Convert a long into a human readable size /*{{{*/
352 // ---------------------------------------------------------------------
353 /* A max of 4 digits are shown before conversion to the next highest unit.
354 The max length of the string will be 5 chars unless the size is > 10
356 string
SizeToStr(double Size
)
365 /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
366 ExaBytes, ZettaBytes, YottaBytes */
367 char Ext
[] = {'\0','k','M','G','T','P','E','Z','Y'};
371 if (ASize
< 100 && I
!= 0)
373 sprintf(S
,"%'.1f %c",ASize
,Ext
[I
]);
379 sprintf(S
,"%'.0f %c",ASize
,Ext
[I
]);
389 // TimeToStr - Convert the time into a string /*{{{*/
390 // ---------------------------------------------------------------------
391 /* Converts a number of seconds to a hms format */
392 string
TimeToStr(unsigned long Sec
)
400 //d means days, h means hours, min means minutes, s means seconds
401 sprintf(S
,_("%lid %lih %limin %lis"),Sec
/60/60/24,(Sec
/60/60) % 24,(Sec
/60) % 60,Sec
% 60);
407 //h means hours, min means minutes, s means seconds
408 sprintf(S
,_("%lih %limin %lis"),Sec
/60/60,(Sec
/60) % 60,Sec
% 60);
414 //min means minutes, s means seconds
415 sprintf(S
,_("%limin %lis"),Sec
/60,Sec
% 60);
420 sprintf(S
,_("%lis"),Sec
);
427 // SubstVar - Substitute a string for another string /*{{{*/
428 // ---------------------------------------------------------------------
429 /* This replaces all occurrences of Subst with Contents in Str. */
430 string
SubstVar(const string
&Str
,const string
&Subst
,const string
&Contents
)
432 string::size_type Pos
= 0;
433 string::size_type OldPos
= 0;
436 while (OldPos
< Str
.length() &&
437 (Pos
= Str
.find(Subst
,OldPos
)) != string::npos
)
439 Temp
+= string(Str
,OldPos
,Pos
) + Contents
;
440 OldPos
= Pos
+ Subst
.length();
446 return Temp
+ string(Str
,OldPos
);
449 string
SubstVar(string Str
,const struct SubstVar
*Vars
)
451 for (; Vars
->Subst
!= 0; Vars
++)
452 Str
= SubstVar(Str
,Vars
->Subst
,*Vars
->Contents
);
456 // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
457 // ---------------------------------------------------------------------
458 /* Returns a string with the supplied separator depth + 1 times in it */
459 std::string
OutputInDepth(const unsigned long Depth
, const char* Separator
)
461 std::string output
= "";
462 for(unsigned long d
=Depth
+1; d
> 0; d
--)
463 output
.append(Separator
);
467 // URItoFileName - Convert the uri into a unique file name /*{{{*/
468 // ---------------------------------------------------------------------
469 /* This converts a URI into a safe filename. It quotes all unsafe characters
470 and converts / to _ and removes the scheme identifier. The resulting
471 file name should be unique and never occur again for a different file */
472 string
URItoFileName(const string
&URI
)
474 // Nuke 'sensitive' items
480 // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
481 string NewURI
= QuoteString(U
,"\\|{}[]<>\"^~_=!@#$%^&*");
482 replace(NewURI
.begin(),NewURI
.end(),'/','_');
486 // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
487 // ---------------------------------------------------------------------
488 /* This routine performs a base64 transformation on a string. It was ripped
489 from wget and then patched and bug fixed.
491 This spec can be found in rfc2045 */
492 string
Base64Encode(const string
&S
)
495 static char tbl
[64] = {'A','B','C','D','E','F','G','H',
496 'I','J','K','L','M','N','O','P',
497 'Q','R','S','T','U','V','W','X',
498 'Y','Z','a','b','c','d','e','f',
499 'g','h','i','j','k','l','m','n',
500 'o','p','q','r','s','t','u','v',
501 'w','x','y','z','0','1','2','3',
502 '4','5','6','7','8','9','+','/'};
504 // Pre-allocate some space
506 Final
.reserve((4*S
.length() + 2)/3 + 2);
508 /* Transform the 3x8 bits to 4x6 bits, as required by
510 for (string::const_iterator I
= S
.begin(); I
< S
.end(); I
+= 3)
512 char Bits
[3] = {0,0,0};
519 Final
+= tbl
[Bits
[0] >> 2];
520 Final
+= tbl
[((Bits
[0] & 3) << 4) + (Bits
[1] >> 4)];
522 if (I
+ 1 >= S
.end())
525 Final
+= tbl
[((Bits
[1] & 0xf) << 2) + (Bits
[2] >> 6)];
527 if (I
+ 2 >= S
.end())
530 Final
+= tbl
[Bits
[2] & 0x3f];
533 /* Apply the padding elements, this tells how many bytes the remote
534 end should discard */
535 if (S
.length() % 3 == 2)
537 if (S
.length() % 3 == 1)
543 // stringcmp - Arbitrary string compare /*{{{*/
544 // ---------------------------------------------------------------------
545 /* This safely compares two non-null terminated strings of arbitrary
547 int stringcmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
549 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
553 if (A
== AEnd
&& B
== BEnd
)
565 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
566 const char *B
,const char *BEnd
)
568 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
572 if (A
== AEnd
&& B
== BEnd
)
582 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
583 string::const_iterator B
,string::const_iterator BEnd
)
585 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
589 if (A
== AEnd
&& B
== BEnd
)
601 // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
602 // ---------------------------------------------------------------------
604 int stringcasecmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
606 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
607 if (tolower_ascii(*A
) != tolower_ascii(*B
))
610 if (A
== AEnd
&& B
== BEnd
)
616 if (tolower_ascii(*A
) < tolower_ascii(*B
))
621 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
622 const char *B
,const char *BEnd
)
624 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
625 if (tolower_ascii(*A
) != tolower_ascii(*B
))
628 if (A
== AEnd
&& B
== BEnd
)
634 if (tolower_ascii(*A
) < tolower_ascii(*B
))
638 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
639 string::const_iterator B
,string::const_iterator BEnd
)
641 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
642 if (tolower_ascii(*A
) != tolower_ascii(*B
))
645 if (A
== AEnd
&& B
== BEnd
)
651 if (tolower_ascii(*A
) < tolower_ascii(*B
))
657 // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
658 // ---------------------------------------------------------------------
659 /* The format is like those used in package files and the method
660 communication system */
661 string
LookupTag(const string
&Message
,const char *Tag
,const char *Default
)
663 // Look for a matching tag.
664 int Length
= strlen(Tag
);
665 for (string::const_iterator I
= Message
.begin(); I
+ Length
< Message
.end(); ++I
)
668 if (I
[Length
] == ':' && stringcasecmp(I
,I
+Length
,Tag
) == 0)
670 // Find the end of line and strip the leading/trailing spaces
671 string::const_iterator J
;
673 for (; isspace(*I
) != 0 && I
< Message
.end(); ++I
);
674 for (J
= I
; *J
!= '\n' && J
< Message
.end(); ++J
);
675 for (; J
> I
&& isspace(J
[-1]) != 0; --J
);
680 for (; *I
!= '\n' && I
< Message
.end(); ++I
);
683 // Failed to find a match
689 // StringToBool - Converts a string into a boolean /*{{{*/
690 // ---------------------------------------------------------------------
691 /* This inspects the string to see if it is true or if it is false and
692 then returns the result. Several varients on true/false are checked. */
693 int StringToBool(const string
&Text
,int Default
)
696 int Res
= strtol(Text
.c_str(),&End
,0);
697 if (End
!= Text
.c_str() && Res
>= 0 && Res
<= 1)
700 // Check for positives
701 if (strcasecmp(Text
.c_str(),"no") == 0 ||
702 strcasecmp(Text
.c_str(),"false") == 0 ||
703 strcasecmp(Text
.c_str(),"without") == 0 ||
704 strcasecmp(Text
.c_str(),"off") == 0 ||
705 strcasecmp(Text
.c_str(),"disable") == 0)
708 // Check for negatives
709 if (strcasecmp(Text
.c_str(),"yes") == 0 ||
710 strcasecmp(Text
.c_str(),"true") == 0 ||
711 strcasecmp(Text
.c_str(),"with") == 0 ||
712 strcasecmp(Text
.c_str(),"on") == 0 ||
713 strcasecmp(Text
.c_str(),"enable") == 0)
719 // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
720 // ---------------------------------------------------------------------
721 /* This converts a time_t into a string time representation that is
722 year 2000 complient and timezone neutral */
723 string
TimeRFC1123(time_t Date
)
726 if (gmtime_r(&Date
, &Conv
) == NULL
)
730 const char *Day
[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
731 const char *Month
[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
732 "Aug","Sep","Oct","Nov","Dec"};
734 snprintf(Buf
, sizeof(Buf
), "%s, %02i %s %i %02i:%02i:%02i GMT",Day
[Conv
.tm_wday
],
735 Conv
.tm_mday
,Month
[Conv
.tm_mon
],Conv
.tm_year
+1900,Conv
.tm_hour
,
736 Conv
.tm_min
,Conv
.tm_sec
);
740 // ReadMessages - Read messages from the FD /*{{{*/
741 // ---------------------------------------------------------------------
742 /* This pulls full messages from the input FD into the message buffer.
743 It assumes that messages will not pause during transit so no
744 fancy buffering is used.
746 In particular: this reads blocks from the input until it believes
747 that it's run out of input text. Each block is terminated by a
748 double newline ('\n' followed by '\n'). As noted below, there is a
749 bug in this code: it assumes that all the blocks have been read if
750 it doesn't see additional text in the buffer after the last one is
751 parsed, which will cause it to lose blocks if the last block
752 coincides with the end of the buffer.
754 bool ReadMessages(int Fd
, vector
<string
> &List
)
758 // Represents any left-over from the previous iteration of the
759 // parse loop. (i.e., if a message is split across the end
760 // of the buffer, it goes here)
761 string PartialMessage
;
765 int Res
= read(Fd
,End
,sizeof(Buffer
) - (End
-Buffer
));
766 if (Res
< 0 && errno
== EINTR
)
769 // Process is dead, this is kind of bad..
774 if (Res
< 0 && errno
== EAGAIN
)
781 // Look for the end of the message
782 for (char *I
= Buffer
; I
+ 1 < End
; I
++)
785 (I
[0] != '\n' && strncmp(I
, "\r\n\r\n", 4) != 0))
788 // Pull the message out
789 string
Message(Buffer
,I
-Buffer
);
790 PartialMessage
+= Message
;
793 for (; I
< End
&& (*I
== '\n' || *I
== '\r'); ++I
);
795 memmove(Buffer
,I
,End
-Buffer
);
798 List
.push_back(PartialMessage
);
799 PartialMessage
.clear();
803 // If there's text left in the buffer, store it
804 // in PartialMessage and throw the rest of the buffer
805 // away. This allows us to handle messages that
806 // are longer than the static buffer size.
807 PartialMessage
+= string(Buffer
, End
);
812 // BUG ALERT: if a message block happens to end at a
813 // multiple of 64000 characters, this will cause it to
814 // terminate early, leading to a badly formed block and
815 // probably crashing the method. However, this is the only
816 // way we have to find the end of the message block. I have
817 // an idea of how to fix this, but it will require changes
818 // to the protocol (essentially to mark the beginning and
819 // end of the block).
821 // -- dburrows 2008-04-02
825 if (WaitFd(Fd
) == false)
830 // MonthConv - Converts a month string into a number /*{{{*/
831 // ---------------------------------------------------------------------
832 /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
833 Made it a bit more robust with a few tolower_ascii though. */
834 static int MonthConv(char *Month
)
836 switch (tolower_ascii(*Month
))
839 return tolower_ascii(Month
[1]) == 'p'?3:7;
845 if (tolower_ascii(Month
[1]) == 'a')
847 return tolower_ascii(Month
[2]) == 'n'?5:6;
849 return tolower_ascii(Month
[2]) == 'r'?2:4;
857 // Pretend it is January..
863 // timegm - Internal timegm if the gnu version is not available /*{{{*/
864 // ---------------------------------------------------------------------
865 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
866 than local timezone (mktime assumes the latter).
868 This function is a nonstandard GNU extension that is also present on
869 the BSDs and maybe other systems. For others we follow the advice of
870 the manpage of timegm and use his portable replacement. */
872 static time_t timegm(struct tm
*t
)
874 char *tz
= getenv("TZ");
877 time_t ret
= mktime(t
);
887 // FullDateToTime - Converts a HTTP1.1 full date strings into a time_t /*{{{*/
888 // ---------------------------------------------------------------------
889 /* tries to parses a full date as specified in RFC2616 Section 3.3.1
890 with one exception: All timezones (%Z) are accepted but the protocol
891 says that it MUST be GMT, but this one is equal to UTC which we will
892 encounter from time to time (e.g. in Release files) so we accept all
893 here and just assume it is GMT (or UTC) later on */
894 bool RFC1123StrToTime(const char* const str
,time_t &time
)
897 setlocale (LC_ALL
,"C");
899 // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
900 (strptime(str
, "%a, %d %b %Y %H:%M:%S %Z", &Tm
) == NULL
&&
901 // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
902 strptime(str
, "%A, %d-%b-%y %H:%M:%S %Z", &Tm
) == NULL
&&
903 // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
904 strptime(str
, "%a %b %d %H:%M:%S %Y", &Tm
) == NULL
);
905 setlocale (LC_ALL
,"");
913 // FTPMDTMStrToTime - Converts a ftp modification date into a time_t /*{{{*/
914 // ---------------------------------------------------------------------
916 bool FTPMDTMStrToTime(const char* const str
,time_t &time
)
919 // MDTM includes no whitespaces but recommend and ignored by strptime
920 if (strptime(str
, "%Y %m %d %H %M %S", &Tm
) == NULL
)
927 // StrToTime - Converts a string into a time_t /*{{{*/
928 // ---------------------------------------------------------------------
929 /* This handles all 3 popular time formats including RFC 1123, RFC 1036
930 and the C library asctime format. It requires the GNU library function
931 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
932 reason the C library does not provide any such function :< This also
933 handles the weird, but unambiguous FTP time format*/
934 bool StrToTime(const string
&Val
,time_t &Result
)
939 // Skip the day of the week
940 const char *I
= strchr(Val
.c_str(), ' ');
942 // Handle RFC 1123 time
944 if (sscanf(I
," %2d %3s %4d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,&Tm
.tm_year
,
945 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
947 // Handle RFC 1036 time
948 if (sscanf(I
," %2d-%3s-%3d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,
949 &Tm
.tm_year
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) == 6)
954 if (sscanf(I
," %3s %2d %2d:%2d:%2d %4d",Month
,&Tm
.tm_mday
,
955 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
,&Tm
.tm_year
) != 6)
958 if (sscanf(Val
.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm
.tm_year
,&Tm
.tm_mon
,
959 &Tm
.tm_mday
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
968 Tm
.tm_mon
= MonthConv(Month
);
970 Tm
.tm_mon
= 0; // we don't have a month, so pick something
973 // Convert to local time and then to GMT
974 Result
= timegm(&Tm
);
978 // StrToNum - Convert a fixed length string to a number /*{{{*/
979 // ---------------------------------------------------------------------
980 /* This is used in decoding the crazy fixed length string headers in
982 bool StrToNum(const char *Str
,unsigned long &Res
,unsigned Len
,unsigned Base
)
985 if (Len
>= sizeof(S
))
990 // All spaces is a zero
993 for (I
= 0; S
[I
] == ' '; I
++);
998 Res
= strtoul(S
,&End
,Base
);
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 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
= strtoull(S
,&End
,Base
);
1033 // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
1034 // ---------------------------------------------------------------------
1035 /* This is used in decoding the 256bit encoded fixed length fields in
1037 bool Base256ToNum(const char *Str
,unsigned long &Res
,unsigned int Len
)
1039 if ((Str
[0] & 0x80) == 0)
1043 Res
= Str
[0] & 0x7F;
1044 for(unsigned int i
= 1; i
< Len
; ++i
)
1045 Res
= (Res
<<8) + Str
[i
];
1050 // HexDigit - Convert a hex character into an integer /*{{{*/
1051 // ---------------------------------------------------------------------
1052 /* Helper for Hex2Num */
1053 static int HexDigit(int c
)
1055 if (c
>= '0' && c
<= '9')
1057 if (c
>= 'a' && c
<= 'f')
1058 return c
- 'a' + 10;
1059 if (c
>= 'A' && c
<= 'F')
1060 return c
- 'A' + 10;
1064 // Hex2Num - Convert a long hex number into a buffer /*{{{*/
1065 // ---------------------------------------------------------------------
1066 /* The length of the buffer must be exactly 1/2 the length of the string. */
1067 bool Hex2Num(const string
&Str
,unsigned char *Num
,unsigned int Length
)
1069 if (Str
.length() != Length
*2)
1072 // Convert each digit. We store it in the same order as the string
1074 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end();J
++, I
+= 2)
1076 if (isxdigit(*I
) == 0 || isxdigit(I
[1]) == 0)
1079 Num
[J
] = HexDigit(I
[0]) << 4;
1080 Num
[J
] += HexDigit(I
[1]);
1086 // TokSplitString - Split a string up by a given token /*{{{*/
1087 // ---------------------------------------------------------------------
1088 /* This is intended to be a faster splitter, it does not use dynamic
1089 memories. Input is changed to insert nulls at each token location. */
1090 bool TokSplitString(char Tok
,char *Input
,char **List
,
1091 unsigned long ListMax
)
1093 // Strip any leading spaces
1094 char *Start
= Input
;
1095 char *Stop
= Start
+ strlen(Start
);
1096 for (; *Start
!= 0 && isspace(*Start
) != 0; Start
++);
1098 unsigned long Count
= 0;
1102 // Skip to the next Token
1103 for (; Pos
!= Stop
&& *Pos
!= Tok
; Pos
++);
1105 // Back remove spaces
1107 for (; End
> Start
&& (End
[-1] == Tok
|| isspace(End
[-1]) != 0); End
--);
1110 List
[Count
++] = Start
;
1111 if (Count
>= ListMax
)
1118 for (; Pos
!= Stop
&& (*Pos
== Tok
|| isspace(*Pos
) != 0 || *Pos
== 0); Pos
++);
1126 // VectorizeString - Split a string up into a vector of strings /*{{{*/
1127 // ---------------------------------------------------------------------
1128 /* This can be used to split a given string up into a vector, so the
1129 propose is the same as in the method above and this one is a bit slower
1130 also, but the advantage is that we have an iteratable vector */
1131 vector
<string
> VectorizeString(string
const &haystack
, char const &split
)
1133 vector
<string
> exploded
;
1134 if (haystack
.empty() == true)
1136 string::const_iterator start
= haystack
.begin();
1137 string::const_iterator end
= start
;
1139 for (; end
!= haystack
.end() && *end
!= split
; ++end
);
1140 exploded
.push_back(string(start
, end
));
1142 } while (end
!= haystack
.end() && (++end
) != haystack
.end());
1146 // StringSplit - split a string into a string vector by token /*{{{*/
1147 // ---------------------------------------------------------------------
1148 /* See header for details.
1150 vector
<string
> StringSplit(std::string
const &s
, std::string
const &sep
,
1151 unsigned int maxsplit
)
1153 vector
<string
> split
;
1156 // no seperator given, this is bogus
1161 while (pos
!= string::npos
)
1163 pos
= s
.find(sep
, start
);
1164 split
.push_back(s
.substr(start
, pos
-start
));
1166 // if maxsplit is reached, the remaining string is the last item
1167 if(split
.size() >= maxsplit
)
1169 split
[split
.size()-1] = s
.substr(start
);
1172 start
= pos
+sep
.size();
1177 // RegexChoice - Simple regex list/list matcher /*{{{*/
1178 // ---------------------------------------------------------------------
1180 unsigned long RegexChoice(RxChoiceList
*Rxs
,const char **ListBegin
,
1181 const char **ListEnd
)
1183 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1186 unsigned long Hits
= 0;
1187 for (; ListBegin
!= ListEnd
; ListBegin
++)
1189 // Check if the name is a regex
1192 for (I
= *ListBegin
; *I
!= 0; I
++)
1193 if (*I
== '.' || *I
== '?' || *I
== '*' || *I
== '|')
1198 // Compile the regex pattern
1201 if (regcomp(&Pattern
,*ListBegin
,REG_EXTENDED
| REG_ICASE
|
1207 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1212 if (strcasecmp(R
->Str
,*ListBegin
) != 0)
1216 if (regexec(&Pattern
,R
->Str
,0,0,0) != 0)
1221 if (R
->Hit
== false)
1231 _error
->Warning(_("Selection %s not found"),*ListBegin
);
1237 // {str,io}printf - C format string outputter to C++ strings/iostreams /*{{{*/
1238 // ---------------------------------------------------------------------
1239 /* This is used to make the internationalization strings easier to translate
1240 and to allow reordering of parameters */
1241 static bool iovprintf(ostream
&out
, const char *format
,
1242 va_list &args
, ssize_t
&size
) {
1243 char *S
= (char*)malloc(size
);
1244 ssize_t
const n
= vsnprintf(S
, size
, format
, args
);
1245 if (n
> -1 && n
< size
) {
1258 void ioprintf(ostream
&out
,const char *format
,...)
1263 va_start(args
,format
);
1264 if (iovprintf(out
, format
, args
, size
) == true)
1269 void strprintf(string
&out
,const char *format
,...)
1273 std::ostringstream outstr
;
1275 va_start(args
,format
);
1276 if (iovprintf(outstr
, format
, args
, size
) == true)
1283 // safe_snprintf - Safer snprintf /*{{{*/
1284 // ---------------------------------------------------------------------
1285 /* This is a snprintf that will never (ever) go past 'End' and returns a
1286 pointer to the end of the new string. The returned string is always null
1287 terminated unless Buffer == end. This is a better alterantive to using
1288 consecutive snprintfs. */
1289 char *safe_snprintf(char *Buffer
,char *End
,const char *Format
,...)
1296 va_start(args
,Format
);
1297 Did
= vsnprintf(Buffer
,End
- Buffer
,Format
,args
);
1300 if (Did
< 0 || Buffer
+ Did
> End
)
1302 return Buffer
+ Did
;
1305 // StripEpoch - Remove the version "epoch" from a version string /*{{{*/
1306 // ---------------------------------------------------------------------
1307 string
StripEpoch(const string
&VerStr
)
1309 size_t i
= VerStr
.find(":");
1310 if (i
== string::npos
)
1312 return VerStr
.substr(i
+1);
1315 // tolower_ascii - tolower() function that ignores the locale /*{{{*/
1316 // ---------------------------------------------------------------------
1317 /* This little function is the most called method we have and tries
1318 therefore to do the absolut minimum - and is notable faster than
1319 standard tolower/toupper and as a bonus avoids problems with different
1320 locales - we only operate on ascii chars anyway. */
1321 int tolower_ascii(int const c
)
1323 if (c
>= 'A' && c
<= 'Z')
1329 // CheckDomainList - See if Host is in a , separate list /*{{{*/
1330 // ---------------------------------------------------------------------
1331 /* The domain list is a comma separate list of domains that are suffix
1332 matched against the argument */
1333 bool CheckDomainList(const string
&Host
,const string
&List
)
1335 string::const_iterator Start
= List
.begin();
1336 for (string::const_iterator Cur
= List
.begin(); Cur
<= List
.end(); ++Cur
)
1338 if (Cur
< List
.end() && *Cur
!= ',')
1341 // Match the end of the string..
1342 if ((Host
.size() >= (unsigned)(Cur
- Start
)) &&
1344 stringcasecmp(Host
.end() - (Cur
- Start
),Host
.end(),Start
,Cur
) == 0)
1352 // strv_length - Return the length of a NULL-terminated string array /*{{{*/
1353 // ---------------------------------------------------------------------
1355 size_t strv_length(const char **str_array
)
1358 for (i
=0; str_array
[i
] != NULL
; i
++)
1364 // DeEscapeString - unescape (\0XX and \xXX) from a string /*{{{*/
1365 // ---------------------------------------------------------------------
1367 string
DeEscapeString(const string
&input
)
1370 string::const_iterator it
;
1372 for (it
= input
.begin(); it
!= input
.end(); ++it
)
1374 // just copy non-escape chars
1381 // deal with double escape
1383 (it
+ 1 < input
.end()) && it
[1] == '\\')
1387 // advance iterator one step further
1392 // ensure we have a char to read
1393 if (it
+ 1 == input
.end())
1401 if (it
+ 2 <= input
.end()) {
1405 output
+= (char)strtol(tmp
, 0, 8);
1410 if (it
+ 2 <= input
.end()) {
1414 output
+= (char)strtol(tmp
, 0, 16);
1419 // FIXME: raise exception here?
1426 // URI::CopyFrom - Copy from an object /*{{{*/
1427 // ---------------------------------------------------------------------
1428 /* This parses the URI into all of its components */
1429 void URI::CopyFrom(const string
&U
)
1431 string::const_iterator I
= U
.begin();
1433 // Locate the first colon, this separates the scheme
1434 for (; I
< U
.end() && *I
!= ':' ; ++I
);
1435 string::const_iterator FirstColon
= I
;
1437 /* Determine if this is a host type URI with a leading double //
1438 and then search for the first single / */
1439 string::const_iterator SingleSlash
= I
;
1440 if (I
+ 3 < U
.end() && I
[1] == '/' && I
[2] == '/')
1443 /* Find the / indicating the end of the hostname, ignoring /'s in the
1445 bool InBracket
= false;
1446 for (; SingleSlash
< U
.end() && (*SingleSlash
!= '/' || InBracket
== true); ++SingleSlash
)
1448 if (*SingleSlash
== '[')
1450 if (InBracket
== true && *SingleSlash
== ']')
1454 if (SingleSlash
> U
.end())
1455 SingleSlash
= U
.end();
1457 // We can now write the access and path specifiers
1458 Access
.assign(U
.begin(),FirstColon
);
1459 if (SingleSlash
!= U
.end())
1460 Path
.assign(SingleSlash
,U
.end());
1461 if (Path
.empty() == true)
1464 // Now we attempt to locate a user:pass@host fragment
1465 if (FirstColon
+ 2 <= U
.end() && FirstColon
[1] == '/' && FirstColon
[2] == '/')
1469 if (FirstColon
>= U
.end())
1472 if (FirstColon
> SingleSlash
)
1473 FirstColon
= SingleSlash
;
1475 // Find the colon...
1477 if (I
> SingleSlash
)
1479 for (; I
< SingleSlash
&& *I
!= ':'; ++I
);
1480 string::const_iterator SecondColon
= I
;
1482 // Search for the @ after the colon
1483 for (; I
< SingleSlash
&& *I
!= '@'; ++I
);
1484 string::const_iterator At
= I
;
1486 // Now write the host and user/pass
1487 if (At
== SingleSlash
)
1489 if (FirstColon
< SingleSlash
)
1490 Host
.assign(FirstColon
,SingleSlash
);
1494 Host
.assign(At
+1,SingleSlash
);
1495 // username and password must be encoded (RFC 3986)
1496 User
.assign(DeQuoteString(FirstColon
,SecondColon
));
1497 if (SecondColon
< At
)
1498 Password
.assign(DeQuoteString(SecondColon
+1,At
));
1501 // Now we parse the RFC 2732 [] hostnames.
1502 unsigned long PortEnd
= 0;
1504 for (unsigned I
= 0; I
!= Host
.length();)
1513 if (InBracket
== true && Host
[I
] == ']')
1524 if (InBracket
== true)
1530 // Now we parse off a port number from the hostname
1532 string::size_type Pos
= Host
.rfind(':');
1533 if (Pos
== string::npos
|| Pos
< PortEnd
)
1536 Port
= atoi(string(Host
,Pos
+1).c_str());
1537 Host
.assign(Host
,0,Pos
);
1540 // URI::operator string - Convert the URI to a string /*{{{*/
1541 // ---------------------------------------------------------------------
1543 URI::operator string()
1547 if (Access
.empty() == false)
1550 if (Host
.empty() == false)
1552 if (Access
.empty() == false)
1555 if (User
.empty() == false)
1557 // FIXME: Technically userinfo is permitted even less
1558 // characters than these, but this is not conveniently
1559 // expressed with a blacklist.
1560 Res
+= QuoteString(User
, ":/?#[]@");
1561 if (Password
.empty() == false)
1562 Res
+= ":" + QuoteString(Password
, ":/?#[]@");
1566 // Add RFC 2732 escaping characters
1567 if (Access
.empty() == false &&
1568 (Host
.find('/') != string::npos
|| Host
.find(':') != string::npos
))
1569 Res
+= '[' + Host
+ ']';
1576 sprintf(S
,":%u",Port
);
1581 if (Path
.empty() == false)
1592 // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
1593 // ---------------------------------------------------------------------
1595 string
URI::SiteOnly(const string
&URI
)
1604 // URI::NoUserPassword - Return the schema, site and path for the URI /*{{{*/
1605 // ---------------------------------------------------------------------
1607 string
URI::NoUserPassword(const string
&URI
)