@@ -83,9 +83,19 @@ func ParseDN(str string) (*DN, error) {
8383 attribute := new (AttributeTypeAndValue )
8484 escaping := false
8585
86+ unescapedTrailingSpaces := 0
87+ stringFromBuffer := func () string {
88+ s := buffer .String ()
89+ s = s [0 : len (s )- unescapedTrailingSpaces ]
90+ buffer .Reset ()
91+ unescapedTrailingSpaces = 0
92+ return s
93+ }
94+
8695 for i := 0 ; i < len (str ); i ++ {
8796 char := str [i ]
8897 if escaping {
98+ unescapedTrailingSpaces = 0
8999 escaping = false
90100 switch char {
91101 case ' ' , '"' , '#' , '+' , ',' , ';' , '<' , '=' , '>' , '\\' :
@@ -107,10 +117,10 @@ func ParseDN(str string) (*DN, error) {
107117 buffer .WriteByte (dst [0 ])
108118 i ++
109119 } else if char == '\\' {
120+ unescapedTrailingSpaces = 0
110121 escaping = true
111122 } else if char == '=' {
112- attribute .Type = buffer .String ()
113- buffer .Reset ()
123+ attribute .Type = stringFromBuffer ()
114124 // Special case: If the first character in the value is # the
115125 // following data is BER encoded so we can just fast forward
116126 // and decode.
@@ -133,24 +143,33 @@ func ParseDN(str string) (*DN, error) {
133143 }
134144 } else if char == ',' || char == '+' {
135145 // We're done with this RDN or value, push it
136- attribute .Value = buffer . String ()
146+ attribute .Value = stringFromBuffer ()
137147 rdn .Attributes = append (rdn .Attributes , attribute )
138148 attribute = new (AttributeTypeAndValue )
139149 if char == ',' {
140150 dn .RDNs = append (dn .RDNs , rdn )
141151 rdn = new (RelativeDN )
142152 rdn .Attributes = make ([]* AttributeTypeAndValue , 0 )
143153 }
144- buffer .Reset ()
154+ } else if char == ' ' && buffer .Len () == 0 {
155+ // ignore unescaped leading spaces
156+ continue
145157 } else {
158+ if char == ' ' {
159+ // Track unescaped spaces in case they are trailing and we need to remove them
160+ unescapedTrailingSpaces ++
161+ } else {
162+ // Reset if we see a non-space char
163+ unescapedTrailingSpaces = 0
164+ }
146165 buffer .WriteByte (char )
147166 }
148167 }
149168 if buffer .Len () > 0 {
150169 if len (attribute .Type ) == 0 {
151170 return nil , errors .New ("DN ended with incomplete type, value pair" )
152171 }
153- attribute .Value = buffer . String ()
172+ attribute .Value = stringFromBuffer ()
154173 rdn .Attributes = append (rdn .Attributes , attribute )
155174 dn .RDNs = append (dn .RDNs , rdn )
156175 }
0 commit comments