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 // URItoFileName - Convert the uri into a unique file name /*{{{*/
391 // ---------------------------------------------------------------------
392 /* This converts a URI into a safe filename. It quotes all unsafe characters
393 and converts / to _ and removes the scheme identifier. The resulting
394 file name should be unique and never occur again for a different file */
395 string
URItoFileName(const string
&URI
)
397 // Nuke 'sensitive' items
403 // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
404 string NewURI
= QuoteString(U
,"\\|{}[]<>\"^~_=!@#$%^&*");
405 replace(NewURI
.begin(),NewURI
.end(),'/','_');
409 // Base64Encode - Base64 Encoding routine for short strings /*{{{*/
410 // ---------------------------------------------------------------------
411 /* This routine performs a base64 transformation on a string. It was ripped
412 from wget and then patched and bug fixed.
414 This spec can be found in rfc2045 */
415 string
Base64Encode(const string
&S
)
418 static char tbl
[64] = {'A','B','C','D','E','F','G','H',
419 'I','J','K','L','M','N','O','P',
420 'Q','R','S','T','U','V','W','X',
421 'Y','Z','a','b','c','d','e','f',
422 'g','h','i','j','k','l','m','n',
423 'o','p','q','r','s','t','u','v',
424 'w','x','y','z','0','1','2','3',
425 '4','5','6','7','8','9','+','/'};
427 // Pre-allocate some space
429 Final
.reserve((4*S
.length() + 2)/3 + 2);
431 /* Transform the 3x8 bits to 4x6 bits, as required by
433 for (string::const_iterator I
= S
.begin(); I
< S
.end(); I
+= 3)
435 char Bits
[3] = {0,0,0};
442 Final
+= tbl
[Bits
[0] >> 2];
443 Final
+= tbl
[((Bits
[0] & 3) << 4) + (Bits
[1] >> 4)];
445 if (I
+ 1 >= S
.end())
448 Final
+= tbl
[((Bits
[1] & 0xf) << 2) + (Bits
[2] >> 6)];
450 if (I
+ 2 >= S
.end())
453 Final
+= tbl
[Bits
[2] & 0x3f];
456 /* Apply the padding elements, this tells how many bytes the remote
457 end should discard */
458 if (S
.length() % 3 == 2)
460 if (S
.length() % 3 == 1)
466 // stringcmp - Arbitrary string compare /*{{{*/
467 // ---------------------------------------------------------------------
468 /* This safely compares two non-null terminated strings of arbitrary
470 int stringcmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
472 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
476 if (A
== AEnd
&& B
== BEnd
)
488 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
489 const char *B
,const char *BEnd
)
491 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
495 if (A
== AEnd
&& B
== BEnd
)
505 int stringcmp(string::const_iterator A
,string::const_iterator AEnd
,
506 string::const_iterator B
,string::const_iterator BEnd
)
508 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
512 if (A
== AEnd
&& B
== BEnd
)
524 // stringcasecmp - Arbitrary case insensitive string compare /*{{{*/
525 // ---------------------------------------------------------------------
527 int stringcasecmp(const char *A
,const char *AEnd
,const char *B
,const char *BEnd
)
529 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
530 if (toupper(*A
) != toupper(*B
))
533 if (A
== AEnd
&& B
== BEnd
)
539 if (toupper(*A
) < toupper(*B
))
544 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
545 const char *B
,const char *BEnd
)
547 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
548 if (toupper(*A
) != toupper(*B
))
551 if (A
== AEnd
&& B
== BEnd
)
557 if (toupper(*A
) < toupper(*B
))
561 int stringcasecmp(string::const_iterator A
,string::const_iterator AEnd
,
562 string::const_iterator B
,string::const_iterator BEnd
)
564 for (; A
!= AEnd
&& B
!= BEnd
; A
++, B
++)
565 if (toupper(*A
) != toupper(*B
))
568 if (A
== AEnd
&& B
== BEnd
)
574 if (toupper(*A
) < toupper(*B
))
580 // LookupTag - Lookup the value of a tag in a taged string /*{{{*/
581 // ---------------------------------------------------------------------
582 /* The format is like those used in package files and the method
583 communication system */
584 string
LookupTag(const string
&Message
,const char *Tag
,const char *Default
)
586 // Look for a matching tag.
587 int Length
= strlen(Tag
);
588 for (string::const_iterator I
= Message
.begin(); I
+ Length
< Message
.end(); I
++)
591 if (I
[Length
] == ':' && stringcasecmp(I
,I
+Length
,Tag
) == 0)
593 // Find the end of line and strip the leading/trailing spaces
594 string::const_iterator J
;
596 for (; isspace(*I
) != 0 && I
< Message
.end(); I
++);
597 for (J
= I
; *J
!= '\n' && J
< Message
.end(); J
++);
598 for (; J
> I
&& isspace(J
[-1]) != 0; J
--);
603 for (; *I
!= '\n' && I
< Message
.end(); I
++);
606 // Failed to find a match
612 // StringToBool - Converts a string into a boolean /*{{{*/
613 // ---------------------------------------------------------------------
614 /* This inspects the string to see if it is true or if it is false and
615 then returns the result. Several varients on true/false are checked. */
616 int StringToBool(const string
&Text
,int Default
)
619 int Res
= strtol(Text
.c_str(),&End
,0);
620 if (End
!= Text
.c_str() && Res
>= 0 && Res
<= 1)
623 // Check for positives
624 if (strcasecmp(Text
.c_str(),"no") == 0 ||
625 strcasecmp(Text
.c_str(),"false") == 0 ||
626 strcasecmp(Text
.c_str(),"without") == 0 ||
627 strcasecmp(Text
.c_str(),"off") == 0 ||
628 strcasecmp(Text
.c_str(),"disable") == 0)
631 // Check for negatives
632 if (strcasecmp(Text
.c_str(),"yes") == 0 ||
633 strcasecmp(Text
.c_str(),"true") == 0 ||
634 strcasecmp(Text
.c_str(),"with") == 0 ||
635 strcasecmp(Text
.c_str(),"on") == 0 ||
636 strcasecmp(Text
.c_str(),"enable") == 0)
642 // TimeRFC1123 - Convert a time_t into RFC1123 format /*{{{*/
643 // ---------------------------------------------------------------------
644 /* This converts a time_t into a string time representation that is
645 year 2000 complient and timezone neutral */
646 string
TimeRFC1123(time_t Date
)
648 struct tm Conv
= *gmtime(&Date
);
651 const char *Day
[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
652 const char *Month
[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul",
653 "Aug","Sep","Oct","Nov","Dec"};
655 sprintf(Buf
,"%s, %02i %s %i %02i:%02i:%02i GMT",Day
[Conv
.tm_wday
],
656 Conv
.tm_mday
,Month
[Conv
.tm_mon
],Conv
.tm_year
+1900,Conv
.tm_hour
,
657 Conv
.tm_min
,Conv
.tm_sec
);
661 // ReadMessages - Read messages from the FD /*{{{*/
662 // ---------------------------------------------------------------------
663 /* This pulls full messages from the input FD into the message buffer.
664 It assumes that messages will not pause during transit so no
665 fancy buffering is used.
667 In particular: this reads blocks from the input until it believes
668 that it's run out of input text. Each block is terminated by a
669 double newline ('\n' followed by '\n'). As noted below, there is a
670 bug in this code: it assumes that all the blocks have been read if
671 it doesn't see additional text in the buffer after the last one is
672 parsed, which will cause it to lose blocks if the last block
673 coincides with the end of the buffer.
675 bool ReadMessages(int Fd
, vector
<string
> &List
)
679 // Represents any left-over from the previous iteration of the
680 // parse loop. (i.e., if a message is split across the end
681 // of the buffer, it goes here)
682 string PartialMessage
;
686 int Res
= read(Fd
,End
,sizeof(Buffer
) - (End
-Buffer
));
687 if (Res
< 0 && errno
== EINTR
)
690 // Process is dead, this is kind of bad..
695 if (Res
< 0 && errno
== EAGAIN
)
702 // Look for the end of the message
703 for (char *I
= Buffer
; I
+ 1 < End
; I
++)
705 if (I
[0] != '\n' || I
[1] != '\n')
708 // Pull the message out
709 string
Message(Buffer
,I
-Buffer
);
710 PartialMessage
+= Message
;
713 for (; I
< End
&& *I
== '\n'; I
++);
715 memmove(Buffer
,I
,End
-Buffer
);
718 List
.push_back(PartialMessage
);
719 PartialMessage
.clear();
723 // If there's text left in the buffer, store it
724 // in PartialMessage and throw the rest of the buffer
725 // away. This allows us to handle messages that
726 // are longer than the static buffer size.
727 PartialMessage
+= string(Buffer
, End
);
732 // BUG ALERT: if a message block happens to end at a
733 // multiple of 64000 characters, this will cause it to
734 // terminate early, leading to a badly formed block and
735 // probably crashing the method. However, this is the only
736 // way we have to find the end of the message block. I have
737 // an idea of how to fix this, but it will require changes
738 // to the protocol (essentially to mark the beginning and
739 // end of the block).
741 // -- dburrows 2008-04-02
745 if (WaitFd(Fd
) == false)
750 // MonthConv - Converts a month string into a number /*{{{*/
751 // ---------------------------------------------------------------------
752 /* This was lifted from the boa webserver which lifted it from 'wn-v1.07'
753 Made it a bit more robust with a few touppers though. */
754 static int MonthConv(char *Month
)
756 switch (toupper(*Month
))
759 return toupper(Month
[1]) == 'P'?3:7;
765 if (toupper(Month
[1]) == 'A')
767 return toupper(Month
[2]) == 'N'?5:6;
769 return toupper(Month
[2]) == 'R'?2:4;
777 // Pretend it is January..
783 // timegm - Internal timegm function if gnu is not available /*{{{*/
784 // ---------------------------------------------------------------------
785 /* Ripped this evil little function from wget - I prefer the use of
786 GNU timegm if possible as this technique will have interesting problems
787 with leap seconds, timezones and other.
789 Converts struct tm to time_t, assuming the data in tm is UTC rather
790 than local timezone (mktime assumes the latter).
792 Contributed by Roger Beeman <beeman@cisco.com>, with the help of
793 Mark Baushke <mdb@cisco.com> and the rest of the Gurus at CISCO. */
795 /* Turned it into an autoconf check, because GNU is not the only thing which
796 can provide timegm. -- 2002-09-22, Joel Baker */
798 #ifndef HAVE_TIMEGM // Now with autoconf!
799 static time_t timegm(struct tm
*t
)
806 tb
= mktime (gmtime (&tl
));
807 return (tl
<= tb
? (tl
+ (tl
- tb
)) : (tl
- (tb
- tl
)));
811 // StrToTime - Converts a string into a time_t /*{{{*/
812 // ---------------------------------------------------------------------
813 /* This handles all 3 populare time formats including RFC 1123, RFC 1036
814 and the C library asctime format. It requires the GNU library function
815 'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
816 reason the C library does not provide any such function :< This also
817 handles the weird, but unambiguous FTP time format*/
818 bool StrToTime(const string
&Val
,time_t &Result
)
822 const char *I
= Val
.c_str();
824 // Skip the day of the week
825 for (;*I
!= 0 && *I
!= ' '; I
++);
827 // Handle RFC 1123 time
829 if (sscanf(I
," %d %3s %d %d:%d:%d GMT",&Tm
.tm_mday
,Month
,&Tm
.tm_year
,
830 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
832 // Handle RFC 1036 time
833 if (sscanf(I
," %d-%3s-%d %d:%d:%d GMT",&Tm
.tm_mday
,Month
,
834 &Tm
.tm_year
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) == 6)
839 if (sscanf(I
," %3s %d %d:%d:%d %d",Month
,&Tm
.tm_mday
,
840 &Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
,&Tm
.tm_year
) != 6)
843 if (sscanf(Val
.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm
.tm_year
,&Tm
.tm_mon
,
844 &Tm
.tm_mday
,&Tm
.tm_hour
,&Tm
.tm_min
,&Tm
.tm_sec
) != 6)
853 Tm
.tm_mon
= MonthConv(Month
);
856 // Convert to local time and then to GMT
857 Result
= timegm(&Tm
);
861 // StrToNum - Convert a fixed length string to a number /*{{{*/
862 // ---------------------------------------------------------------------
863 /* This is used in decoding the crazy fixed length string headers in
865 bool StrToNum(const char *Str
,unsigned long &Res
,unsigned Len
,unsigned Base
)
868 if (Len
>= sizeof(S
))
873 // All spaces is a zero
876 for (I
= 0; S
[I
] == ' '; I
++);
881 Res
= strtoul(S
,&End
,Base
);
888 // HexDigit - Convert a hex character into an integer /*{{{*/
889 // ---------------------------------------------------------------------
890 /* Helper for Hex2Num */
891 static int HexDigit(int c
)
893 if (c
>= '0' && c
<= '9')
895 if (c
>= 'a' && c
<= 'f')
897 if (c
>= 'A' && c
<= 'F')
902 // Hex2Num - Convert a long hex number into a buffer /*{{{*/
903 // ---------------------------------------------------------------------
904 /* The length of the buffer must be exactly 1/2 the length of the string. */
905 bool Hex2Num(const string
&Str
,unsigned char *Num
,unsigned int Length
)
907 if (Str
.length() != Length
*2)
910 // Convert each digit. We store it in the same order as the string
912 for (string::const_iterator I
= Str
.begin(); I
!= Str
.end();J
++, I
+= 2)
914 if (isxdigit(*I
) == 0 || isxdigit(I
[1]) == 0)
917 Num
[J
] = HexDigit(I
[0]) << 4;
918 Num
[J
] += HexDigit(I
[1]);
924 // TokSplitString - Split a string up by a given token /*{{{*/
925 // ---------------------------------------------------------------------
926 /* This is intended to be a faster splitter, it does not use dynamic
927 memories. Input is changed to insert nulls at each token location. */
928 bool TokSplitString(char Tok
,char *Input
,char **List
,
929 unsigned long ListMax
)
931 // Strip any leading spaces
933 char *Stop
= Start
+ strlen(Start
);
934 for (; *Start
!= 0 && isspace(*Start
) != 0; Start
++);
936 unsigned long Count
= 0;
940 // Skip to the next Token
941 for (; Pos
!= Stop
&& *Pos
!= Tok
; Pos
++);
943 // Back remove spaces
945 for (; End
> Start
&& (End
[-1] == Tok
|| isspace(End
[-1]) != 0); End
--);
948 List
[Count
++] = Start
;
949 if (Count
>= ListMax
)
956 for (; Pos
!= Stop
&& (*Pos
== Tok
|| isspace(*Pos
) != 0 || *Pos
== 0); Pos
++);
964 // RegexChoice - Simple regex list/list matcher /*{{{*/
965 // ---------------------------------------------------------------------
967 unsigned long RegexChoice(RxChoiceList
*Rxs
,const char **ListBegin
,
968 const char **ListEnd
)
970 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
973 unsigned long Hits
= 0;
974 for (; ListBegin
!= ListEnd
; ListBegin
++)
976 // Check if the name is a regex
979 for (I
= *ListBegin
; *I
!= 0; I
++)
980 if (*I
== '.' || *I
== '?' || *I
== '*' || *I
== '|')
985 // Compile the regex pattern
988 if (regcomp(&Pattern
,*ListBegin
,REG_EXTENDED
| REG_ICASE
|
994 for (RxChoiceList
*R
= Rxs
; R
->Str
!= 0; R
++)
999 if (strcasecmp(R
->Str
,*ListBegin
) != 0)
1003 if (regexec(&Pattern
,R
->Str
,0,0,0) != 0)
1008 if (R
->Hit
== false)
1018 _error
->Warning(_("Selection %s not found"),*ListBegin
);
1024 // ioprintf - C format string outputter to C++ iostreams /*{{{*/
1025 // ---------------------------------------------------------------------
1026 /* This is used to make the internationalization strings easier to translate
1027 and to allow reordering of parameters */
1028 void ioprintf(ostream
&out
,const char *format
,...)
1031 va_start(args
,format
);
1033 // sprintf the description
1035 vsnprintf(S
,sizeof(S
),format
,args
);
1039 // safe_snprintf - Safer snprintf /*{{{*/
1040 // ---------------------------------------------------------------------
1041 /* This is a snprintf that will never (ever) go past 'End' and returns a
1042 pointer to the end of the new string. The returned string is always null
1043 terminated unless Buffer == end. This is a better alterantive to using
1044 consecutive snprintfs. */
1045 char *safe_snprintf(char *Buffer
,char *End
,const char *Format
,...)
1050 va_start(args
,Format
);
1055 Did
= vsnprintf(Buffer
,End
- Buffer
,Format
,args
);
1056 if (Did
< 0 || Buffer
+ Did
> End
)
1058 return Buffer
+ Did
;
1062 // CheckDomainList - See if Host is in a , seperate list /*{{{*/
1063 // ---------------------------------------------------------------------
1064 /* The domain list is a comma seperate list of domains that are suffix
1065 matched against the argument */
1066 bool CheckDomainList(const string
&Host
,const string
&List
)
1068 string::const_iterator Start
= List
.begin();
1069 for (string::const_iterator Cur
= List
.begin(); Cur
<= List
.end(); Cur
++)
1071 if (Cur
< List
.end() && *Cur
!= ',')
1074 // Match the end of the string..
1075 if ((Host
.size() >= (unsigned)(Cur
- Start
)) &&
1077 stringcasecmp(Host
.end() - (Cur
- Start
),Host
.end(),Start
,Cur
) == 0)
1086 // URI::CopyFrom - Copy from an object /*{{{*/
1087 // ---------------------------------------------------------------------
1088 /* This parses the URI into all of its components */
1089 void URI::CopyFrom(const string
&U
)
1091 string::const_iterator I
= U
.begin();
1093 // Locate the first colon, this separates the scheme
1094 for (; I
< U
.end() && *I
!= ':' ; I
++);
1095 string::const_iterator FirstColon
= I
;
1097 /* Determine if this is a host type URI with a leading double //
1098 and then search for the first single / */
1099 string::const_iterator SingleSlash
= I
;
1100 if (I
+ 3 < U
.end() && I
[1] == '/' && I
[2] == '/')
1103 /* Find the / indicating the end of the hostname, ignoring /'s in the
1105 bool InBracket
= false;
1106 for (; SingleSlash
< U
.end() && (*SingleSlash
!= '/' || InBracket
== true); SingleSlash
++)
1108 if (*SingleSlash
== '[')
1110 if (InBracket
== true && *SingleSlash
== ']')
1114 if (SingleSlash
> U
.end())
1115 SingleSlash
= U
.end();
1117 // We can now write the access and path specifiers
1118 Access
.assign(U
.begin(),FirstColon
);
1119 if (SingleSlash
!= U
.end())
1120 Path
.assign(SingleSlash
,U
.end());
1121 if (Path
.empty() == true)
1124 // Now we attempt to locate a user:pass@host fragment
1125 if (FirstColon
+ 2 <= U
.end() && FirstColon
[1] == '/' && FirstColon
[2] == '/')
1129 if (FirstColon
>= U
.end())
1132 if (FirstColon
> SingleSlash
)
1133 FirstColon
= SingleSlash
;
1135 // Find the colon...
1137 if (I
> SingleSlash
)
1139 for (; I
< SingleSlash
&& *I
!= ':'; I
++);
1140 string::const_iterator SecondColon
= I
;
1142 // Search for the @ after the colon
1143 for (; I
< SingleSlash
&& *I
!= '@'; I
++);
1144 string::const_iterator At
= I
;
1146 // Now write the host and user/pass
1147 if (At
== SingleSlash
)
1149 if (FirstColon
< SingleSlash
)
1150 Host
.assign(FirstColon
,SingleSlash
);
1154 Host
.assign(At
+1,SingleSlash
);
1155 User
.assign(FirstColon
,SecondColon
);
1156 if (SecondColon
< At
)
1157 Password
.assign(SecondColon
+1,At
);
1160 // Now we parse the RFC 2732 [] hostnames.
1161 unsigned long PortEnd
= 0;
1163 for (unsigned I
= 0; I
!= Host
.length();)
1172 if (InBracket
== true && Host
[I
] == ']')
1183 if (InBracket
== true)
1189 // Now we parse off a port number from the hostname
1191 string::size_type Pos
= Host
.rfind(':');
1192 if (Pos
== string::npos
|| Pos
< PortEnd
)
1195 Port
= atoi(string(Host
,Pos
+1).c_str());
1196 Host
.assign(Host
,0,Pos
);
1199 // URI::operator string - Convert the URI to a string /*{{{*/
1200 // ---------------------------------------------------------------------
1202 URI::operator string()
1206 if (Access
.empty() == false)
1209 if (Host
.empty() == false)
1211 if (Access
.empty() == false)
1214 if (User
.empty() == false)
1217 if (Password
.empty() == false)
1218 Res
+= ":" + Password
;
1222 // Add RFC 2732 escaping characters
1223 if (Access
.empty() == false &&
1224 (Host
.find('/') != string::npos
|| Host
.find(':') != string::npos
))
1225 Res
+= '[' + Host
+ ']';
1232 sprintf(S
,":%u",Port
);
1237 if (Path
.empty() == false)
1248 // URI::SiteOnly - Return the schema and site for the URI /*{{{*/
1249 // ---------------------------------------------------------------------
1251 string
URI::SiteOnly(const string
&URI
)