]> git.saurik.com Git - apt.git/blobdiff - apt-pkg/contrib/strutl.cc
More ignoring of versionless packages
[apt.git] / apt-pkg / contrib / strutl.cc
index 2411623c573bc9fe87e7702528f09c69e8c4c35d..5e703138492c05062e9bdcde2473c72888fe1e46 100644 (file)
@@ -1,12 +1,12 @@
 // -*- mode: cpp; mode: fold -*-
 // Description                                                         /*{{{*/
 // -*- mode: cpp; mode: fold -*-
 // Description                                                         /*{{{*/
-// $Id: strutl.cc,v 1.24 1999/04/04 08:07:39 jgg Exp $
+// $Id: strutl.cc,v 1.40 2001/05/27 05:36:04 jgg Exp $
 /* ######################################################################
 
 /* ######################################################################
 
-   String Util - Some usefull string functions.
+   String Util - Some useful string functions.
 
 
-   These have been collected from here and there to do all sorts of usefull
-   things to strings. They are usefull in file parsers, URI handlers and
+   These have been collected from here and there to do all sorts of useful
+   things to strings. They are useful in file parsers, URI handlers and
    especially in APT methods.   
    
    This source is placed in the Public Domain, do with it what you will
    especially in APT methods.   
    
    This source is placed in the Public Domain, do with it what you will
 
 #include <apt-pkg/strutl.h>
 #include <apt-pkg/fileutl.h>
 
 #include <apt-pkg/strutl.h>
 #include <apt-pkg/fileutl.h>
+#include <apt-pkg/error.h>
 
 
+#include <apti18n.h>
+    
 #include <ctype.h>
 #include <string.h>
 #include <stdio.h>
 #include <unistd.h>
 #include <ctype.h>
 #include <string.h>
 #include <stdio.h>
 #include <unistd.h>
+#include <regex.h>
 #include <errno.h>
 #include <errno.h>
+#include <stdarg.h>
+
+using namespace std;
                                                                        /*}}}*/
 
 // strstrip - Remove white space from the front and back of a string   /*{{{*/
                                                                        /*}}}*/
 
 // strstrip - Remove white space from the front and back of a string   /*{{{*/
