summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util/ldap/connection.rb
blob: abcc07ecbb5ea187bb9326f122f686d70ca3655b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#
#  Created by Luke Kanies on 2008-3-23.
#  Copyright (c) 2008. All rights reserved.
require 'puppet/util/ldap'

class Puppet::Util::Ldap::Connection
    attr_accessor :host, :port, :user, :password, :reset, :ssl

    attr_reader :connection

    def close
        connection.unbind if connection.bound?
    end

    def initialize(host, port, options = {})
        raise Puppet::Error, "Could not set up LDAP Connection: Missing ruby/ldap libraries" unless Puppet.features.ldap?

        @host, @port = host, port

        options.each do |param, value|
            begin
                send(param.to_s + "=", value)
            rescue
                raise ArgumentError, "LDAP connections do not support %s parameters" % param
            end
        end
    end

    # Create a per-connection unique name.
    def name
        [host, port, user, password, ssl].collect { |p| p.to_s }.join("/")
    end

    # Should we reset the connection?
    def reset?
        reset
    end

    # Start our ldap connection.
    def start
        begin
            case ssl
            when :tls:
                @connection = LDAP::SSLConn.new(host, port, true)
            when true:
                @connection = LDAP::SSLConn.new(host, port)
            else
                @connection = LDAP::Conn.new(host, port)
            end
            @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
            @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)
            @connection.simple_bind(user, password)
        rescue => detail
            raise Puppet::Error, "Could not connect to LDAP: %s" % detail
        end
    end
end