Use File.expand_path with require.
[puppet-modules/puppetlabs-apt.git] / lib / puppet / provider / apt_key / apt_key.rb
1 require 'date'
2 require 'open-uri'
3 require 'net/ftp'
4 require 'tempfile'
5
6 if RUBY_VERSION == '1.8.7'
7   # Mothers cry, puppies die and Ruby 1.8.7's open-uri needs to be
8   # monkeypatched to support passing in :ftp_passive_mode.
9   require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..',
10                                     'puppet_x', 'apt_key', 'patch_openuri.rb'))
11   OpenURI::Options.merge!({:ftp_active_mode => false,})
12 end
13
14 Puppet::Type.type(:apt_key).provide(:apt_key) do
15
16   KEY_LINE = {
17     :date     => '[0-9]{4}-[0-9]{2}-[0-9]{2}',
18     :key_type => '(R|D)',
19     :key_size => '\d{4}',
20     :key_id   => '[0-9a-fA-F]+',
21     :expires  => 'expire(d|s)',
22   }
23
24   confine    :osfamily => :debian
25   defaultfor :osfamily => :debian
26   commands   :apt_key  => 'apt-key'
27
28   def self.instances
29     key_array = apt_key('list').split("\n").collect do |line|
30       line_hash = key_line_hash(line)
31       next unless line_hash
32       expired = false
33
34       if line_hash[:key_expiry]
35         expired = Date.today > Date.parse(line_hash[:key_expiry])
36       end
37
38       new(
39         :name    => line_hash[:key_id],
40         :id      => line_hash[:key_id],
41         :ensure  => :present,
42         :expired => expired,
43         :expiry  => line_hash[:key_expiry],
44         :size    => line_hash[:key_size],
45         :type    => line_hash[:key_type] == 'R' ? :rsa : :dsa,
46         :created => line_hash[:key_created]
47       )
48     end
49     key_array.compact!
50   end
51
52   def self.prefetch(resources)
53     apt_keys = instances
54     resources.keys.each do |name|
55       if provider = apt_keys.find{ |key| key.name == name }
56         resources[name].provider = provider
57       end
58     end
59   end
60
61   def self.key_line_hash(line)
62     line_array = line.match(key_line_regexp).to_a
63     return nil if line_array.length < 5
64
65     return_hash = {
66       :key_id      => line_array[3],
67       :key_size    => line_array[1],
68       :key_type    => line_array[2],
69       :key_created => line_array[4],
70       :key_expiry  => nil,
71     }
72
73     return_hash[:key_expiry] = line_array[7] if line_array.length == 8
74     return return_hash
75   end
76
77   def self.key_line_regexp
78     # This regexp is trying to match the following output
79     # pub   4096R/4BD6EC30 2010-07-10 [expires: 2016-07-08]
80     # pub   1024D/CD2EFD2A 2009-12-15
81     regexp = /\A
82       pub  # match only the public key, not signatures
83       \s+  # bunch of spaces after that
84       (#{KEY_LINE[:key_size]})  # size of the key, usually a multiple of 1024
85       #{KEY_LINE[:key_type]}  # type of the key, usually R or D
86       \/  # separator between key_type and key_id
87       (#{KEY_LINE[:key_id]})  # hex id of the key
88       \s+  # bunch of spaces after that
89       (#{KEY_LINE[:date]})  # date the key was added to the keyring
90       # following an optional block which indicates if the key has an expiration
91       # date and if it has expired yet
92       (
93         \s+  # again with thes paces
94         \[  # we open with a square bracket
95         #{KEY_LINE[:expires]}  # expires or expired
96         \:  # a colon
97         \s+  # more spaces
98         (#{KEY_LINE[:date]})  # date indicating key expiry
99         \]  # we close with a square bracket
100       )?  # end of the optional block
101       \Z/x
102       regexp
103   end
104
105   def source_to_file(value)
106     if URI::parse(value).scheme.nil?
107       fail("The file #{value} does not exist") unless File.exists?(value)
108       value
109     else
110       begin
111         key = open(value, :ftp_active_mode => false).read
112       rescue OpenURI::HTTPError, Net::FTPPermError => e
113         fail("#{e.message} for #{resource[:source]}")
114       rescue SocketError
115         fail("could not resolve #{resource[:source]}")
116       else
117         tempfile(key)
118       end
119     end
120   end
121
122   def tempfile(content)
123     file = Tempfile.new('apt_key')
124     file.write content
125     file.close
126     file.path
127   end
128
129   def exists?
130     @property_hash[:ensure] == :present
131   end
132
133   def create
134     command = []
135     if resource[:source].nil? and resource[:content].nil?
136       # Breaking up the command like this is needed because it blows up
137       # if --recv-keys isn't the last argument.
138       command.push('adv', '--keyserver', resource[:server])
139       unless resource[:keyserver_options].nil?
140         command.push('--keyserver-options', resource[:keyserver_options])
141       end
142       command.push('--recv-keys', resource[:id])
143     elsif resource[:content]
144       command.push('add', tempfile(resource[:content]))
145     elsif resource[:source]
146       command.push('add', source_to_file(resource[:source]))
147     # In case we really screwed up, better safe than sorry.
148     else
149       fail("an unexpected condition occurred while trying to add the key: #{resource[:id]}")
150     end
151     apt_key(command)
152     @property_hash[:ensure] = :present
153   end
154
155   def destroy
156     apt_key('del', resource[:id])
157     @property_hash.clear
158   end
159
160   def read_only(value)
161     fail('This is a read-only property.')
162   end
163
164   mk_resource_methods
165
166   # Needed until PUP-1470 is fixed and we can drop support for Puppet versions
167   # before that.
168   def expired
169     @property_hash[:expired]
170   end
171
172   # Alias the setters of read-only properties
173   # to the read_only function.
174   alias :created= :read_only
175   alias :expired= :read_only
176   alias :expiry=  :read_only
177   alias :size=    :read_only
178   alias :type=    :read_only
179 end