vici: Add a ruby gem providing a native vici interface
[strongswan.git] / src / libcharon / plugins / vici / ruby / lib / vici.rb
1 ##
2 # The Vici module implements a native ruby client side library for the
3 # strongSwan VICI protocol. The Connection class provides a high-level
4 # interface to issue requests or listen for events.
5 #
6 # Copyright (C) 2014 Martin Willi
7 # Copyright (C) 2014 revosec AG
8 #
9 # Permission is hereby granted, free of charge, to any person obtaining a copy
10 # of this software and associated documentation files (the "Software"), to deal
11 # in the Software without restriction, including without limitation the rights
12 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 # copies of the Software, and to permit persons to whom the Software is
14 # furnished to do so, subject to the following conditions:
15 #
16 # The above copyright notice and this permission notice shall be included in
17 # all copies or substantial portions of the Software.
18 #
19 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 # THE SOFTWARE.
26
27 module Vici
28
29 ##
30 # Vici specific exception all others inherit from
31 class Error < StandardError
32 end
33
34 ##
35 # Error while parsing a vici message from the daemon
36 class ParseError < Error
37 end
38
39 ##
40 # Error while encoding a vici message from ruby data structures
41 class EncodeError < Error
42 end
43
44 ##
45 # Error while exchanging messages over the vici Transport layer
46 class TransportError < Error
47 end
48
49 ##
50 # Generic vici command execution error
51 class CommandError < Error
52 end
53
54 ##
55 # Error if an issued vici command is unknown by the daemon
56 class CommandUnknownError < CommandError
57 end
58
59 ##
60 # Error if a command failed to execute in the daemon
61 class CommandExecError < CommandError
62 end
63
64 ##
65 # Generic vici event handling error
66 class EventError < Error
67 end
68
69 ##
70 # Tried to register to / unregister from an unknown vici event
71 class EventUnknownError < EventError
72 end
73
74 ##
75 # Exception to raise from an event listening closure to stop listening
76 class StopEventListening < Exception
77 end
78
79
80 ##
81 # The Message class provides the low level encoding and decoding of vici
82 # protocol messages. Directly using this class is usually not required.
83 class Message
84
85 SECTION_START = 1
86 SECTION_END = 2
87 KEY_VALUE = 3
88 LIST_START = 4
89 LIST_ITEM = 5
90 LIST_END = 6
91
92 def initialize(data = "")
93 if data == nil
94 @root = Hash.new()
95 elsif data.is_a?(Hash)
96 @root = data
97 else
98 @encoded = data
99 end
100 end
101
102 ##
103 # Get the raw byte encoding of an on-the-wire message
104 def encoding
105 if @encoded == nil
106 @encoded = encode(@root)
107 end
108 @encoded
109 end
110
111 ##
112 # Get the root element of the parsed ruby data structures
113 def root
114 if @root == nil
115 @root = parse(@encoded)
116 end
117 @root
118 end
119
120 private
121
122 def encode_name(name)
123 [name.length].pack("c") << name
124 end
125
126 def encode_value(value)
127 if value.class != String
128 value = value.to_s
129 end
130 [value.length].pack("n") << value
131 end
132
133 def encode_kv(encoding, key, value)
134 encoding << KEY_VALUE << encode_name(key) << encode_value(value)
135 end
136
137 def encode_section(encoding, key, value)
138 encoding << SECTION_START << encode_name(key)
139 encoding << encode(value) << SECTION_END
140 end
141
142 def encode_list(encoding, key, value)
143 encoding << LIST_START << encode_name(key)
144 value.each do |item|
145 encoding << LIST_ITEM << encode_value(item)
146 end
147 encoding << LIST_END
148 end
149
150 def encode(node)
151 encoding = ""
152 node.each do |key, value|
153 case value.class
154 when String, Fixnum, true, false
155 encoding = encode_kv(encoding, key, value)
156 else
157 if value.is_a?(Hash)
158 encoding = encode_section(encoding, key, value)
159 elsif value.is_a?(Array)
160 encoding = encode_list(encoding, key, value)
161 else
162 encoding = encode_kv(encoding, key, value)
163 end
164 end
165 end
166 encoding
167 end
168
169 def parse_name(encoding)
170 len = encoding.unpack("c")[0]
171 name = encoding[1, len]
172 return encoding[(1 + len)..-1], name
173 end
174
175 def parse_value(encoding)
176 len = encoding.unpack("n")[0]
177 value = encoding[2, len]
178 return encoding[(2 + len)..-1], value
179 end
180
181 def parse(encoding)
182 stack = [Hash.new]
183 list = nil
184 while encoding.length != 0 do
185 type = encoding.unpack("c")[0]
186 encoding = encoding[1..-1]
187 case type
188 when SECTION_START
189 encoding, name = parse_name(encoding)
190 stack.push(stack[-1][name] = Hash.new)
191 when SECTION_END
192 if stack.length() == 1
193 raise ParseError, "unexpected section end"
194 end
195 stack.pop()
196 when KEY_VALUE
197 encoding, name = parse_name(encoding)
198 encoding, value = parse_value(encoding)
199 stack[-1][name] = value
200 when LIST_START
201 encoding, name = parse_name(encoding)
202 stack[-1][name] = []
203 list = name
204 when LIST_ITEM
205 raise ParseError, "unexpected list item" if list == nil
206 encoding, value = parse_value(encoding)
207 stack[-1][list].push(value)
208 when LIST_END
209 raise ParseError, "unexpected list end" if list == nil
210 list = nil
211 else
212 raise ParseError, "invalid type: #{type}"
213 end
214 end
215 if stack.length() > 1
216 raise ParseError, "unexpected message end"
217 end
218 stack[0]
219 end
220 end
221
222
223 ##
224 # The Transport class implements to low level segmentation of packets
225 # to the underlying transport stream. Directly using this class is usually
226 # not required.
227 class Transport
228
229 CMD_REQUEST = 0
230 CMD_RESPONSE = 1
231 CMD_UNKNOWN = 2
232 EVENT_REGISTER = 3
233 EVENT_UNREGISTER = 4
234 EVENT_CONFIRM = 5
235 EVENT_UNKNOWN = 6
236 EVENT = 7
237
238 ##
239 # Create a transport layer using a provided socket for communication.
240 def initialize(socket)
241 @socket = socket
242 @events = Hash.new
243 end
244
245 ##
246 # Write a packet prefixed by its length over the transport socket. Type
247 # specifies the message, the optional label and message get appended.
248 def write(type, label, message)
249 encoding = ""
250 if label
251 encoding << label.length << label
252 end
253 if message
254 encoding << message.encoding
255 end
256 @socket.send([encoding.length + 1, type].pack("Nc") + encoding, 0)
257 end
258
259 ##
260 # Read a packet from the transport socket. Returns the packet type, and
261 # if available in the packet a label and the contained message.
262 def read
263 len = @socket.recv(4).unpack("N")[0]
264 encoding = @socket.recv(len)
265 type = encoding.unpack("c")[0]
266 len = 1
267 case type
268 when CMD_REQUEST, EVENT_REGISTER, EVENT_UNREGISTER, EVENT
269 label = encoding[2, encoding[1].unpack("c")[0]]
270 len += label.length + 1
271 when CMD_RESPONSE, CMD_UNKNOWN, EVENT_CONFIRM, EVENT_UNKNOWN
272 label = nil
273 else
274 raise TransportError, "invalid message: #{type}"
275 end
276 if encoding.length == len
277 return type, label, Message.new
278 end
279 return type, label, Message.new(encoding[len..-1])
280 end
281
282 def dispatch_event(name, message)
283 @events[name].each do |handler|
284 handler.call(name, message)
285 end
286 end
287
288 def read_and_dispatch_event
289 type, label, message = read
290 p
291 if type == EVENT
292 dispatch_event(label, message)
293 else
294 raise TransportError, "unexpected message: #{type}"
295 end
296 end
297
298 def read_and_dispatch_events
299 loop do
300 type, label, message = read
301 if type == EVENT
302 dispatch_event(label, message)
303 else
304 return type, label, message
305 end
306 end
307 end
308
309 ##
310 # Send a command with a given name, and optionally a message. Returns
311 # the reply message on success.
312 def request(name, message = nil)
313 write(CMD_REQUEST, name, message)
314 type, label, message = read_and_dispatch_events
315 case type
316 when CMD_RESPONSE
317 return message
318 when CMD_UNKNOWN
319 raise CommandUnknownError, name
320 else
321 raise CommandError, "invalid response for #{name}"
322 end
323 end
324
325 ##
326 # Register a handler method for the given event name
327 def register(name, handler)
328 write(EVENT_REGISTER, name, nil)
329 type, label, message = read_and_dispatch_events
330 case type
331 when EVENT_CONFIRM
332 if @events.has_key?(name)
333 @events[name] += [handler]
334 else
335 @events[name] = [handler];
336 end
337 when EVENT_UNKNOWN
338 raise EventUnknownError, name
339 else
340 raise EventError, "invalid response for #{name} register"
341 end
342 end
343
344 ##
345 # Unregister a handler method for the given event name
346 def unregister(name, handler)
347 write(EVENT_UNREGISTER, name, nil)
348 type, label, message = read_and_dispatch_events
349 case type
350 when EVENT_CONFIRM
351 @events[name] -= [handler]
352 when EVENT_UNKNOWN
353 raise EventUnknownError, name
354 else
355 raise EventError, "invalid response for #{name} unregister"
356 end
357 end
358 end
359
360
361 ##
362 # The Connection class provides the high-level interface to monitor, configure
363 # and control the IKE daemon. It takes a connected stream-oriented Socket for
364 # the communication with the IKE daemon.
365 #
366 # This class takes and returns ruby objects for the exchanged message data.
367 # * Sections get encoded as Hash, containing other sections as Hash, or
368 # * Key/Values, where the values are Strings as Hash values
369 # * Lists get encoded as Arrays with String values
370 # Non-String values that are not a Hash nor an Array get converted with .to_s
371 # during encoding.
372 class Connection
373
374 def initialize(socket)
375 @transp = Transport.new(socket)
376 end
377
378 ##
379 # List matching loaded connections. The provided closure is invoked
380 # for each matching connection.
381 def list_conns(match = nil, &block)
382 call_with_event("list-conns", Message.new(match), "list-conn", &block)
383 end
384
385 ##
386 # List matching active SAs. The provided closure is invoked for each
387 # matching SA.
388 def list_sas(match = nil, &block)
389 call_with_event("list-sas", Message.new(match), "list-sa", &block)
390 end
391
392 ##
393 # List matching installed policies. The provided closure is invoked
394 # for each matching policy.
395 def list_policies(match, &block)
396 call_with_event("list-policies", Message.new(match), "list-policy",
397 &block)
398 end
399
400 ##
401 # List matching loaded certificates. The provided closure is invoked
402 # for each matching certificate definition.
403 def list_certs(match = nil, &block)
404 call_with_event("list-certs", Message.new(match), "list-cert", &block)
405 end
406
407 ##
408 # Load a connection into the daemon.
409 def load_conn(conn)
410 check_success(@transp.request("load-conn", Message.new(conn)))
411 end
412
413 ##
414 # Unload a connection from the daemon.
415 def unload_conn(conn)
416 check_success(@transp.request("unload-conn", Message.new(conn)))
417 end
418
419 ##
420 # Get the names of connections managed by vici.
421 def get_conns()
422 @transp.request("get-conns").root
423 end
424
425 ##
426 # Clear all loaded credentials.
427 def clear_creds()
428 check_success(@transp.request("clear-creds"))
429 end
430
431 ##
432 # Load a certificate into the daemon.
433 def load_cert(cert)
434 check_success(@transp.request("load-cert", Message.new(cert)))
435 end
436
437 ##
438 # Load a private key into the daemon.
439 def load_key(key)
440 check_success(@transp.request("load-key", Message.new(key)))
441 end
442
443 ##
444 # Load a shared key into the daemon.
445 def load_shared(shared)
446 check_success(@transp.request("load-shared", Message.new(shared)))
447 end
448
449 ##
450 # Load a virtual IP / attribute pool
451 def load_pool(pool)
452 check_success(@transp.request("load-pool", Message.new(pool)))
453 end
454
455 ##
456 # Unload a virtual IP / attribute pool
457 def unload_pool(pool)
458 check_success(@transp.request("unload-pool", Message.new(pool)))
459 end
460
461 ##
462 # Get the currently loaded pools.
463 def get_pools()
464 @transp.request("get-pools").root
465 end
466
467 ##
468 # Initiate a connection. The provided closure is invoked for each log line.
469 def initiate(options, &block)
470 check_success(call_with_event("initiate", Message.new(options),
471 "control-log", &block))
472 end
473
474 ##
475 # Terminate a connection. The provided closure is invoked for each log line.
476 def terminate(options, &block)
477 check_success(call_with_event("terminate", Message.new(options),
478 "control-log", &block))
479 end
480
481 ##
482 # Install a shunt/route policy.
483 def install(policy)
484 check_success(@transp.request("install", Message.new(policy)))
485 end
486
487 ##
488 # Uninstall a shunt/route policy.
489 def uninstall(policy)
490 check_success(@transp.request("uninstall", Message.new(policy)))
491 end
492
493 ##
494 # Reload strongswan.conf settings.
495 def reload_settings
496 check_success(@transp.request("reload-settings", nil))
497 end
498
499 ##
500 # Get daemon statistics and information.
501 def stats
502 @transp.request("stats", nil).root
503 end
504
505 ##
506 # Get daemon version information
507 def version
508 @transp.request("version", nil).root
509 end
510
511 ##
512 # Listen for a set of event messages. This call is blocking, and invokes
513 # the passed closure for each event received. The closure receives the
514 # event name and the event message as argument. To stop listening, the
515 # closure may raise a StopEventListening exception, the only catched
516 # exception.
517 def listen_events(events, &block)
518 self.class.instance_eval do
519 define_method(:listen_event) do |label, message|
520 block.call(label, message.root)
521 end
522 end
523 events.each do |event|
524 @transp.register(event, method(:listen_event))
525 end
526 begin
527 loop do
528 @transp.read_and_dispatch_event
529 end
530 rescue StopEventListening
531 ensure
532 events.each do |event|
533 @transp.unregister(event, method(:listen_event))
534 end
535 end
536 end
537
538 ##
539 # Issue a command request, but register for a specific event while the
540 # command is active. VICI uses this mechanism to stream potentially large
541 # data objects continuously. The provided closure is invoked for all
542 # event messages.
543 def call_with_event(command, request, event, &block)
544 self.class.instance_eval do
545 define_method(:call_event) do |label, message|
546 block.call(message.root)
547 end
548 end
549 @transp.register(event, method(:call_event))
550 begin
551 reply = @transp.request(command, request)
552 ensure
553 @transp.unregister(event, method(:call_event))
554 end
555 reply
556 end
557
558 ##
559 # Check if the reply of a command indicates "success", otherwise raise a
560 # CommandExecError exception
561 def check_success(reply)
562 root = reply.root
563 if root["success"] != "yes"
564 raise CommandExecError, root["errmsg"]
565 end
566 root
567 end
568 end
569 end