summaryrefslogtreecommitdiff
path: root/lib/nickserver/hkp/fetch_key.rb
blob: c24b2c7b47ed1e9936f48300075a36d3ea89ae50 (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
require 'em-http'

#
# Fetch keys via HKP
# http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00
#

module Nickserver; module HKP

  class FetchKey
    include EM::Deferrable

    def get(uid)
      FetchKeyInfo.new.search(uid).callback {|key_info_list|
        best = pick_best_key(key_info_list)
        get_key_by_fingerprint(best.keyid) {|key|
          self.succeed key
        }
      }.errback {|status, msg|
        self.fail status, msg
      }
      self
    end

    #
    # fetches ascii armored OpenPGP public key from the keyserver
    #
    def get_key_by_fingerprint(key_id)
      params = {:op => 'get', :search => "0x" + key_id, :exact => 'on', :options => 'mr'}
      http = EventMachine::HttpRequest.new(Config.hkp_url).get(:query => params)
      http.callback {
        if http.response_header.status != 200
          self.fail http.response_header.status, "HKP Request failed"
        else
          yield http.response
        end
      }
      http.errback {
        self.fail 500, http.error
      }
    end

    protected

    #
    # for now, just pick the newest key.
    #
    # in the future, we should perhaps pick the newest key
    # that is signed by the oldest key.
    #
    def pick_best_key(key_info_list)
      key_info_list.sort {|a,b| a.creationdate <=> b.creationdate}.last
    end
  end

end; end