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 ##################################################################### */
18 #include <apt-pkg/strutl.h>
19 #include <apt-pkg/fileutl.h>
20 #include <apt-pkg/error.h>
39 // UTF8ToCodeset - Convert some UTF-8 string for some codeset /*{{{*/
40 // ---------------------------------------------------------------------
41 /* This is handy to use before display some information for enduser */
42 bool UTF8ToCodeset(const char *codeset
, const string
&orig
, string
*dest
)
46 char *inptr
, *outbuf
, *outptr
;
47 size_t insize
, outsize
;
49 cd
= iconv_open(codeset
, "UTF-8");
50 if (cd
== (iconv_t
)(-1)) {
51 // Something went wrong
53 _error
->Error("conversion from 'UTF-8' to '%s' not available",
58 // Clean the destination string
64 insize
= outsize
= orig
.size();
66 inptr
= (char *)inbuf
;
67 outbuf
= new char[insize
+1];
70 iconv(cd
, &inptr
, &insize
, &outptr
, &outsize
);
81 // strstrip - Remove white space from the front and back of a string /*{{{*/
82 // ---------------------------------------------------------------------
83 /* This is handy to use when parsing a file. It also removes \n's left
84 over from fgets and company */
85 char *_strstrip(char *String
)
87 for (;*String
!= 0 && (*String
== ' ' || *String
== '\t'); String
++);
92 char *End
= String
+ strlen(String
) - 1;
93 for (;End
!= String
- 1 && (*End
== ' ' || *End
== '\t' || *End
== '\n' ||
94 *End
== '\r'); End
--);
100 // strtabexpand - Converts tabs into 8 spaces /*{{{*/
101 // ---------------------------------------------------------------------
103 char *_strtabexpand(char *String
,size_t Len
)
105 for (char *I
= String
; I
!= I
+ Len
&& *I
!= 0; I
++)
109 if (I
+ 8 > String
+ Len
)
115 /* Assume the start of the string is 0 and find the next 8 char
121 Len
= 8 - ((String
- I
) % 8);
129 memmove(I
+ Len
,I
+ 1,strlen(I
) + 1);
130 for (char *J
= I
; J
+ Len
!= I
; *I
= ' ', I
++);
135 // ParseQuoteWord - Parse a single word out of a string /*{{{*/
136 // ---------------------------------------------------------------------
137 /* This grabs a single word, converts any % escaped characters to their
138 proper values and advances the pointer. Double quotes are understood
139 and striped out as well. This is for URI/URL parsing. It also can
140 understand [] brackets.*/
141 bool ParseQuoteWord(const char *&String
,string
&Res
)
143 // Skip leading whitespace
144 const char *C
= String
;
145 for (;*C
!= 0 && *C
== ' '; C
++);
149 // Jump to the next word
150 for (;*C
!= 0 && isspace(*C
) == 0; C
++)
154 for (C
++; *C
!= 0 && *C
!= '"'; C
++);
160 for (C
++; *C
!= 0 && *C
!= ']'; C
++);
166 // Now de-quote characters
169 const char *Start
= String
;
171 for (I
= Buffer
; I
< Buffer
+ sizeof(Buffer
) && Start
!= C
; I
++)
173 if (*Start
== '%' && Start
+ 2 < C
)
178 *I
= (char)strtol(Tmp
,0,16);
191 // Skip ending white space
192 for (;*C
!= 0 && isspace(*C
) != 0; C
++);
197 // ParseCWord - Parses a string like a C "" expression /*{{{*/
198 // ---------------------------------------------------------------------
199 /* This expects a series of space separated strings enclosed in ""'s.
200 It concatenates the ""'s into a single string. */
201 bool ParseCWord(const char *&String
,string
&Res
)
203 // Skip leading whitespace
204 const char *C
= String
;
205 for (;*C
!= 0 && *C
== ' '; C
++);
211 if (strlen(String
) >= sizeof(Buffer
))
218 for (C
++; *C
!= 0 && *C
!= '"'; C
++)
227 if (C
!= String
&& isspace(*C
) != 0 && isspace(C
[-1]) != 0)
229 if (isspace(*C
) == 0)
239 // QuoteString - Convert a string into quoted from /*{{{*/
240 // ---------------------------------------------------------------------
242 string
QuoteString(const string
&Str
, const char *Bad
)
245 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end(); I
++)
247 if (strchr(Bad
,*I
) != 0 || isprint(*I
) == 0 ||
248 *I
<= 0x20 || *I
>= 0x7F)
251 sprintf(Buf
,"%%%02x",(int)*I
);
260 // DeQuoteString - Convert a string from quoted from /*{{{*/
261 // ---------------------------------------------------------------------
262 /* This undoes QuoteString */
263 string
DeQuoteString(const string
&Str
)
266 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end(); I
++)
268 if (*I
== '%' && I
+ 2 < Str
.end())
274 Res
+= (char)strtol(Tmp
,0,16);
285 // SizeToStr - Convert a long into a human readable size /*{{{*/
286 // ---------------------------------------------------------------------
287 /* A max of 4 digits are shown before conversion to the next highest unit.
288 The max length of the string will be 5 chars unless the size is > 10
290 string
SizeToStr(double Size
)
299 /* bytes, KiloBytes, MegaBytes, GigaBytes, TeraBytes, PetaBytes,
300 ExaBytes, ZettaBytes, YottaBytes */
301 char Ext
[] = {'\0','k','M','G','T','P','E','Z','Y'};
305 if (ASize
< 100 && I
!= 0)
307 sprintf(S
,"%'.1f%c",ASize
,Ext
[I
]);
313 sprintf(S
,"%'.0f%c",ASize
,Ext
[I
]);
323 // TimeToStr - Convert the time into a string /*{{{*/
324 // ---------------------------------------------------------------------
325 /* Converts a number of seconds to a hms format */
326 string
TimeToStr(unsigned long Sec
)
334 //d means days, h means hours, min means minutes, s means seconds
335 sprintf(S
,_("%lid %lih %limin %lis"),Sec
/60/60/24,(Sec
/60/60) % 24,(Sec
/60) % 60,Sec
% 60);
341 //h means hours, min means minutes, s means seconds
342 sprintf(S
,_("%lih %limin %lis"),Sec
/60/60,(Sec
/60) % 60,Sec
% 60);
348 //min means minutes, s means seconds
349 sprintf(S
,_("%limin %lis"),Sec
/60,Sec
% 60);
354 sprintf(S
,_("%lis"),Sec
);
361 // SubstVar - Substitute a string for another string /*{{{*/
362 // ---------------------------------------------------------------------
363 /* This replaces all occurances of Subst with Contents in Str. */
364 string
SubstVar(const string
&Str
,const string
&Subst
,const string
&Contents
)
366 string::size_type Pos
= 0;
367 string::size_type OldPos
= 0;
370 while (OldPos
< Str
.length() &&
371 (Pos
= Str
.find(Subst
,OldPos
)) != string::npos
)
373 Temp
+= string(Str
,OldPos
,Pos
) + Contents
;
374 OldPos
= Pos
+ Subst
.length();
380 return Temp
+ string(Str
,OldPos
);
383 string
SubstVar(string Str
,const struct SubstVar
*Vars
)
385 for (; Vars
->Subst
!= 0; Vars
++)
386 Str
= SubstVar(Str
,Vars
->Subst
,*Vars
->Contents
);
390 // OutputInDepth - return a string with separator multiplied with depth /*{{{*/
391 // ---------------------------------------------------------------------
392 /* Returns a string with the supplied separator depth + 1 times in it */
393 std::string
OutputInDepth(const unsigned long Depth
, const char* Separator
)
395 std::string output
= "";
396 for(unsigned long d
=Depth
+1; d
> 0; d
--)
397 output
.append(Separator
);
401 // URItoFileName - Convert the uri into a unique file name /*{{{*/
402 // ---------------------------------------------------------------------
403 /* This converts a URI into a safe filename. It quotes all unsafe characters
404 and converts / to _ and removes the scheme identifier. The resulting
405 file name should be unique and never occur again for a different file */
406 string
URItoFileName(const string
&URI
)
408 // Nuke 'sensitive' items
414 // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
415 string NewURI
= QuoteString(U
,"\\|{}[]<>\"^~_=!@#$%^&*");
416 replace(NewURI
.begin(),NewURI
.end(),'/','_');
420 // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
421 // ---------------------------------------------------------------------
422 /* This routine performs a base64 transformation on a string. It was ripped
423 from wget and then patched and bug fixed.
425 This spec can be found in rfc2045 */
426 string
Base64Encode(const string
&S
)
429 static char tbl
[64] = {'A','B','C','D','E','F','G','H',
430 'I','J','K','L','M','N','O','P',
431 'Q','R','S','T','U','V','W','X',
432 'Y','Z','a','b','c','d','e','f',
433 'g','h','i','j','k','l','m','n',
434 'o','p','q','r','s','t','u','v',
435 'w','x','y','z','0','1','2','3',
436 '4','5','6','7','8','9','+','/'};
438 // Pre-allocate some space
440 Final
.reserve((4*S
.length() + 2)/3 + 2);
442 /* Transform the 3x8 bits to 4x6 bits, as required by
444 for (string::const_iterator I
= S
.begin(); I
< S
.end(); I
+= 3)
446 char Bits
[3] = {0,0,0};
453 Final
+= tbl
[Bits
[0] >> 2];
454 Final
+= tbl
[((Bits
[0] & 3) << 4) + (Bits
[1] >> 4)];
456 if (I
+ 1 >= S
.end())
459 Final
+= tbl
[((Bits
[1] & 0xf) << 2) + (Bits
[2] >> 6)];
461 if (I
+ 2 >= S
.end())
464 Final
+= tbl
[Bits
[2] & 0x3f];
467 /* Apply the padding elements, this tells how many bytes the remote
468 end should discard */
469 if (S
.length() % 3 == 2)
471 if (S
.length() % 3 == 1)
477 // stringcmp - Arbitrary string compare /*{{{*/
478 // ---------------------------------------------------------------------
479 /* This safely compares two non-null terminated strings of arbitrary
481 int stringcmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
483 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
487 if (A
== AEnd
&& B
== BEnd
)
499 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
500 const char *B
,const char *BEnd
)
502 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
506 if (A
== AEnd
&& B
== BEnd
)
516 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
517 string::const_iterator B
,string::const_iterator BEnd
)
519 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
523 if (A
== AEnd
&& B
== BEnd
)
535 // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
536 // ---------------------------------------------------------------------
538 int stringcasecmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
540 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
541 if (toupper(*A
) != toupper(*B
))
544 if (A
== AEnd
&& B
== BEnd
)
550 if (toupper(*A
) < toupper(*B
))
555 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
556 const char *B
,const char *BEnd
)
558 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
559 if (toupper(*A
) != toupper(*B
))
562 if (A
== AEnd
&& B
== BEnd
)
568 if (toupper(*A
) < toupper(*B
))
572 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
573 string::const_iterator B
,string::const_iterator BEnd
)
575 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
576 if (toupper(*A
) != toupper(*B
))
579 if (A
== AEnd
&& B
== BEnd
)
585 if (toupper(*A
) < toupper(*B
))
591 // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
592 // ---------------------------------------------------------------------
593 /* The format is like those used in package files and the method
594 communication system */
595 string
LookupTag(const string
&Message
,const char *Tag
,const char *Default
)
597 // Look for a matching tag.
598 int Length
= strlen(Tag
);
599 for (string::const_iterator I
= Message
.begin(); I
+ Length
< Message
.end(); I
++)
602 if (I
[Length
] == ':' && stringcasecmp(I
,I
+Length
,Tag
) == 0)
604 // Find the end of line and strip the leading/trailing spaces
605 string::const_iterator J
;
607 for (; isspace(*I
) != 0 && I
< Message
.end(); I
++);
608 for (J
= I
; *J
!= '\n' && J
< Message
.end(); J
++);
609 for (; J
> I
&& isspace(J
[-1]) != 0; J
--);
614 for (; *I
!= '\n' && I
< Message
.end(); I
++);
617 // Failed to find a match
623 // StringToBool - Converts a string into a boolean /*{{{*/
624 // ---------------------------------------------------------------------
625 /* This inspects the string to see if it is true or if it is false and
626 then returns the result. Several varients on true/false are checked. */
627 int StringToBool(const string
&Text
,int Default
)
630 int Res
= strtol(Text
.c_str(),&End
,0);
631 if (End
!= Text
.c_str() && Res
>= 0 && Res
<= 1)
634 // Check for positives
635 if (strcasecmp(Text
.c_str(),"no") == 0 ||
636 strcasecmp(Text
.c_str(),"false") == 0 ||
637 strcasecmp(Text
.c_str(),"without") == 0 ||
638 strcasecmp(Text
.c_str(),"off") == 0 ||
639 strcasecmp(Text
.c_str(),"disable") == 0)
642 // Check for negatives
643 if (strcasecmp(Text
.c_str(),"yes") == 0 ||
644 strcasecmp(Text
.c_str(),"true") == 0 ||
645 strcasecmp(Text
.c_str(),"with") == 0 ||
646 strcasecmp(Text
.c_str(),"on") == 0 ||
647 strcasecmp(Text
.c_str(),"enable") == 0)
653 // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
654 // ---------------------------------------------------------------------
655 /* This converts a time_t into a string time representation that is
656 year 2000 complient and timezone neutral */
657 string
TimeRFC1123(time_t Date
)
659 struct tm Conv
= *gmtime(&Date
);
662 const char *Day
[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
663 const char *Month
[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
664 "Aug","Sep","Oct","Nov","Dec"};
666 sprintf(Buf
,"%s, %02i %s %i %02i:%02i:%02i GMT",Day
[Conv
.tm_wday
],
667 Conv
.tm_mday
,Month
[Conv
.tm_mon
],Conv
.tm_year
+1900,Conv
.tm_hour
,
668 Conv
.tm_min
,Conv
.tm_sec
);
672 // ReadMessages - Read messages from the FD /*{{{*/
673 // ---------------------------------------------------------------------
674 /* This pulls full messages from the input FD into the message buffer.
675 It assumes that messages will not pause during transit so no
676 fancy buffering is used.
678 In particular: this reads blocks from the input until it believes
679 that it's run out of input text. Each block is terminated by a
680 double newline ('\n' followed by '\n'). As noted below, there is a
681 bug in this code: it assumes that all the blocks have been read if
682 it doesn't see additional text in the buffer after the last one is
683 parsed, which will cause it to lose blocks if the last block
684 coincides with the end of the buffer.
686 bool ReadMessages(int Fd
, vector
<string
> &List
)
690 // Represents any left-over from the previous iteration of the
691 // parse loop. (i.e., if a message is split across the end
692 // of the buffer, it goes here)
693 string PartialMessage
;
697 int Res
= read(Fd
,End
,sizeof(Buffer
) - (End
-Buffer
));
698 if (Res
< 0 && errno
== EINTR
)
701 // Process is dead, this is kind of bad..
706 if (Res
< 0 && errno
== EAGAIN
)
713 // Look for the end of the message
714 for (char *I
= Buffer
; I
+ 1 < End
; I
++)
716 if (I
[0] != '\n' || I
[1] != '\n')
719 // Pull the message out
720 string
Message(Buffer
,I
-Buffer
);
721 PartialMessage
+= Message
;
724 for (; I
< End
&& *I
== '\n'; I
++);
726 memmove(Buffer
,I
,End
-Buffer
);
729 List
.push_back(PartialMessage
);
730 PartialMessage
.clear();
734 // If there's text left in the buffer, store it
735 // in PartialMessage and throw the rest of the buffer
736 // away. This allows us to handle messages that
737 // are longer than the static buffer size.
738 PartialMessage
+= string(Buffer
, End
);
743 // BUG ALERT: if a message block happens to end at a
744 // multiple of 64000 characters, this will cause it to
745 // terminate early, leading to a badly formed block and
746 // probably crashing the method. However, this is the only
747 // way we have to find the end of the message block. I have
748 // an idea of how to fix this, but it will require changes
749 // to the protocol (essentially to mark the beginning and
750 // end of the block).
752 // -- dburrows 2008-04-02
756 if (WaitFd(Fd
) == false)
761 // MonthConv - Converts a month string into a number /*{{{*/
762 // ---------------------------------------------------------------------
763 /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
764 Made it a bit more robust with a few touppers though. */
765 static int MonthConv(char *Month
)
767 switch (toupper(*Month
))
770 return toupper(Month
[1]) == 'P'?3:7;
776 if (toupper(Month
[1]) == 'A')
778 return toupper(Month
[2]) == 'N'?5:6;
780 return toupper(Month
[2]) == 'R'?2:4;
788 // Pretend it is January..
794 // timegm - Internal timegm function if gnu is not available /*{{{*/
795 // ---------------------------------------------------------------------
796 /* Ripped this evil little function from wget - I prefer the use of
797 GNU timegm if possible as this technique will have interesting problems
798 with leap seconds, timezones and other.
800 Converts struct tm to time_t, assuming the data in tm is UTC rather
801 than local timezone (mktime assumes the latter).
803 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
804 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
806 /* Turned it into an autoconf check, because GNU is not the only thing which
807 can provide timegm. -- 2002-09-22, Joel Baker */
809 #ifndef HAVE_TIMEGM // Now with autoconf!
810 static time_t timegm(struct tm
*t
)
817 tb
= mktime (gmtime (&tl
));
818 return (tl
<= tb
? (tl
+ (tl
- tb
)) : (tl
- (tb
- tl
)));
822 // StrToTime - Converts a string into a time_t /*{{{*/
823 // ---------------------------------------------------------------------
824 /* This handles all 3 populare time formats including RFC 1123, RFC 1036
825 and the C library asctime format. It requires the GNU library function
826 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
827 reason the C library does not provide any such function :< This also
828 handles the weird, but unambiguous FTP time format*/
829 bool StrToTime(const string
&Val
,time_t &Result
)
833 const char *I
= Val
.c_str();
835 // Skip the day of the week
836 for (;*I
!= 0 && *I
!= ' '; I
++);
838 // Handle RFC 1123 time
840 if (sscanf(I
," %d %3s %d %d:%d:%d GMT",&Tm
.tm_mday
,Month
,&Tm
.tm_year
,
841 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
843 // Handle RFC 1036 time
844 if (sscanf(I
," %d-%3s-%d %d:%d:%d GMT",&Tm
.tm_mday
,Month
,
845 &Tm
.tm_year
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) == 6)
850 if (sscanf(I
," %3s %d %d:%d:%d %d",Month
,&Tm
.tm_mday
,
851 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
,&Tm
.tm_year
) != 6)
854 if (sscanf(Val
.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm
.tm_year
,&Tm
.tm_mon
,
855 &Tm
.tm_mday
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
864 Tm
.tm_mon
= MonthConv(Month
);
867 // Convert to local time and then to GMT
868 Result
= timegm(&Tm
);
872 // StrToNum - Convert a fixed length string to a number /*{{{*/
873 // ---------------------------------------------------------------------
874 /* This is used in decoding the crazy fixed length string headers in
876 bool StrToNum(const char *Str
,unsigned long &Res
,unsigned Len
,unsigned Base
)
879 if (Len
>= sizeof(S
))
884 // All spaces is a zero
887 for (I
= 0; S
[I
] == ' '; I
++);
892 Res
= strtoul(S
,&End
,Base
);
899 // HexDigit - Convert a hex character into an integer /*{{{*/
900 // ---------------------------------------------------------------------
901 /* Helper for Hex2Num */
902 static int HexDigit(int c
)
904 if (c
>= '0' && c
<= '9')
906 if (c
>= 'a' && c
<= 'f')
908 if (c
>= 'A' && c
<= 'F')
913 // Hex2Num - Convert a long hex number into a buffer /*{{{*/
914 // ---------------------------------------------------------------------
915 /* The length of the buffer must be exactly 1/2 the length of the string. */
916 bool Hex2Num(const string
&Str
,unsigned char *Num
,unsigned int Length
)
918 if (Str
.length() != Length
*2)
921 // Convert each digit. We store it in the same order as the string
923 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end();J
++, I
+= 2)
925 if (isxdigit(*I
) == 0 || isxdigit(I
[1]) == 0)
928 Num
[J
] = HexDigit(I
[0]) << 4;
929 Num
[J
] += HexDigit(I
[1]);
935 // TokSplitString - Split a string up by a given token /*{{{*/
936 // ---------------------------------------------------------------------
937 /* This is intended to be a faster splitter, it does not use dynamic
938 memories. Input is changed to insert nulls at each token location. */
939 bool TokSplitString(char Tok
,char *Input
,char **List
,
940 unsigned long ListMax
)
942 // Strip any leading spaces
944 char *Stop
= Start
+ strlen(Start
);
945 for (; *Start
!= 0 && isspace(*Start
) != 0; Start
++);
947 unsigned long Count
= 0;
951 // Skip to the next Token
952 for (; Pos
!= Stop
&& *Pos
!= Tok
; Pos
++);
954 // Back remove spaces
956 for (; End
> Start
&& (End
[-1] == Tok
|| isspace(End
[-1]) != 0); End
--);
959 List
[Count
++] = Start
;
960 if (Count
>= ListMax
)
967 for (; Pos
!= Stop
&& (*Pos
== Tok
|| isspace(*Pos
) != 0 || *Pos
== 0); Pos
++);
975 // RegexChoice - Simple regex list/list matcher /*{{{*/
976 // ---------------------------------------------------------------------
978 unsigned long RegexChoice(RxChoiceList
*Rxs
,const char **ListBegin
,
979 const char **ListEnd
)
981 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
984 unsigned long Hits
= 0;
985 for (; ListBegin
!= ListEnd
; ListBegin
++)
987 // Check if the name is a regex
990 for (I
= *ListBegin
; *I
!= 0; I
++)
991 if (*I
== '.' || *I
== '?' || *I
== '*' || *I
== '|')
996 // Compile the regex pattern
999 if (regcomp(&Pattern
,*ListBegin
,REG_EXTENDED
| REG_ICASE
|
1005 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
1010 if (strcasecmp(R
->Str
,*ListBegin
) != 0)
1014 if (regexec(&Pattern
,R
->Str
,0,0,0) != 0)
1019 if (R
->Hit
== false)
1029 _error
->Warning(_("Selection %s not found"),*ListBegin
);
1035 // ioprintf - C format string outputter to C++ iostreams /*{{{*/
1036 // ---------------------------------------------------------------------
1037 /* This is used to make the internationalization strings easier to translate
1038 and to allow reordering of parameters */
1039 void ioprintf(ostream
&out
,const char *format
,...)
1042 va_start(args
,format
);
1044 // sprintf the description
1046 vsnprintf(S
,sizeof(S
),format
,args
);
1050 // strprintf - C format string outputter to C++ strings /*{{{*/
1051 // ---------------------------------------------------------------------
1052 /* This is used to make the internationalization strings easier to translate
1053 and to allow reordering of parameters */
1054 void strprintf(string
&out
,const char *format
,...)
1057 va_start(args
,format
);
1059 // sprintf the description
1061 vsnprintf(S
,sizeof(S
),format
,args
);
1065 // safe_snprintf - Safer snprintf /*{{{*/
1066 // ---------------------------------------------------------------------
1067 /* This is a snprintf that will never (ever) go past 'End' and returns a
1068 pointer to the end of the new string. The returned string is always null
1069 terminated unless Buffer == end. This is a better alterantive to using
1070 consecutive snprintfs. */
1071 char *safe_snprintf(char *Buffer
,char *End
,const char *Format
,...)
1076 va_start(args
,Format
);
1081 Did
= vsnprintf(Buffer
,End
- Buffer
,Format
,args
);
1082 if (Did
< 0 || Buffer
+ Did
> End
)
1084 return Buffer
+ Did
;
1088 // tolower_ascii - tolower() function that ignores the locale /*{{{*/
1089 // ---------------------------------------------------------------------
1091 int tolower_ascii(int c
)
1093 if (c
>= 'A' and c
<= 'Z')
1099 // CheckDomainList - See if Host is in a , seperate list /*{{{*/
1100 // ---------------------------------------------------------------------
1101 /* The domain list is a comma seperate list of domains that are suffix
1102 matched against the argument */
1103 bool CheckDomainList(const string
&Host
,const string
&List
)
1105 string::const_iterator Start
= List
.begin();
1106 for (string::const_iterator Cur
= List
.begin(); Cur
<= List
.end(); Cur
++)
1108 if (Cur
< List
.end() && *Cur
!= ',')
1111 // Match the end of the string..
1112 if ((Host
.size() >= (unsigned)(Cur
- Start
)) &&
1114 stringcasecmp(Host
.end() - (Cur
- Start
),Host
.end(),Start
,Cur
) == 0)
1123 // URI::CopyFrom - Copy from an object /*{{{*/
1124 // ---------------------------------------------------------------------
1125 /* This parses the URI into all of its components */
1126 void URI::CopyFrom(const string
&U
)
1128 string::const_iterator I
= U
.begin();
1130 // Locate the first colon, this separates the scheme
1131 for (; I
< U
.end() && *I
!= ':' ; I
++);
1132 string::const_iterator FirstColon
= I
;
1134 /* Determine if this is a host type URI with a leading double //
1135 and then search for the first single / */
1136 string::const_iterator SingleSlash
= I
;
1137 if (I
+ 3 < U
.end() && I
[1] == '/' && I
[2] == '/')
1140 /* Find the / indicating the end of the hostname, ignoring /'s in the
1142 bool InBracket
= false;
1143 for (; SingleSlash
< U
.end() && (*SingleSlash
!= '/' || InBracket
== true); SingleSlash
++)
1145 if (*SingleSlash
== '[')
1147 if (InBracket
== true && *SingleSlash
== ']')
1151 if (SingleSlash
> U
.end())
1152 SingleSlash
= U
.end();
1154 // We can now write the access and path specifiers
1155 Access
.assign(U
.begin(),FirstColon
);
1156 if (SingleSlash
!= U
.end())
1157 Path
.assign(SingleSlash
,U
.end());
1158 if (Path
.empty() == true)
1161 // Now we attempt to locate a user:pass@host fragment
1162 if (FirstColon
+ 2 <= U
.end() && FirstColon
[1] == '/' && FirstColon
[2] == '/')
1166 if (FirstColon
>= U
.end())
1169 if (FirstColon
> SingleSlash
)
1170 FirstColon
= SingleSlash
;
1172 // Find the colon...
1174 if (I
> SingleSlash
)
1176 for (; I
< SingleSlash
&& *I
!= ':'; I
++);
1177 string::const_iterator SecondColon
= I
;
1179 // Search for the @ after the colon
1180 for (; I
< SingleSlash
&& *I
!= '@'; I
++);
1181 string::const_iterator At
= I
;
1183 // Now write the host and user/pass
1184 if (At
== SingleSlash
)
1186 if (FirstColon
< SingleSlash
)
1187 Host
.assign(FirstColon
,SingleSlash
);
1191 Host
.assign(At
+1,SingleSlash
);
1192 User
.assign(FirstColon
,SecondColon
);
1193 if (SecondColon
< At
)
1194 Password
.assign(SecondColon
+1,At
);
1197 // Now we parse the RFC 2732 [] hostnames.
1198 unsigned long PortEnd
= 0;
1200 for (unsigned I
= 0; I
!= Host
.length();)
1209 if (InBracket
== true && Host
[I
] == ']')
1220 if (InBracket
== true)
1226 // Now we parse off a port number from the hostname
1228 string::size_type Pos
= Host
.rfind(':');
1229 if (Pos
== string::npos
|| Pos
< PortEnd
)
1232 Port
= atoi(string(Host
,Pos
+1).c_str());
1233 Host
.assign(Host
,0,Pos
);
1236 // URI::operator string - Convert the URI to a string /*{{{*/
1237 // ---------------------------------------------------------------------
1239 URI::operator string()
1243 if (Access
.empty() == false)
1246 if (Host
.empty() == false)
1248 if (Access
.empty() == false)
1251 if (User
.empty() == false)
1254 if (Password
.empty() == false)
1255 Res
+= ":" + Password
;
1259 // Add RFC 2732 escaping characters
1260 if (Access
.empty() == false &&
1261 (Host
.find('/') != string::npos
|| Host
.find(':') != string::npos
))
1262 Res
+= '[' + Host
+ ']';
1269 sprintf(S
,":%u",Port
);
1274 if (Path
.empty() == false)
1285 // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
1286 // ---------------------------------------------------------------------
1288 string
URI::SiteOnly(const string
&URI
)