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
&s
)
50 size_t start
= s
.find_first_not_of(" \t\n");
52 if (start
== string::npos
)
54 size_t end
= s
.find_last_not_of(" \t\n");
55 return s
.substr(start
, end
-start
+1);
58 bool Endswith(const std::string
&s
, const std::string
&end
)
60 if (end
.size() > s
.size())
62 return (s
.substr(s
.size() - end
.size(), s
.size()) == end
);
68 // UTF8ToCodeset - Convert some UTF-8 string for some codeset /*{{{*/
69 // ---------------------------------------------------------------------
70 /* This is handy to use before display some information for enduser */
71 bool UTF8ToCodeset(const char *codeset
, const string
&orig
, string
*dest
)
76 size_t insize
, bufsize
;
79 cd
= iconv_open(codeset
, "UTF-8");
80 if (cd
== (iconv_t
)(-1)) {
81 // Something went wrong
83 _error
->Error("conversion from 'UTF-8' to '%s' not available",
91 insize
= bufsize
= orig
.size();
93 inptr
= (char *)inbuf
;
94 outbuf
= new char[bufsize
];
95 size_t lastError
= -1;
99 char *outptr
= outbuf
;
100 size_t outsize
= bufsize
;
101 size_t const err
= iconv(cd
, &inptr
, &insize
, &outptr
, &outsize
);
102 dest
->append(outbuf
, outptr
- outbuf
);
103 if (err
== (size_t)(-1))
110 // replace a series of unknown multibytes with a single "?"
111 if (lastError
!= insize
) {
112 lastError
= insize
- 1;
120 if (outptr
== outbuf
)
124 outbuf
= new char[bufsize
];
138 // strstrip - Remove white space from the front and back of a string /*{{{*/
139 // ---------------------------------------------------------------------
140 /* This is handy to use when parsing a file. It also removes \n's left
141 over from fgets and company */
142 char *_strstrip(char *String
)
144 for (;*String
!= 0 && (*String
== ' ' || *String
== '\t'); String
++);
148 return _strrstrip(String
);
151 // strrstrip - Remove white space from the back of a string /*{{{*/
152 // ---------------------------------------------------------------------
153 char *_strrstrip(char *String
)
155 char *End
= String
+ strlen(String
) - 1;
156 for (;End
!= String
- 1 && (*End
== ' ' || *End
== '\t' || *End
== '\n' ||
157 *End
== '\r'); End
--);
163 // strtabexpand - Converts tabs into 8 spaces /*{{{*/
164 // ---------------------------------------------------------------------
166 char *_strtabexpand(char *String
,size_t Len
)
168 for (char *I
= String
; I
!= I
+ Len
&& *I
!= 0; I
++)
172 if (I
+ 8 > String
+ Len
)
178 /* Assume the start of the string is 0 and find the next 8 char
184 Len
= 8 - ((String
- I
) % 8);
192 memmove(I
+ Len
,I
+ 1,strlen(I
) + 1);
193 for (char *J
= I
; J
+ Len
!= I
; *I
= ' ', I
++);
198 // ParseQuoteWord - Parse a single word out of a string /*{{{*/
199 // ---------------------------------------------------------------------
200 /* This grabs a single word, converts any % escaped characters to their
201 proper values and advances the pointer. Double quotes are understood
202 and striped out as well. This is for URI/URL parsing. It also can
203 understand [] brackets.*/
204 bool ParseQuoteWord(const char *&String
,string
&Res
)
206 // Skip leading whitespace
207 const char *C
= String
;
208 for (;*C
!= 0 && *C
== ' '; C
++);
212 // Jump to the next word
213 for (;*C
!= 0 && isspace(*C
) == 0; C
++)
217 C
= strchr(C
+ 1, '"');
223 C
= strchr(C
+ 1, ']');
229 // Now de-quote characters
232 const char *Start
= String
;
234 for (I
= Buffer
; I
< Buffer
+ sizeof(Buffer
) && Start
!= C
; I
++)
236 if (*Start
== '%' && Start
+ 2 < C
&&
237 isxdigit(Start
[1]) && isxdigit(Start
[2]))
242 *I
= (char)strtol(Tmp
,0,16);
255 // Skip ending white space
256 for (;*C
!= 0 && isspace(*C
) != 0; C
++);
261 // ParseCWord - Parses a string like a C "" expression /*{{{*/
262 // ---------------------------------------------------------------------
263 /* This expects a series of space separated strings enclosed in ""'s.
264 It concatenates the ""'s into a single string. */
265 bool ParseCWord(const char *&String
,string
&Res
)
267 // Skip leading whitespace
268 const char *C
= String
;
269 for (;*C
!= 0 && *C
== ' '; C
++);
275 if (strlen(String
) >= sizeof(Buffer
))
282 for (C
++; *C
!= 0 && *C
!= '"'; C
++)
291 if (C
!= String
&& isspace(*C
) != 0 && isspace(C
[-1]) != 0)
293 if (isspace(*C
) == 0)
303 // QuoteString - Convert a string into quoted from /*{{{*/
304 // ---------------------------------------------------------------------
306 string
QuoteString(const string
&Str
, const char *Bad
)
309 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end(); ++I
)
311 if (strchr(Bad
,*I
) != 0 || isprint(*I
) == 0 ||
312 *I
== 0x25 || // percent '%' char
313 *I
<= 0x20 || *I
>= 0x7F) // control chars
316 sprintf(Buf
,"%%%02x",(int)*I
);
325 // DeQuoteString - Convert a string from quoted from /*{{{*/
326 // ---------------------------------------------------------------------
327 /* This undoes QuoteString */
328 string
DeQuoteString(const string
&Str
)
330 return DeQuoteString(Str
.begin(),Str
.end());
332 string
DeQuoteString(string::const_iterator
const &begin
,
333 string::const_iterator
const &end
)
336 for (string::const_iterator I
= begin
; I
!= end
; ++I
)
338 if (*I
== '%' && I
+ 2 < end
&&
339 isxdigit(I
[1]) && isxdigit(I
[2]))
345 Res
+= (char)strtol(Tmp
,0,16);
356 // SizeToStr - Convert a long into a human readable size /*{{{*/
357 // ---------------------------------------------------------------------
358 /* A max of 4 digits are shown before conversion to the next highest unit.
359 The max length of the string will be 5 chars unless the size is > 10
361 string
SizeToStr(double Size
)
370 /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
371 ExaBytes, ZettaBytes, YottaBytes */
372 char Ext
[] = {'\0','k','M','G','T','P','E','Z','Y'};
376 if (ASize
< 100 && I
!= 0)
378 sprintf(S
,"%'.1f %c",ASize
,Ext
[I
]);
384 sprintf(S
,"%'.0f %c",ASize
,Ext
[I
]);
394 // TimeToStr - Convert the time into a string /*{{{*/
395 // ---------------------------------------------------------------------
396 /* Converts a number of seconds to a hms format */
397 string
TimeToStr(unsigned long Sec
)
405 //d means days, h means hours, min means minutes, s means seconds
406 sprintf(S
,_("%lid %lih %limin %lis"),Sec
/60/60/24,(Sec
/60/60) % 24,(Sec
/60) % 60,Sec
% 60);
412 //h means hours, min means minutes, s means seconds
413 sprintf(S
,_("%lih %limin %lis"),Sec
/60/60,(Sec
/60) % 60,Sec
% 60);
419 //min means minutes, s means seconds
420 sprintf(S
,_("%limin %lis"),Sec
/60,Sec
% 60);
425 sprintf(S
,_("%lis"),Sec
);
432 // SubstVar - Substitute a string for another string /*{{{*/
433 // ---------------------------------------------------------------------
434 /* This replaces all occurrences of Subst with Contents in Str. */
435 string
SubstVar(const string
&Str
,const string
&Subst
,const string
&Contents
)
437 if (Subst
.empty() == true)
440 string::size_type Pos
= 0;
441 string::size_type OldPos
= 0;
444 while (OldPos
< Str
.length() &&
445 (Pos
= Str
.find(Subst
,OldPos
)) != string::npos
)
448 Temp
.append(Str
, OldPos
, Pos
- OldPos
);
449 if (Contents
.empty() == false)
450 Temp
.append(Contents
);
451 OldPos
= Pos
+ Subst
.length();
457 if (OldPos
>= Str
.length())
459 return Temp
+ string(Str
,OldPos
);
461 string
SubstVar(string Str
,const struct SubstVar
*Vars
)
463 for (; Vars
->Subst
!= 0; Vars
++)
464 Str
= SubstVar(Str
,Vars
->Subst
,*Vars
->Contents
);
468 // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
469 // ---------------------------------------------------------------------
470 /* Returns a string with the supplied separator depth + 1 times in it */
471 std::string
OutputInDepth(const unsigned long Depth
, const char* Separator
)
473 std::string output
= "";
474 for(unsigned long d
=Depth
+1; d
> 0; d
--)
475 output
.append(Separator
);
479 // URItoFileName - Convert the uri into a unique file name /*{{{*/
480 // ---------------------------------------------------------------------
481 /* This converts a URI into a safe filename. It quotes all unsafe characters
482 and converts / to _ and removes the scheme identifier. The resulting
483 file name should be unique and never occur again for a different file */
484 string
URItoFileName(const string
&URI
)
486 // Nuke 'sensitive' items
492 // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
493 string NewURI
= QuoteString(U
,"\\|{}[]<>\"^~_=!@#$%^&*");
494 replace(NewURI
.begin(),NewURI
.end(),'/','_');
498 // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
499 // ---------------------------------------------------------------------
500 /* This routine performs a base64 transformation on a string. It was ripped
501 from wget and then patched and bug fixed.
503 This spec can be found in rfc2045 */
504 string
Base64Encode(const string
&S
)
507 static char tbl
[64] = {'A','B','C','D','E','F','G','H',
508 'I','J','K','L','M','N','O','P',
509 'Q','R','S','T','U','V','W','X',
510 'Y','Z','a','b','c','d','e','f',
511 'g','h','i','j','k','l','m','n',
512 'o','p','q','r','s','t','u','v',
513 'w','x','y','z','0','1','2','3',
514 '4','5','6','7','8','9','+','/'};
516 // Pre-allocate some space
518 Final
.reserve((4*S
.length() + 2)/3 + 2);
520 /* Transform the 3x8 bits to 4x6 bits, as required by
522 for (string::const_iterator I
= S
.begin(); I
< S
.end(); I
+= 3)
524 char Bits
[3] = {0,0,0};
531 Final
+= tbl
[Bits
[0] >> 2];
532 Final
+= tbl
[((Bits
[0] & 3) << 4) + (Bits
[1] >> 4)];
534 if (I
+ 1 >= S
.end())
537 Final
+= tbl
[((Bits
[1] & 0xf) << 2) + (Bits
[2] >> 6)];
539 if (I
+ 2 >= S
.end())
542 Final
+= tbl
[Bits
[2] & 0x3f];
545 /* Apply the padding elements, this tells how many bytes the remote
546 end should discard */
547 if (S
.length() % 3 == 2)
549 if (S
.length() % 3 == 1)
555 // stringcmp - Arbitrary string compare /*{{{*/
556 // ---------------------------------------------------------------------
557 /* This safely compares two non-null terminated strings of arbitrary
559 int stringcmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
561 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
565 if (A
== AEnd
&& B
== BEnd
)
577 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
578 const char *B
,const char *BEnd
)
580 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
584 if (A
== AEnd
&& B
== BEnd
)
594 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
595 string::const_iterator B
,string::const_iterator BEnd
)
597 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
601 if (A
== AEnd
&& B
== BEnd
)
613 // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
614 // ---------------------------------------------------------------------
616 int stringcasecmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
618 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
619 if (tolower_ascii(*A
) != tolower_ascii(*B
))
622 if (A
== AEnd
&& B
== BEnd
)
628 if (tolower_ascii(*A
) < tolower_ascii(*B
))
633 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
634 const char *B
,const char *BEnd
)
636 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
637 if (tolower_ascii(*A
) != tolower_ascii(*B
))
640 if (A
== AEnd
&& B
== BEnd
)
646 if (tolower_ascii(*A
) < tolower_ascii(*B
))
650 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
651 string::const_iterator B
,string::const_iterator BEnd
)
653 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
654 if (tolower_ascii(*A
) != tolower_ascii(*B
))
657 if (A
== AEnd
&& B
== BEnd
)
663 if (tolower_ascii(*A
) < tolower_ascii(*B
))
669 // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
670 // ---------------------------------------------------------------------
671 /* The format is like those used in package files and the method
672 communication system */
673 string
LookupTag(const string
&Message
,const char *Tag
,const char *Default
)
675 // Look for a matching tag.
676 int Length
= strlen(Tag
);
677 for (string::const_iterator I
= Message
.begin(); I
+ Length
< Message
.end(); ++I
)
680 if (I
[Length
] == ':' && stringcasecmp(I
,I
+Length
,Tag
) == 0)
682 // Find the end of line and strip the leading/trailing spaces
683 string::const_iterator J
;
685 for (; isspace(*I
) != 0 && I
< Message
.end(); ++I
);
686 for (J
= I
; *J
!= '\n' && J
< Message
.end(); ++J
);
687 for (; J
> I
&& isspace(J
[-1]) != 0; --J
);
692 for (; *I
!= '\n' && I
< Message
.end(); ++I
);
695 // Failed to find a match
701 // StringToBool - Converts a string into a boolean /*{{{*/
702 // ---------------------------------------------------------------------
703 /* This inspects the string to see if it is true or if it is false and
704 then returns the result. Several varients on true/false are checked. */
705 int StringToBool(const string
&Text
,int Default
)
708 int Res
= strtol(Text
.c_str(),&End
,0);
709 if (End
!= Text
.c_str() && Res
>= 0 && Res
<= 1)
712 // Check for positives
713 if (strcasecmp(Text
.c_str(),"no") == 0 ||
714 strcasecmp(Text
.c_str(),"false") == 0 ||
715 strcasecmp(Text
.c_str(),"without") == 0 ||
716 strcasecmp(Text
.c_str(),"off") == 0 ||
717 strcasecmp(Text
.c_str(),"disable") == 0)
720 // Check for negatives
721 if (strcasecmp(Text
.c_str(),"yes") == 0 ||
722 strcasecmp(Text
.c_str(),"true") == 0 ||
723 strcasecmp(Text
.c_str(),"with") == 0 ||
724 strcasecmp(Text
.c_str(),"on") == 0 ||
725 strcasecmp(Text
.c_str(),"enable") == 0)
731 // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
732 // ---------------------------------------------------------------------
733 /* This converts a time_t into a string time representation that is
734 year 2000 complient and timezone neutral */
735 string
TimeRFC1123(time_t Date
)
738 if (gmtime_r(&Date
, &Conv
) == NULL
)
742 const char *Day
[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
743 const char *Month
[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
744 "Aug","Sep","Oct","Nov","Dec"};
746 snprintf(Buf
, sizeof(Buf
), "%s, %02i %s %i %02i:%02i:%02i GMT",Day
[Conv
.tm_wday
],
747 Conv
.tm_mday
,Month
[Conv
.tm_mon
],Conv
.tm_year
+1900,Conv
.tm_hour
,
748 Conv
.tm_min
,Conv
.tm_sec
);
752 // ReadMessages - Read messages from the FD /*{{{*/
753 // ---------------------------------------------------------------------
754 /* This pulls full messages from the input FD into the message buffer.
755 It assumes that messages will not pause during transit so no
756 fancy buffering is used.
758 In particular: this reads blocks from the input until it believes
759 that it's run out of input text. Each block is terminated by a
760 double newline ('\n' followed by '\n'). As noted below, there is a
761 bug in this code: it assumes that all the blocks have been read if
762 it doesn't see additional text in the buffer after the last one is
763 parsed, which will cause it to lose blocks if the last block
764 coincides with the end of the buffer.
766 bool ReadMessages(int Fd
, vector
<string
> &List
)
770 // Represents any left-over from the previous iteration of the
771 // parse loop. (i.e., if a message is split across the end
772 // of the buffer, it goes here)
773 string PartialMessage
;
777 int Res
= read(Fd
,End
,sizeof(Buffer
) - (End
-Buffer
));
778 if (Res
< 0 && errno
== EINTR
)
781 // Process is dead, this is kind of bad..
786 if (Res
< 0 && errno
== EAGAIN
)
793 // Look for the end of the message
794 for (char *I
= Buffer
; I
+ 1 < End
; I
++)
797 (I
[0] != '\n' && strncmp(I
, "\r\n\r\n", 4) != 0))
800 // Pull the message out
801 string
Message(Buffer
,I
-Buffer
);
802 PartialMessage
+= Message
;
805 for (; I
< End
&& (*I
== '\n' || *I
== '\r'); ++I
);
807 memmove(Buffer
,I
,End
-Buffer
);
810 List
.push_back(PartialMessage
);
811 PartialMessage
.clear();
815 // If there's text left in the buffer, store it
816 // in PartialMessage and throw the rest of the buffer
817 // away. This allows us to handle messages that
818 // are longer than the static buffer size.
819 PartialMessage
+= string(Buffer
, End
);
824 // BUG ALERT: if a message block happens to end at a
825 // multiple of 64000 characters, this will cause it to
826 // terminate early, leading to a badly formed block and
827 // probably crashing the method. However, this is the only
828 // way we have to find the end of the message block. I have
829 // an idea of how to fix this, but it will require changes
830 // to the protocol (essentially to mark the beginning and
831 // end of the block).
833 // -- dburrows 2008-04-02
837 if (WaitFd(Fd
) == false)
842 // MonthConv - Converts a month string into a number /*{{{*/
843 // ---------------------------------------------------------------------
844 /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
845 Made it a bit more robust with a few tolower_ascii though. */
846 static int MonthConv(char *Month
)
848 switch (tolower_ascii(*Month
))
851 return tolower_ascii(Month
[1]) == 'p'?3:7;
857 if (tolower_ascii(Month
[1]) == 'a')
859 return tolower_ascii(Month
[2]) == 'n'?5:6;
861 return tolower_ascii(Month
[2]) == 'r'?2:4;
869 // Pretend it is January..
875 // timegm - Internal timegm if the gnu version is not available /*{{{*/
876 // ---------------------------------------------------------------------
877 /* Converts struct tm to time_t, assuming the data in tm is UTC rather
878 than local timezone (mktime assumes the latter).
880 This function is a nonstandard GNU extension that is also present on
881 the BSDs and maybe other systems. For others we follow the advice of
882 the manpage of timegm and use his portable replacement. */
884 static time_t timegm(struct tm
*t
)
886 char *tz
= getenv("TZ");
889 time_t ret
= mktime(t
);
899 // FullDateToTime - Converts a HTTP1.1 full date strings into a time_t /*{{{*/
900 // ---------------------------------------------------------------------
901 /* tries to parses a full date as specified in RFC2616 Section 3.3.1
902 with one exception: All timezones (%Z) are accepted but the protocol
903 says that it MUST be GMT, but this one is equal to UTC which we will
904 encounter from time to time (e.g. in Release files) so we accept all
905 here and just assume it is GMT (or UTC) later on */
906 bool RFC1123StrToTime(const char* const str
,time_t &time
)
909 setlocale (LC_ALL
,"C");
911 // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
912 (strptime(str
, "%a, %d %b %Y %H:%M:%S %Z", &Tm
) == NULL
&&
913 // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
914 strptime(str
, "%A, %d-%b-%y %H:%M:%S %Z", &Tm
) == NULL
&&
915 // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
916 strptime(str
, "%a %b %d %H:%M:%S %Y", &Tm
) == NULL
);
917 setlocale (LC_ALL
,"");
925 // FTPMDTMStrToTime - Converts a ftp modification date into a time_t /*{{{*/
926 // ---------------------------------------------------------------------
928 bool FTPMDTMStrToTime(const char* const str
,time_t &time
)
931 // MDTM includes no whitespaces but recommend and ignored by strptime
932 if (strptime(str
, "%Y %m %d %H %M %S", &Tm
) == NULL
)
939 // StrToTime - Converts a string into a time_t /*{{{*/
940 // ---------------------------------------------------------------------
941 /* This handles all 3 popular time formats including RFC 1123, RFC 1036
942 and the C library asctime format. It requires the GNU library function
943 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
944 reason the C library does not provide any such function :< This also
945 handles the weird, but unambiguous FTP time format*/
946 bool StrToTime(const string
&Val
,time_t &Result
)
951 // Skip the day of the week
952 const char *I
= strchr(Val
.c_str(), ' ');
954 // Handle RFC 1123 time
956 if (sscanf(I
," %2d %3s %4d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,&Tm
.tm_year
,
957 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
959 // Handle RFC 1036 time
960 if (sscanf(I
," %2d-%3s-%3d %2d:%2d:%2d GMT",&Tm
.tm_mday
,Month
,
961 &Tm
.tm_year
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) == 6)
966 if (sscanf(I
," %3s %2d %2d:%2d:%2d %4d",Month
,&Tm
.tm_mday
,
967 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
,&Tm
.tm_year
) != 6)
970 if (sscanf(Val
.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm
.tm_year
,&Tm
.tm_mon
,
971 &Tm
.tm_mday
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
980 Tm
.tm_mon
= MonthConv(Month
);
982 Tm
.tm_mon
= 0; // we don't have a month, so pick something
985 // Convert to local time and then to GMT
986 Result
= timegm(&Tm
);
990 // StrToNum - Convert a fixed length string to a number /*{{{*/
991 // ---------------------------------------------------------------------
992 /* This is used in decoding the crazy fixed length string headers in
994 bool StrToNum(const char *Str
,unsigned long &Res
,unsigned Len
,unsigned Base
)
997 if (Len
>= sizeof(S
))
1002 // All spaces is a zero
1005 for (I
= 0; S
[I
] == ' '; I
++);
1010 Res
= strtoul(S
,&End
,Base
);
1017 // StrToNum - Convert a fixed length string to a number /*{{{*/
1018 // ---------------------------------------------------------------------
1019 /* This is used in decoding the crazy fixed length string headers in
1020 tar and ar files. */
1021 bool StrToNum(const char *Str
,unsigned long long &Res
,unsigned Len
,unsigned Base
)
1024 if (Len
>= sizeof(S
))
1029 // All spaces is a zero
1032 for (I
= 0; S
[I
] == ' '; I
++);
1037 Res
= strtoull(S
,&End
,Base
);
1045 // Base256ToNum - Convert a fixed length binary to a number /*{{{*/
1046 // ---------------------------------------------------------------------
1047 /* This is used in decoding the 256bit encoded fixed length fields in
1049 bool Base256ToNum(const char *Str
,unsigned long &Res
,unsigned int Len
)
1051 if ((Str
[0] & 0x80) == 0)
1055 Res
= Str
[0] & 0x7F;
1056 for(unsigned int i
= 1; i
< Len
; ++i
)
1057 Res
= (Res
<<8) + Str
[i
];
1062 // HexDigit - Convert a hex character into an integer /*{{{*/
1063 // ---------------------------------------------------------------------
1064 /* Helper for Hex2Num */
1065 static int HexDigit(int c
)
1067 if (c
>= '0' && c
<= '9')
1069 if (c
>= 'a' && c
<= 'f')
1070 return c
- 'a' + 10;
1071 if (c
>= 'A' && c
<= 'F')
1072 return c
- 'A' + 10;
1076 // Hex2Num - Convert a long hex number into a buffer /*{{{*/
1077 // ---------------------------------------------------------------------
1078 /* The length of the buffer must be exactly 1/2 the length of the string. */
1079 bool Hex2Num(const string
&Str
,unsigned char *Num
,unsigned int Length
)
1081 if (Str
.length() != Length
*2)
1084 // Convert each digit. We store it in the same order as the string
1086 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end();J
++, I
+= 2)
1088 if (isxdigit(*I
) == 0 || isxdigit(I
[1]) == 0)
1091 Num
[J
] = HexDigit(I
[0]) << 4;
1092 Num
[J
] += HexDigit(I
[1]);
1098 // TokSplitString - Split a string up by a given token /*{{{*/
1099 // ---------------------------------------------------------------------
1100 /* This is intended to be a faster splitter, it does not use dynamic
1101 memories. Input is changed to insert nulls at each token location. */
1102 bool TokSplitString(char Tok
,char *Input
,char **List
,
1103 unsigned long ListMax
)
1105 // Strip any leading spaces
1106 char *Start
= Input
;
1107 char *Stop
= Start
+ strlen(Start
);
1108 for (; *Start
!= 0 && isspace(*Start
) != 0; Start
++);
1110 unsigned long Count
= 0;
1114 // Skip to the next Token
1115 for (; Pos
!= Stop
&& *Pos
!= Tok
; Pos
++);
1117 // Back remove spaces
1119 for (; End
> Start
&& (End
[-1] == Tok
|| isspace(End
[-1]) != 0); End
--);
1122 List
[Count
++] = Start
;
1123 if (Count
>= ListMax
)
1130 for (; Pos
!= Stop
&& (*Pos
== Tok
|| isspace(*Pos
) != 0 || *Pos
== 0); Pos
++);
1138 // VectorizeString - Split a string up into a vector of strings /*{{{*/
1139 // ---------------------------------------------------------------------
1140 /* This can be used to split a given string up into a vector, so the
1141 propose is the same as in the method above and this one is a bit slower
1142 also, but the advantage is that we have an iteratable vector */
1143 vector
<string
> VectorizeString(string
const &haystack
, char const &split
)
1145 vector
<string
> exploded
;
1146 if (haystack
.empty() == true)
1148 string::const_iterator start
= haystack
.begin();
1149 string::const_iterator end
= start
;
1151 for (; end
!= haystack
.end() && *end
!= split
; ++end
);
1152 exploded
.push_back(string(start
, end
));
1154 } while (end
!= haystack
.end() && (++end
) != haystack
.end());
1158 // StringSplit - split a string into a string vector by token /*{{{*/
1159 // ---------------------------------------------------------------------
1160 /* See header for details.
1162 vector
<string
> StringSplit(std::string
const &s
, std::string
const &sep
,
1163 unsigned int maxsplit
)
1165 vector
<string
> split
;
1168 // no seperator given, this is bogus
1173 while (pos
!= string::npos
)
1175 pos
= s
.find(sep
, start
);
1176 split
.push_back(s
.substr(start
, pos
-start
));
1178 // if maxsplit is reached, the remaining string is the last item
1179 if(split
.size() >= maxsplit
)
1181 split
[split
.size()-1] = s
.substr(start
);
1184 start
= pos
+sep
.size();
1189 // RegexChoice - Simple regex list/list matcher /*{{{*/
1190 // ---------------------------------------------------------------------
1192 unsigned long RegexChoice(RxChoiceList
*Rxs
,const char **ListBegin
,
1193 const char **ListEnd
)
1195 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1198 unsigned long Hits
= 0;
1199 for (; ListBegin
< ListEnd
; ++ListBegin
)
1201 // Check if the name is a regex
1204 for (I
= *ListBegin
; *I
!= 0; I
++)
1205 if (*I
== '.' || *I
== '?' || *I
== '*' || *I
== '|')
1210 // Compile the regex pattern
1213 if (regcomp(&Pattern
,*ListBegin
,REG_EXTENDED
| REG_ICASE
|
1219 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1224 if (strcasecmp(R
->Str
,*ListBegin
) != 0)
1228 if (regexec(&Pattern
,R
->Str
,0,0,0) != 0)
1233 if (R
->Hit
== false)
1243 _error
->Warning(_("Selection %s not found"),*ListBegin
);
1249 // {str,io}printf - C format string outputter to C++ strings/iostreams /*{{{*/
1250 // ---------------------------------------------------------------------
1251 /* This is used to make the internationalization strings easier to translate
1252 and to allow reordering of parameters */
1253 static bool iovprintf(ostream
&out
, const char *format
,
1254 va_list &args
, ssize_t
&size
) {
1255 char *S
= (char*)malloc(size
);
1256 ssize_t
const n
= vsnprintf(S
, size
, format
, args
);
1257 if (n
> -1 && n
< size
) {
1270 void ioprintf(ostream
&out
,const char *format
,...)
1275 va_start(args
,format
);
1276 if (iovprintf(out
, format
, args
, size
) == true)
1281 void strprintf(string
&out
,const char *format
,...)
1285 std::ostringstream outstr
;
1287 va_start(args
,format
);
1288 if (iovprintf(outstr
, format
, args
, size
) == true)
1295 // safe_snprintf - Safer snprintf /*{{{*/
1296 // ---------------------------------------------------------------------
1297 /* This is a snprintf that will never (ever) go past 'End' and returns a
1298 pointer to the end of the new string. The returned string is always null
1299 terminated unless Buffer == end. This is a better alterantive to using
1300 consecutive snprintfs. */
1301 char *safe_snprintf(char *Buffer
,char *End
,const char *Format
,...)
1308 va_start(args
,Format
);
1309 Did
= vsnprintf(Buffer
,End
- Buffer
,Format
,args
);
1312 if (Did
< 0 || Buffer
+ Did
> End
)
1314 return Buffer
+ Did
;
1317 // StripEpoch - Remove the version "epoch" from a version string /*{{{*/
1318 // ---------------------------------------------------------------------
1319 string
StripEpoch(const string
&VerStr
)
1321 size_t i
= VerStr
.find(":");
1322 if (i
== string::npos
)
1324 return VerStr
.substr(i
+1);
1327 // tolower_ascii - tolower() function that ignores the locale /*{{{*/
1328 // ---------------------------------------------------------------------
1329 /* This little function is the most called method we have and tries
1330 therefore to do the absolut minimum - and is notable faster than
1331 standard tolower/toupper and as a bonus avoids problems with different
1332 locales - we only operate on ascii chars anyway. */
1333 int tolower_ascii(int const c
)
1335 if (c
>= 'A' && c
<= 'Z')
1341 // CheckDomainList - See if Host is in a , separate list /*{{{*/
1342 // ---------------------------------------------------------------------
1343 /* The domain list is a comma separate list of domains that are suffix
1344 matched against the argument */
1345 bool CheckDomainList(const string
&Host
,const string
&List
)
1347 string::const_iterator Start
= List
.begin();
1348 for (string::const_iterator Cur
= List
.begin(); Cur
<= List
.end(); ++Cur
)
1350 if (Cur
< List
.end() && *Cur
!= ',')
1353 // Match the end of the string..
1354 if ((Host
.size() >= (unsigned)(Cur
- Start
)) &&
1356 stringcasecmp(Host
.end() - (Cur
- Start
),Host
.end(),Start
,Cur
) == 0)
1364 // strv_length - Return the length of a NULL-terminated string array /*{{{*/
1365 // ---------------------------------------------------------------------
1367 size_t strv_length(const char **str_array
)
1370 for (i
=0; str_array
[i
] != NULL
; i
++)
1376 // DeEscapeString - unescape (\0XX and \xXX) from a string /*{{{*/
1377 // ---------------------------------------------------------------------
1379 string
DeEscapeString(const string
&input
)
1382 string::const_iterator it
;
1384 for (it
= input
.begin(); it
!= input
.end(); ++it
)
1386 // just copy non-escape chars
1393 // deal with double escape
1395 (it
+ 1 < input
.end()) && it
[1] == '\\')
1399 // advance iterator one step further
1404 // ensure we have a char to read
1405 if (it
+ 1 == input
.end())
1413 if (it
+ 2 <= input
.end()) {
1417 output
+= (char)strtol(tmp
, 0, 8);
1422 if (it
+ 2 <= input
.end()) {
1426 output
+= (char)strtol(tmp
, 0, 16);
1431 // FIXME: raise exception here?
1438 // URI::CopyFrom - Copy from an object /*{{{*/
1439 // ---------------------------------------------------------------------
1440 /* This parses the URI into all of its components */
1441 void URI::CopyFrom(const string
&U
)
1443 string::const_iterator I
= U
.begin();
1445 // Locate the first colon, this separates the scheme
1446 for (; I
< U
.end() && *I
!= ':' ; ++I
);
1447 string::const_iterator FirstColon
= I
;
1449 /* Determine if this is a host type URI with a leading double //
1450 and then search for the first single / */
1451 string::const_iterator SingleSlash
= I
;
1452 if (I
+ 3 < U
.end() && I
[1] == '/' && I
[2] == '/')
1455 /* Find the / indicating the end of the hostname, ignoring /'s in the
1457 bool InBracket
= false;
1458 for (; SingleSlash
< U
.end() && (*SingleSlash
!= '/' || InBracket
== true); ++SingleSlash
)
1460 if (*SingleSlash
== '[')
1462 if (InBracket
== true && *SingleSlash
== ']')
1466 if (SingleSlash
> U
.end())
1467 SingleSlash
= U
.end();
1469 // We can now write the access and path specifiers
1470 Access
.assign(U
.begin(),FirstColon
);
1471 if (SingleSlash
!= U
.end())
1472 Path
.assign(SingleSlash
,U
.end());
1473 if (Path
.empty() == true)
1476 // Now we attempt to locate a user:pass@host fragment
1477 if (FirstColon
+ 2 <= U
.end() && FirstColon
[1] == '/' && FirstColon
[2] == '/')
1481 if (FirstColon
>= U
.end())
1484 if (FirstColon
> SingleSlash
)
1485 FirstColon
= SingleSlash
;
1487 // Find the colon...
1489 if (I
> SingleSlash
)
1491 for (; I
< SingleSlash
&& *I
!= ':'; ++I
);
1492 string::const_iterator SecondColon
= I
;
1494 // Search for the @ after the colon
1495 for (; I
< SingleSlash
&& *I
!= '@'; ++I
);
1496 string::const_iterator At
= I
;
1498 // Now write the host and user/pass
1499 if (At
== SingleSlash
)
1501 if (FirstColon
< SingleSlash
)
1502 Host
.assign(FirstColon
,SingleSlash
);
1506 Host
.assign(At
+1,SingleSlash
);
1507 // username and password must be encoded (RFC 3986)
1508 User
.assign(DeQuoteString(FirstColon
,SecondColon
));
1509 if (SecondColon
< At
)
1510 Password
.assign(DeQuoteString(SecondColon
+1,At
));
1513 // Now we parse the RFC 2732 [] hostnames.
1514 unsigned long PortEnd
= 0;
1516 for (unsigned I
= 0; I
!= Host
.length();)
1525 if (InBracket
== true && Host
[I
] == ']')
1536 if (InBracket
== true)
1542 // Now we parse off a port number from the hostname
1544 string::size_type Pos
= Host
.rfind(':');
1545 if (Pos
== string::npos
|| Pos
< PortEnd
)
1548 Port
= atoi(string(Host
,Pos
+1).c_str());
1549 Host
.assign(Host
,0,Pos
);
1552 // URI::operator string - Convert the URI to a string /*{{{*/
1553 // ---------------------------------------------------------------------
1555 URI::operator string()
1559 if (Access
.empty() == false)
1562 if (Host
.empty() == false)
1564 if (Access
.empty() == false)
1567 if (User
.empty() == false)
1569 // FIXME: Technically userinfo is permitted even less
1570 // characters than these, but this is not conveniently
1571 // expressed with a blacklist.
1572 Res
+= QuoteString(User
, ":/?#[]@");
1573 if (Password
.empty() == false)
1574 Res
+= ":" + QuoteString(Password
, ":/?#[]@");
1578 // Add RFC 2732 escaping characters
1579 if (Access
.empty() == false &&
1580 (Host
.find('/') != string::npos
|| Host
.find(':') != string::npos
))
1581 Res
+= '[' + Host
+ ']';
1588 sprintf(S
,":%u",Port
);
1593 if (Path
.empty() == false)
1604 // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
1605 // ---------------------------------------------------------------------
1607 string
URI::SiteOnly(const string
&URI
)
1616 // URI::NoUserPassword - Return the schema, site and path for the URI /*{{{*/
1617 // ---------------------------------------------------------------------
1619 string
URI::NoUserPassword(const string
&URI
)