123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158 |
- package ldap
- import (
- "bytes"
- enchex "encoding/hex"
- "errors"
- "fmt"
- "strings"
- ber "gopkg.in/asn1-ber.v1"
- )
- type AttributeTypeAndValue struct {
-
- Type string
-
- Value string
- }
- type RelativeDN struct {
- Attributes []*AttributeTypeAndValue
- }
- type DN struct {
- RDNs []*RelativeDN
- }
- func ParseDN(str string) (*DN, error) {
- dn := new(DN)
- dn.RDNs = make([]*RelativeDN, 0)
- rdn := new(RelativeDN)
- rdn.Attributes = make([]*AttributeTypeAndValue, 0)
- buffer := bytes.Buffer{}
- attribute := new(AttributeTypeAndValue)
- escaping := false
- for i := 0; i < len(str); i++ {
- char := str[i]
- if escaping {
- escaping = false
- switch char {
- case ' ', '"', '#', '+', ',', ';', '<', '=', '>', '\\':
- buffer.WriteByte(char)
- continue
- }
-
- if len(str) == i+1 {
- return nil, errors.New("Got corrupted escaped character")
- }
- dst := []byte{0}
- n, err := enchex.Decode([]byte(dst), []byte(str[i:i+2]))
- if err != nil {
- return nil, fmt.Errorf("Failed to decode escaped character: %s", err)
- } else if n != 1 {
- return nil, fmt.Errorf("Expected 1 byte when un-escaping, got %d", n)
- }
- buffer.WriteByte(dst[0])
- i++
- } else if char == '\\' {
- escaping = true
- } else if char == '=' {
- attribute.Type = buffer.String()
- buffer.Reset()
-
-
-
- if len(str) > i+1 && str[i+1] == '#' {
- i += 2
- index := strings.IndexAny(str[i:], ",+")
- data := str
- if index > 0 {
- data = str[i : i+index]
- } else {
- data = str[i:]
- }
- rawBER, err := enchex.DecodeString(data)
- if err != nil {
- return nil, fmt.Errorf("Failed to decode BER encoding: %s", err)
- }
- packet := ber.DecodePacket(rawBER)
- buffer.WriteString(packet.Data.String())
- i += len(data) - 1
- }
- } else if char == ',' || char == '+' {
-
- attribute.Value = buffer.String()
- rdn.Attributes = append(rdn.Attributes, attribute)
- attribute = new(AttributeTypeAndValue)
- if char == ',' {
- dn.RDNs = append(dn.RDNs, rdn)
- rdn = new(RelativeDN)
- rdn.Attributes = make([]*AttributeTypeAndValue, 0)
- }
- buffer.Reset()
- } else {
- buffer.WriteByte(char)
- }
- }
- if buffer.Len() > 0 {
- if len(attribute.Type) == 0 {
- return nil, errors.New("DN ended with incomplete type, value pair")
- }
- attribute.Value = buffer.String()
- rdn.Attributes = append(rdn.Attributes, attribute)
- dn.RDNs = append(dn.RDNs, rdn)
- }
- return dn, nil
- }
|