@@ -87,7 +94,8 @@ char *_strtabexpand(char *String,size_t Len)
 // ---------------------------------------------------------------------
 /* This grabs a single word, converts any % escaped characters to their
    proper values and advances the pointer. Double quotes are understood
 // ---------------------------------------------------------------------
 /* This grabs a single word, converts any % escaped characters to their
    proper values and advances the pointer. Double quotes are understood
-   and striped out as well. This is for URI/URL parsing. */
+   and striped out as well. This is for URI/URL parsing. It also can 
+   understand [] brackets.*/
 bool ParseQuoteWord(const char *&String,string &Res)
 {
    // Skip leading whitespace
 bool ParseQuoteWord(const char *&String,string &Res)
 {
    // Skip leading whitespace
@@ -101,7 +109,13 @@ bool ParseQuoteWord(const char *&String,string &Res)
    {
       if (*C == '"')
       {
    {
       if (*C == '"')
       {
-        for (C++;*C != 0 && *C != '"'; C++);
+        for (C++; *C != 0 && *C != '"'; C++);
+        if (*C == 0)
+           return false;
+      }
+      if (*C == '[')
+      {
+        for (C++; *C != 0 && *C != ']'; C++);
         if (*C == 0)
            return false;
       }
         if (*C == 0)
            return false;
       }
@@ -140,9 +154,9 @@ bool ParseQuoteWord(const char *&String,string &Res)
                                                                        /*}}}*/
 // ParseCWord - Parses a string like a C "" expression                 /*{{{*/
 // ---------------------------------------------------------------------
                                                                        /*}}}*/
 // ParseCWord - Parses a string like a C "" expression                 /*{{{*/
 // ---------------------------------------------------------------------
-/* This expects a series of space seperated strings enclosed in ""'s. 
+/* This expects a series of space separated strings enclosed in ""'s. 
    It concatenates the ""'s into a single string. */
    It concatenates the ""'s into a single string. */
-bool ParseCWord(const char *String,string &Res)
+bool ParseCWord(const char *&String,string &Res)
 {
    // Skip leading whitespace
    const char *C = String;
 {
    // Skip leading whitespace
    const char *C = String;
@@ -173,9 +187,10 @@ bool ParseCWord(const char *String,string &Res)
       if (isspace(*C) == 0)
         return false;
       *Buf++ = ' ';
       if (isspace(*C) == 0)
         return false;
       *Buf++ = ' ';
-   }   
+   }
    *Buf = 0;
    Res = Buffer;
    *Buf = 0;
    Res = Buffer;
+   String = C;
    return true;
 }
                                                                        /*}}}*/
    return true;
 }
                                                                        /*}}}*/
@@ -185,7 +200,7 @@ bool ParseCWord(const char *String,string &Res)
 string QuoteString(string Str,const char *Bad)
 {
    string Res;
 string QuoteString(string Str,const char *Bad)
 {
    string Res;
-   for (string::iterator I = Str.begin(); I != Str.end(); I++)
+   for (const char *I = Str.c_str(); *I != 0; I++)
    {
       if (strchr(Bad,*I) != 0 || isprint(*I) == 0 || 
          *I <= 0x20 || *I >= 0x7F)
    {
       if (strchr(Bad,*I) != 0 || isprint(*I) == 0 || 
          *I <= 0x20 || *I >= 0x7F)
@@ -206,9 +221,9 @@ string QuoteString(string Str,const char *Bad)
 string DeQuoteString(string Str)
 {
    string Res;
 string DeQuoteString(string Str)
 {
    string Res;
-   for (string::iterator I = Str.begin(); I != Str.end(); I++)
+   for (const char *I = Str.c_str(); *I != 0; I++)
    {
    {
-      if (*I == '%' && I + 2 < Str.end())
+      if (*I == '%' && I + 2 < Str.c_str() + Str.length())
       {
         char Tmp[3];
         Tmp[0] = I[1];
       {
         char Tmp[3];
         Tmp[0] = I[1];
@@ -318,6 +333,13 @@ string SubstVar(string Str,string Subst,string Contents)
    
    return Temp + string(Str,OldPos);
 }
    
    return Temp + string(Str,OldPos);
 }
+
+string SubstVar(string Str,const struct SubstVar *Vars)
+{
+   for (; Vars->Subst != 0; Vars++)
+      Str = SubstVar(Str,Vars->Subst,*Vars->Contents);
+   return Str;
+}
                                                                        /*}}}*/
 // URItoFileName - Convert the uri into a unique file name             /*{{{*/
 // ---------------------------------------------------------------------
                                                                        /*}}}*/
 // URItoFileName - Convert the uri into a unique file name             /*{{{*/
 // ---------------------------------------------------------------------
@@ -326,13 +348,16 @@ string SubstVar(string Str,string Subst,string Contents)
    file name should be unique and never occur again for a different file */
 string URItoFileName(string URI)
 {
    file name should be unique and never occur again for a different file */
 string URItoFileName(string URI)
 {
-   string::const_iterator I = URI.begin() + URI.find(':') + 1;
-   for (; I < URI.end() && *I == '/'; I++);
-
+   // Nuke 'sensitive' items
+   ::URI U(URI);
+   U.User = string();
+   U.Password = string();
+   U.Access = "";
+   
    // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
    // "\x00-\x20{}|\\\\^\\[\\]<>\"\x7F-\xFF";
-   URI = QuoteString(string(I,URI.end() - I),"\\|{}[]<>\"^~_=!@#$%^&*");
-   string::iterator J = URI.begin();
-   for (; J != URI.end(); J++)
+   URI = QuoteString(U,"\\|{}[]<>\"^~_=!@#$%^&*");
+   char *J = const_cast<char *>(URI.c_str());
+   for (; *J != 0; J++)
       if (*J == '/') 
         *J = '_';
    return URI;
       if (*J == '/') 
         *J = '_';
    return URI;
@@ -362,24 +387,24 @@ string Base64Encode(string S)
 
    /* Transform the 3x8 bits to 4x6 bits, as required by
       base64.  */
 
    /* Transform the 3x8 bits to 4x6 bits, as required by
       base64.  */
-   for (string::const_iterator I = S.begin(); I < S.end(); I += 3)
+   for (const char *I = S.c_str(); I < (S.c_str() + S.length()); I += 3)
    {
       char Bits[3] = {0,0,0};
       Bits[0] = I[0];
    {
       char Bits[3] = {0,0,0};
       Bits[0] = I[0];
-      if (I + 1 < S.end())
+      if (I + 1 < S.c_str() + S.length())
         Bits[1] = I[1];
         Bits[1] = I[1];
-      if (I + 2 < S.end())
+      if (I + 2 < S.c_str() + S.length())
         Bits[2] = I[2];
 
       Final += tbl[Bits[0] >> 2];
       Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
       
         Bits[2] = I[2];
 
       Final += tbl[Bits[0] >> 2];
       Final += tbl[((Bits[0] & 3) << 4) + (Bits[1] >> 4)];
       
-      if (I + 1 >= S.end())
+      if (I + 1 >= S.c_str() + S.length())
         break;
       
       Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
       
         break;
       
       Final += tbl[((Bits[1] & 0xf) << 2) + (Bits[2] >> 6)];
       
-      if (I + 2 >= S.end())
+      if (I + 2 >= S.c_str() + S.length())
         break;
       
       Final += tbl[Bits[2] & 0x3f];
         break;
       
       Final += tbl[Bits[2] & 0x3f];
@@ -444,22 +469,22 @@ string LookupTag(string Message,const char *Tag,const char *Default)
 {
    // Look for a matching tag.
    int Length = strlen(Tag);
 {
    // Look for a matching tag.
    int Length = strlen(Tag);
-   for (string::iterator I = Message.begin(); I + Length < Message.end(); I++)
+   for (const char *I = Message.c_str(); I + Length < Message.c_str() + Message.length(); I++)
    {
       // Found the tag
       if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
       {
         // Find the end of line and strip the leading/trailing spaces
    {
       // Found the tag
       if (I[Length] == ':' && stringcasecmp(I,I+Length,Tag) == 0)
       {
         // Find the end of line and strip the leading/trailing spaces
-        string::iterator J;
+        const char *J;
         I += Length + 1;
         I += Length + 1;
-        for (; isspace(*I) != 0 && I < Message.end(); I++);
-        for (J = I; *J != '\n' && J < Message.end(); J++);
+        for (; isspace(*I) != 0 && *I != 0; I++);
+        for (J = I; *J != '\n' && *J != 0; J++);
         for (; J > I && isspace(J[-1]) != 0; J--);
         
         for (; J > I && isspace(J[-1]) != 0; J--);
         
-        return string(I,J-I);
+        return string(I,J);
       }
       
       }
       
-      for (; *I != '\n' && I < Message.end(); I++);
+      for (; *I != '\n' && *I != 0; I++);
    }   
    
    // Failed to find a match
    }   
    
    // Failed to find a match
@@ -472,7 +497,7 @@ string LookupTag(string Message,const char *Tag,const char *Default)
 // ---------------------------------------------------------------------
 /* This inspects the string to see if it is true or if it is false and
    then returns the result. Several varients on true/false are checked. */
 // ---------------------------------------------------------------------
 /* This inspects the string to see if it is true or if it is false and
    then returns the result. Several varients on true/false are checked. */
-int StringToBool(string Text,int Default = -1)
+int StringToBool(string Text,int Default)
 {
    char *End;
    int Res = strtol(Text.c_str(),&End,0);   
 {
    char *End;
    int Res = strtol(Text.c_str(),&End,0);   
@@ -538,9 +563,11 @@ bool ReadMessages(int Fd, vector<string> &List)
         return false;
       
       // No data
         return false;
       
       // No data
-      if (Res <= 0)
+      if (Res < 0 && errno == EAGAIN)
         return true;
         return true;
-
+      if (Res < 0)
+        return false;
+                             
       End += Res;
       
       // Look for the end of the message
       End += Res;
       
       // Look for the end of the message
@@ -630,7 +657,8 @@ static time_t timegm(struct tm *t)
 /* This handles all 3 populare time formats including RFC 1123, RFC 1036
    and the C library asctime format. It requires the GNU library function
    'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
 /* This handles all 3 populare time formats including RFC 1123, RFC 1036
    and the C library asctime format. It requires the GNU library function
    'timegm' to convert a struct tm in UTC to a time_t. For some bizzar
-   reason the C library does not provide any such function :<*/
+   reason the C library does not provide any such function :< This also
+   handles the weird, but unambiguous FTP time format*/
 bool StrToTime(string Val,time_t &Result)
 {
    struct tm Tm;
 bool StrToTime(string Val,time_t &Result)
 {
    struct tm Tm;
@@ -641,6 +669,7 @@ bool StrToTime(string Val,time_t &Result)
    for (;*I != 0  && *I != ' '; I++);
    
    // Handle RFC 1123 time
    for (;*I != 0  && *I != ' '; I++);
    
    // Handle RFC 1123 time
+   Month[0] = 0;
    if (sscanf(I," %d %3s %d %d:%d:%d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
              &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
    {
    if (sscanf(I," %d %3s %d %d:%d:%d GMT",&Tm.tm_mday,Month,&Tm.tm_year,
              &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
    {
@@ -653,12 +682,19 @@ bool StrToTime(string Val,time_t &Result)
         // asctime format
         if (sscanf(I," %3s %d %d:%d:%d %d",Month,&Tm.tm_mday,
                    &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
         // asctime format
         if (sscanf(I," %3s %d %d:%d:%d %d",Month,&Tm.tm_mday,
                    &Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec,&Tm.tm_year) != 6)
-           return false;
+        {
+           // 'ftp' time
+           if (sscanf(Val.c_str(),"%4d%2d%2d%2d%2d%2d",&Tm.tm_year,&Tm.tm_mon,
+                      &Tm.tm_mday,&Tm.tm_hour,&Tm.tm_min,&Tm.tm_sec) != 6)
+              return false;
+           Tm.tm_mon--;
+        }       
       }
    }
    
    Tm.tm_isdst = 0;
       }
    }
    
    Tm.tm_isdst = 0;
-   Tm.tm_mon = MonthConv(Month);
+   if (Month[0] != 0)
+      Tm.tm_mon = MonthConv(Month);
    Tm.tm_year -= 1900;
    
    // Convert to local time and then to GMT
    Tm.tm_year -= 1900;
    
    // Convert to local time and then to GMT
@@ -666,31 +702,244 @@ bool StrToTime(string Val,time_t &Result)
    return true;
 }
                                                                        /*}}}*/
    return true;
 }
                                                                        /*}}}*/
+// StrToNum - Convert a fixed length string to a number                        /*{{{*/
+// ---------------------------------------------------------------------
+/* This is used in decoding the crazy fixed length string headers in 
+   tar and ar files. */
+bool StrToNum(const char *Str,unsigned long &Res,unsigned Len,unsigned Base)
+{
+   char S[30];
+   if (Len >= sizeof(S))
+      return false;
+   memcpy(S,Str,Len);
+   S[Len] = 0;
+   
+   // All spaces is a zero
+   Res = 0;
+   unsigned I;
+   for (I = 0; S[I] == ' '; I++);
+   if (S[I] == 0)
+      return true;
+   
+   char *End;
+   Res = strtoul(S,&End,Base);
+   if (End == S)
+      return false;
+   
+   return true;
+}
+                                                                       /*}}}*/
+// HexDigit - Convert a hex character into an integer                  /*{{{*/
+// ---------------------------------------------------------------------
+/* Helper for Hex2Num */
+static int HexDigit(int c)
+{   
+   if (c >= '0' && c <= '9')
+      return c - '0';
+   if (c >= 'a' && c <= 'f')
+      return c - 'a' + 10;
+   if (c >= 'A' && c <= 'F')
+      return c - 'A' + 10;
+   return 0;
+}
+                                                                       /*}}}*/
+// Hex2Num - Convert a long hex number into a buffer                   /*{{{*/
+// ---------------------------------------------------------------------
+/* The length of the buffer must be exactly 1/2 the length of the string. */
+bool Hex2Num(string Str,unsigned char *Num,unsigned int Length)
+{
+   if (Str.length() != Length*2)
+      return false;
+   
+   // Convert each digit. We store it in the same order as the string
+   int J = 0;
+   for (string::const_iterator I = Str.begin(); I != Str.end();J++, I += 2)
+   {
+      if (isxdigit(*I) == 0 || isxdigit(I[1]) == 0)
+        return false;
+      
+      Num[J] = HexDigit(I[0]) << 4;
+      Num[J] += HexDigit(I[1]);
+   }
+   
+   return true;
+}
+                                                                       /*}}}*/
+// TokSplitString - Split a string up by a given token                 /*{{{*/
+// ---------------------------------------------------------------------
+/* This is intended to be a faster splitter, it does not use dynamic
+   memories. Input is changed to insert nulls at each token location. */
+bool TokSplitString(char Tok,char *Input,char **List,
+                   unsigned long ListMax)
+{
+   // Strip any leading spaces
+   char *Start = Input;
+   char *Stop = Start + strlen(Start);
+   for (; *Start != 0 && isspace(*Start) != 0; Start++);
+
+   unsigned long Count = 0;
+   char *Pos = Start;
+   while (Pos != Stop)
+   {
+      // Skip to the next Token
+      for (; Pos != Stop && *Pos != Tok; Pos++);
+      
+      // Back remove spaces
+      char *End = Pos;
+      for (; End > Start && (End[-1] == Tok || isspace(End[-1]) != 0); End--);
+      *End = 0;
+      
+      List[Count++] = Start;
+      if (Count >= ListMax)
+      {
+        List[Count-1] = 0;
+        return false;
+      }
+      
+      // Advance pos
+      for (; Pos != Stop && (*Pos == Tok || isspace(*Pos) != 0 || *Pos == 0); Pos++);
+      Start = Pos;
+   }
+   
+   List[Count] = 0;
+   return true;
+}
+                                                                       /*}}}*/
+// RegexChoice - Simple regex list/list matcher                                /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+unsigned long RegexChoice(RxChoiceList *Rxs,const char **ListBegin,
+                     const char **ListEnd)
+{
+   for (RxChoiceList *R = Rxs; R->Str != 0; R++)
+      R->Hit = false;
+
+   unsigned long Hits = 0;
+   for (; ListBegin != ListEnd; ListBegin++)
+   {
+      // Check if the name is a regex
+      const char *I;
+      bool Regex = true;
+      for (I = *ListBegin; *I != 0; I++)
+        if (*I == '.' || *I == '?' || *I == '*' || *I == '|')
+           break;
+      if (*I == 0)
+        Regex = false;
+        
+      // Compile the regex pattern
+      regex_t Pattern;
+      if (Regex == true)
+        if (regcomp(&Pattern,*ListBegin,REG_EXTENDED | REG_ICASE |
+                    REG_NOSUB) != 0)
+           Regex = false;
+        
+      // Search the list
+      bool Done = false;
+      for (RxChoiceList *R = Rxs; R->Str != 0; R++)
+      {
+        if (R->Str[0] == 0)
+           continue;
+        
+        if (strcasecmp(R->Str,*ListBegin) != 0)
+        {
+           if (Regex == false)
+              continue;
+           if (regexec(&Pattern,R->Str,0,0,0) != 0)
+              continue;
+        }
+        Done = true;
+        
+        if (R->Hit == false)
+           Hits++;
+        
+        R->Hit = true;
+      }
+      
+      if (Regex == true)
+        regfree(&Pattern);
+      
+      if (Done == false)
+        _error->Warning(_("Selection %s not found"),*ListBegin);
+   }
+   
+   return Hits;
+}
+                                                                       /*}}}*/
+// ioprintf - C format string outputter to C++ iostreams               /*{{{*/
+// ---------------------------------------------------------------------
+/* This is used to make the internationalization strinc easier to translate
+ and to allow reordering of parameters */
+void ioprintf(ostream &out,const char *format,...) 
+{
+   va_list args;
+   va_start(args,format);
+   
+   // sprintf the description
+   char S[400];
+   vsnprintf(S,sizeof(S),format,args);
+   out << S;
+}
+                                                                       /*}}}*/
+
+// CheckDomainList - See if Host is in a , seperate list               /*{{{*/
+// ---------------------------------------------------------------------
+/* The domain list is a comma seperate list of domains that are suffix
+   matched against the argument */
+bool CheckDomainList(string Host,string List)
+{
+   const char *Start = List.c_str();
+   for (const char *Cur = List.c_str(); *Cur != 0; Cur++)
+   {
+      if (*Cur != ',')
+        continue;
+      
+      // Match the end of the string..
+      if ((Host.size() >= (unsigned)(Cur - List.c_str())) &&
+         Cur - Start != 0 &&
+         stringcasecmp(Host.c_str() + Host.length() - (Cur - Start),Host.c_str()+Host.length(),Start,Cur) == 0)
+        return true;
+      
+      Start = Cur + 1;
+   }
+   return false;
+}
+                                                                       /*}}}*/
 
 // URI::CopyFrom - Copy from an object                                 /*{{{*/
 // ---------------------------------------------------------------------
 /* This parses the URI into all of its components */
 void URI::CopyFrom(string U)
 {
 
 // URI::CopyFrom - Copy from an object                                 /*{{{*/
 // ---------------------------------------------------------------------
 /* This parses the URI into all of its components */
 void URI::CopyFrom(string U)
 {
-   string::const_iterator I = U.begin();
+   const char *I = U.c_str();
 
 
-   // Locate the first colon, this seperates the scheme
-   for (; I < U.end() && *I != ':' ; I++);
-   string::const_iterator FirstColon = I;
+   // Locate the first colon, this separates the scheme
+   for (; *I != 0  && *I != ':' ; I++);
+   const char *FirstColon = I;
 
    /* Determine if this is a host type URI with a leading double //
       and then search for the first single / */
 
    /* Determine if this is a host type URI with a leading double //
       and then search for the first single / */
-   string::const_iterator SingleSlash = I;
-   if (I + 3 < U.end() && I[1] == '/' && I[2] == '/')
+   const char *SingleSlash = I;
+   if (I + 3 < U.c_str() + U.length() && I[1] == '/' && I[2] == '/')
       SingleSlash += 3;
       SingleSlash += 3;
-   for (; SingleSlash < U.end() && *SingleSlash != '/'; SingleSlash++);
-   if (SingleSlash > U.end())
-      SingleSlash = U.end();
+   
+   /* Find the / indicating the end of the hostname, ignoring /'s in the
+      square brackets */
+   bool InBracket = false;
+   for (; SingleSlash < U.c_str() + U.length() && (*SingleSlash != '/' || InBracket == true); SingleSlash++)
+   {
+      if (*SingleSlash == '[')
+        InBracket = true;
+      if (InBracket == true && *SingleSlash == ']')
+        InBracket = false;
+   }
+   
+   if (SingleSlash > U.c_str() + U.length())
+      SingleSlash = U.c_str() + U.length();
 
    // We can now write the access and path specifiers
 
    // We can now write the access and path specifiers
-   Access = string(U,0,FirstColon - U.begin());
-   if (SingleSlash != U.end())
-      Path = string(U,SingleSlash - U.begin());
+   Access = string(U,0,FirstColon - U.c_str());
+   if (*SingleSlash != 0)
+      Path = string(U,SingleSlash - U.c_str());
    if (Path.empty() == true)
       Path = "/";
 
    if (Path.empty() == true)
       Path = "/";
 
@@ -699,40 +948,70 @@ void URI::CopyFrom(string U)
       FirstColon += 3;
    else
       FirstColon += 1;
       FirstColon += 3;
    else
       FirstColon += 1;
-   if (FirstColon >= U.end())
+   if (FirstColon >= U.c_str() + U.length())
       return;
    
    if (FirstColon > SingleSlash)
       FirstColon = SingleSlash;
    
       return;
    
    if (FirstColon > SingleSlash)
       FirstColon = SingleSlash;
    
-   // Search for the @
-   I = FirstColon;
+   // Find the colon...
+   I = FirstColon + 1;
+   if (I > SingleSlash)
+      I = SingleSlash;
+   for (; I < SingleSlash && *I != ':'; I++);
+   const char *SecondColon = I;
+   
+   // Search for the @ after the colon
    for (; I < SingleSlash && *I != '@'; I++);
    for (; I < SingleSlash && *I != '@'; I++);
-   string::const_iterator At = I;
+   const char *At = I;
    
    
-   // Colon in the @ section
-   I = FirstColon + 1;
-   for (; I < At && *I != ':'; I++);
-   string::const_iterator SecondColon = I;
-      
    // Now write the host and user/pass
    if (At == SingleSlash)
    {
       if (FirstColon < SingleSlash)
    // Now write the host and user/pass
    if (At == SingleSlash)
    {
       if (FirstColon < SingleSlash)
-        Host = string(U,FirstColon - U.begin(),SingleSlash - FirstColon);
+        Host = string(U,FirstColon - U.c_str(),SingleSlash - FirstColon);
    }
    else
    {
    }
    else
    {
-      Host = string(U,At - U.begin() + 1,SingleSlash - At - 1);
-      User = string(U,FirstColon - U.begin(),SecondColon - FirstColon);
+      Host = string(U,At - U.c_str() + 1,SingleSlash - At - 1);
+      User = string(U,FirstColon - U.c_str(),SecondColon - FirstColon);
       if (SecondColon < At)
       if (SecondColon < At)
-        Password = string(U,SecondColon - U.begin() + 1,At - SecondColon - 1);
+        Password = string(U,SecondColon - U.c_str() + 1,At - SecondColon - 1);
    }   
    
    }   
    
-   // Now we parse off a pot number from the hostname
+   // Now we parse the RFC 2732 [] hostnames.
+   unsigned long PortEnd = 0;
+   InBracket = false;
+   for (unsigned I = 0; I != Host.length();)
+   {
+      if (Host[I] == '[')
+      {
+        InBracket = true;
+        Host.erase(I,1);
+        continue;
+      }
+      
+      if (InBracket == true && Host[I] == ']')
+      {
+        InBracket = false;
+        Host.erase(I,1);
+        PortEnd = I;
+        continue;
+      }
+      I++;
+   }
+   
+   // Tsk, weird.
+   if (InBracket == true)
+   {
+      Host = string();
+      return;
+   }
+   
+   // Now we parse off a port number from the hostname
    Port = 0;
    string::size_type Pos = Host.rfind(':');
    Port = 0;
    string::size_type Pos = Host.rfind(':');
-   if (Pos == string::npos)
+   if (Pos == string::npos || Pos < PortEnd)
       return;
    
    Port = atoi(string(Host,Pos+1).c_str());
       return;
    
    Port = atoi(string(Host,Pos+1).c_str());
@@ -744,18 +1023,31 @@ void URI::CopyFrom(string U)
 /* */
 URI::operator string()
 {
 /* */
 URI::operator string()
 {
-   string Res = Access + ':';
+   string Res;
+   
+   if (Access.empty() == false)
+      Res = Access + ':';
+   
    if (Host.empty() == false)
    if (Host.empty() == false)
-   {
-      Res += "//";
+   {    
+      if (Access.empty() == false)
+        Res += "//";
+          
       if (User.empty() == false)
       {
       if (User.empty() == false)
       {
-        Res += "//" + User;
+        Res +=  User;
         if (Password.empty() == false)
            Res += ":" + Password;
         Res += "@";
       }
         if (Password.empty() == false)
            Res += ":" + Password;
         Res += "@";
       }
-      Res += Host;
+      
+      // Add RFC 2732 escaping characters
+      if (Access.empty() == false &&
+         (Host.find('/') != string::npos || Host.find(':') != string::npos))
+        Res += '[' + Host + ']';
+      else
+        Res += Host;
+      
       if (Port != 0)
       {
         char S[30];
       if (Port != 0)
       {
         char S[30];
@@ -775,3 +1067,16 @@ URI::operator string()
    return Res;
 }
                                                                        /*}}}*/
    return Res;
 }
                                                                        /*}}}*/
+// URI::SiteOnly - Return the schema and site for the URI              /*{{{*/
+// ---------------------------------------------------------------------
+/* */
+string URI::SiteOnly(string URI)
+{
+   ::URI U(URI);
+   U.User = string();
+   U.Password = string();
+   U.Path = string();
+   U.Port = 0;
+   return U;
+}
+                                                                       /*}}}*/