-
Notifications
You must be signed in to change notification settings - Fork 0
/
plume.rb
93 lines (73 loc) · 2.12 KB
/
plume.rb
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#
# plume.rb - Plume! Plume, plume, plume!
#
require 'rubygems'
require 'bundler/setup'
require 'eventmachine'
require 'msgpack'
require 'openssl'
require_relative 'conn/conn.rb'
require_relative 'conn/plume_udp.rb'
require_relative 'util.rb'
class PlumeServer < PlumeConn
LEGAL_OPS = %w(route udp)
def initialize(key_file, crt_file, conn_table, udp_reqs)
super key_file, crt_file
@conns = conn_table
@udp_reqs = udp_reqs
end
#
# Add a connection to our table.
#
def ssl_handshake_completed
@peer_handle = cert_cn(get_peer_cert)
@conns[@peer_handle] = self
end
#
# Remove a dropped connection from our table.
#
def unbind
@conns.delete @peer_handle
end
private
#
# Route a message to a peer, via another Plume server or direct connection.
#
def route(cert, peer, op, payload=nil)
# Validate the peer name.
email = parse_email(peer)
return close_connection if email.nil?
# If we have a connection to the peer, route directly.
if @conns[peer]
return @conns[peer].send_data [op, [cert, payload]].to_msgpack
end
addr, port = '', 0
# Determine the address and port of the peer's Plume server.
addr, port = dns_get_srv("_plume._tcp.#{email.domain}")
return close_connection if addr.nil? or port.nil?
# Route the connection request to the peer's Plume server.
EM.connect(addr, port, PlumeServer,
key_file, crt_file, @conns, @udp_reqs) do |conn|
conn.send_data ['route', [cert, peer, op, payload]].to_msgpack
end
end
#
# Register a UDP self-identification request.
#
def udp(cert, cookie)
@udp_reqs[cookie] = self
send_data ['ack_udp', [cookie]].to_msgpack
end
end
conns = {}
udp_reqs = {}
plume_dir = File.expand_path "~/.plume/#{ENV['PLUME_HOSTNAME'].to_s}"
key_file = ENV['PLUME_KEY'] || plume_dir + '/plume.key'
crt_file = ENV['PLUME_CRT'] || plume_dir + '/plume.crt'
port = ARGV[0] || '42000'
udp_port = '42002'
EM.run {
EM.start_server('0.0.0.0', port, PlumeServer,
key_file, crt_file, conns, udp_reqs)
EM.open_datagram_socket '0.0.0.0', udp_port, PlumeUDPEcho, udp_reqs
}