liberic 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/liberic/boot.rb CHANGED
@@ -4,8 +4,82 @@ module Liberic
4
4
 
5
5
  extend self
6
6
 
7
+ # Loads the ERiC library and initializes it (+EricInitialisiere()+).
8
+ #
9
+ # <tt>require "liberic"</tt> calls this with the defaults. To control when
10
+ # and how ERiC is initialized, require <tt>"liberic/core"</tt> instead (for
11
+ # example with <tt>gem "liberic", require: "liberic/core"</tt>) and call
12
+ # +boot!+ yourself:
13
+ #
14
+ # Liberic.boot!(eric_home: "/opt/ERiC-43.5.4.0/Linux-x86_64", log_path: "log/eric")
15
+ #
16
+ # +eric_home+ the SDK directory containing +lib/libericapi.so+ (default: ERIC_HOME, then ERIC_HOME_40)
17
+ # +plugin_path+ the directory searched for ERiC plugins (default: ERiC's library directory)
18
+ # +log_path+ the directory for +eric.log+ (default: the system's temporary directory).
19
+ # ERiC cannot change it after initialization. ERiC stops writing
20
+ # +eric.log+ once +Liberic.config+ is first used, unless
21
+ # <tt>Liberic.config.log_file = true</tt>; see +Config#log_file=+.
22
+ #
23
+ # ERiC is initialized once per process; calling +boot!+ again raises
24
+ # +InitializationError+. ERiC's single-threading API is not thread safe.
25
+ # If initialization fails after loading the library, a retry must use the
26
+ # same +eric_home+: the native API is already bound to that SDK.
27
+ def boot!(eric_home: nil, plugin_path: nil, log_path: nil)
28
+ raise InitializationError.new('ERiC has already been initialized') if booted?
29
+
30
+ home = eric_home || ENV['ERIC_HOME'] || ENV['ERIC_HOME_40'] || raise(
31
+ InitializationError.new(
32
+ 'ERIC_HOME or ERIC_HOME_40 environment variable not found ' \
33
+ '(set it to the ERiC SDK directory, or run `bundle exec rake eric:install`)'
34
+ )
35
+ )
36
+ home = File.expand_path(home)
37
+ if @loaded_eric_home && @loaded_eric_home != home
38
+ raise InitializationError.new("ERiC is already loaded from #{@loaded_eric_home}; cannot change eric_home to #{home} in this process")
39
+ end
40
+ plugin_path = plugin_path && File.expand_path(plugin_path)
41
+ log_path = log_path && File.expand_path(log_path)
42
+
43
+ previous_home = @eric_home
44
+ @eric_home = home # SDK::API uses library_path while loading.
45
+ begin
46
+ require 'liberic/sdk/api'
47
+ rescue LoadError, StandardError
48
+ @eric_home = previous_home
49
+ raise
50
+ end
51
+ @loaded_eric_home = home
52
+
53
+ code = SDK::API.initialisiere(plugin_path, log_path)
54
+ unless code == SDK::Fehlercodes::ERIC_OK
55
+ raise InitializationError.new("EricInitialisiere failed: #{Helpers::Invocation.error_name(code)} (#{code})")
56
+ end
57
+ @plugin_path = plugin_path
58
+ @log_path = log_path
59
+ define_home_constants
60
+ @booted = true
61
+
62
+ check_eric_version!
63
+ true
64
+ end
65
+
66
+ def booted?
67
+ @booted == true
68
+ end
69
+
7
70
  def eric_home
8
- ERIC_HOME
71
+ @eric_home || ENV['ERIC_HOME'] || ENV['ERIC_HOME_40']
72
+ end
73
+
74
+ # The directory passed to +boot!+ as +log_path+, or +nil+ if ERiC writes
75
+ # +eric.log+ to the system's temporary directory.
76
+ attr_reader :log_path
77
+
78
+ # The directory passed to +boot!+ as +plugin_path+, or +nil+ for ERiC's default.
79
+ attr_reader :plugin_path
80
+
81
+ def library_folder
82
+ File.expand_path('lib', eric_home)
9
83
  end
10
84
 
11
85
  def library_path
@@ -16,17 +90,9 @@ module Liberic
16
90
  else
17
91
  'dll'
18
92
  end
19
- File.expand_path("libericapi.#{suffix}", ERIC_LIB_FOLDER)
93
+ File.expand_path("libericapi.#{suffix}", library_folder)
20
94
  end
21
95
 
22
- ERIC_HOME = ENV['ERIC_HOME'] || ENV['ERIC_HOME_40'] || raise(
23
- InitializationError.new(
24
- 'ERIC_HOME or ERIC_HOME_40 environment variable not found ' \
25
- '(set it to the ERiC SDK directory, or run `bundle exec rake eric:install`)'
26
- )
27
- )
28
- ERIC_LIB_FOLDER = File.expand_path('lib', ERIC_HOME)
29
-
30
96
  def check_eric_version!
31
97
  version_response = Response::Version.new(
32
98
  Helpers::Invocation.with_result_buffer do |handle|
@@ -40,4 +106,13 @@ module Liberic
40
106
  warn "ERiC #{SDK::Configuration::LIBERICAPI_VERSION.join(', ')} required, but #{eric_version} found."
41
107
  end
42
108
  end
109
+
110
+ private
111
+
112
+ # ERIC_HOME and ERIC_LIB_FOLDER were defined when the gem was required in
113
+ # earlier versions; keep them for applications that use them.
114
+ def define_home_constants
115
+ const_set(:ERIC_HOME, @eric_home) unless const_defined?(:ERIC_HOME, false)
116
+ const_set(:ERIC_LIB_FOLDER, library_folder) unless const_defined?(:ERIC_LIB_FOLDER, false)
117
+ end
43
118
  end
@@ -4,10 +4,40 @@ module Liberic
4
4
  class Certificate
5
5
  attr_reader :features, :handle
6
6
 
7
+ # Bits of +iInfoPinSupport+ as returned by +EricGetHandleToCertificate()+
8
+ # (see the ERiC API reference). A value without any of the +PIN_REQUIRED_*+
9
+ # bits means that no PIN is needed.
10
+ PIN_REQUIRED_FOR_SIGNATURE = 0x01
11
+ PIN_REQUIRED_FOR_DECRYPTION = 0x02
12
+ PIN_REQUIRED_FOR_CERT_ENCRYPTION = 0x04
13
+ PIN_REQUIRED_MASK = PIN_REQUIRED_FOR_SIGNATURE | PIN_REQUIRED_FOR_DECRYPTION | PIN_REQUIRED_FOR_CERT_ENCRYPTION
14
+ PIN_STATUS_OK = 0x10
15
+ PIN_STATUS_LAST_ATTEMPT_FAILED = 0x20
16
+ PIN_STATUS_LOCK_ON_NEXT_FAILURE = 0x40
17
+ PIN_STATUS_LOCKED = 0x80
18
+
19
+ # Opens a certificate from a PKCS#12 container in memory
20
+ # (+EricZertifikatOeffnenAusBytes()+), for example one read from a
21
+ # database or a secrets store, without writing it to disk.
22
+ #
23
+ # +pkcs12+ the content of the pfx file (a String, binary)
24
+ # +pin+ the container's PIN or password. ERiC only accepts password
25
+ # protected containers.
26
+ #
27
+ # The native copies of the container and the PIN made for ERiC are
28
+ # overwritten with zero bytes after the call. +features+ is +nil+:
29
+ # ERiC does not report the PIN features for certificates opened this way.
30
+ #
31
+ # cert = Liberic::Certificate.from_bytes(File.binread('cert.pfx'), pin)
32
+ def self.from_bytes(pkcs12, pin)
33
+ allocate.tap { |certificate| certificate.send(:open_from_bytes, pkcs12, pin) }
34
+ end
35
+
7
36
  # +cert_file+ path to a pfx file (Portal-Zertifikat)
8
37
  # +pin+ the pin for the certificate (if applicable, string)
9
38
  def initialize(cert_file, pin)
10
39
  @pin = pin
40
+ @issued_encryption_params = ObjectSpace::WeakMap.new
11
41
  ch = FFI::MemoryPointer.new(:uint32, 1)
12
42
  cert_feature_flag_pointer = FFI::MemoryPointer.new(:uint32, 1)
13
43
 
@@ -16,18 +46,7 @@ module Liberic
16
46
  )
17
47
 
18
48
  @handle = ch.get_uint32(0)
19
-
20
- flags = cert_feature_flag_pointer.get_uint32(0)
21
- @features = PinFeatures.new(
22
- (flags & 0x00) != 0,
23
- (flags & 0x01) != 0,
24
- (flags & 0x02) != 0,
25
- (flags & 0x04) != 0,
26
- (flags & 0x10) != 0,
27
- (flags & 0x20) != 0,
28
- (flags & 0x40) != 0,
29
- (flags & 0x80) != 0
30
- )
49
+ @features = PinFeatures.from_flags(cert_feature_flag_pointer.get_uint32(0))
31
50
  end
32
51
 
33
52
  # Returns the result of +EricHoleZertifikatEigenschaften()+
@@ -39,20 +58,67 @@ module Liberic
39
58
  end
40
59
 
41
60
  # Returns a +SDK::Types::VerschluesselungsParameter+ data structure that can be passed on to
42
- # Process.execute
61
+ # Process#execute.
62
+ #
63
+ # The struct keeps its own native copy of the PIN. That copy is overwritten
64
+ # with zero bytes by +release_handle!+, or after the block if one is given:
65
+ #
66
+ # cert.encryption_params do |params|
67
+ # filing.execute(action: :submit, encryption: params)
68
+ # end
43
69
  def encryption_params
44
70
  params = SDK::Types::VerschluesselungsParameter.new
45
71
 
46
72
  params[:version] = 3
47
73
  params[:zertifikatHandle] = @handle
48
- params[:pin] = FFI::MemoryPointer.from_string(@pin).address
74
+ params.set_string(:pin, @pin)
49
75
 
50
- params
76
+ return remember_encryption_params(params) unless block_given?
77
+
78
+ begin
79
+ yield params
80
+ ensure
81
+ params.wipe_pin!
82
+ end
51
83
  end
52
84
 
85
+ # Closes the certificate handle and wipes the PIN copies of all
86
+ # still-live encryption params created by this certificate.
53
87
  def release_handle!
88
+ @issued_encryption_params.each_key(&:wipe_pin!)
89
+ @issued_encryption_params = ObjectSpace::WeakMap.new
54
90
  SDK::API.close_handle_to_certificate(@handle)
55
91
  end
92
+
93
+ private
94
+
95
+ def open_from_bytes(pkcs12, pin)
96
+ raise ArgumentError.new('pin must not be nil') if pin.nil?
97
+
98
+ @pin = pin
99
+ @issued_encryption_params = ObjectSpace::WeakMap.new
100
+ @features = nil
101
+ handle_pointer = FFI::MemoryPointer.new(:uint32, 1)
102
+ container = FFI::MemoryPointer.new(:uint8, pkcs12.bytesize)
103
+ container.put_bytes(0, pkcs12)
104
+ pin_pointer = FFI::MemoryPointer.from_string(pin.to_s)
105
+ begin
106
+ Helpers::Invocation.raise_on_error(
107
+ SDK::API.zertifikat_oeffnen_aus_bytes(handle_pointer, container, pkcs12.bytesize, pin_pointer)
108
+ )
109
+ ensure
110
+ container.clear
111
+ pin_pointer.clear
112
+ end
113
+ @handle = handle_pointer.get_uint32(0)
114
+ end
115
+
116
+ def remember_encryption_params(params)
117
+ # Track live structs for wiping without retaining discarded structs and
118
+ # their native PIN copies for the certificate's entire lifetime.
119
+ @issued_encryption_params[params] = true
120
+ params
121
+ end
56
122
  end
57
123
 
58
124
  PinFeatures = Struct.new(
@@ -64,5 +130,18 @@ module Liberic
64
130
  :supports_last_attempt_failed,
65
131
  :supports_pin_lock_on_next_fail,
66
132
  :supports_pin_is_locked
67
- )
133
+ ) do
134
+ def self.from_flags(flags)
135
+ new(
136
+ (flags & Certificate::PIN_REQUIRED_MASK).zero?,
137
+ (flags & Certificate::PIN_REQUIRED_FOR_SIGNATURE) != 0,
138
+ (flags & Certificate::PIN_REQUIRED_FOR_DECRYPTION) != 0,
139
+ (flags & Certificate::PIN_REQUIRED_FOR_CERT_ENCRYPTION) != 0,
140
+ (flags & Certificate::PIN_STATUS_OK) != 0,
141
+ (flags & Certificate::PIN_STATUS_LAST_ATTEMPT_FAILED) != 0,
142
+ (flags & Certificate::PIN_STATUS_LOCK_ON_NEXT_FAILURE) != 0,
143
+ (flags & Certificate::PIN_STATUS_LOCKED) != 0
144
+ )
145
+ end
146
+ end
68
147
  end
@@ -1,3 +1,5 @@
1
+ require 'liberic/helpers'
2
+
1
3
  module Liberic
2
4
 
3
5
  # Provides an interface to ERiC's configuration parameters and logging.
@@ -24,25 +26,60 @@ module Liberic
24
26
  #
25
27
  # Liberic.config.validation_error_limit = 30
26
28
  #
27
- # The most common settings are (german names in paranthesis)
29
+ # The settings available as accessors are (German names in parenthesis):
28
30
  #
29
- # * +data_path+ (basis.data_dir) directory to store PDFs and certificates in
30
- # * +allow_test_id+ (basis.test_id_erlaubt) allow fake tax ids when processing tax filings
31
- # * +detailed_logs+ (log.detailed) set log level to debug. Also disables rolling logs (if +detailed_logs+ is +false+, ERiC will create a maximum of ten log files on disk, each with 1 MB of size. The oldest file will be deleted when rolling over). *WARNING*: Logging to disk is disabled after instantiating +Config+. See +:logger:+ for details.
31
+ # * +allow_test_id+ (basis.test_id_erlaubt) allow test tax ids (Test-Steueridentifikationsnummern)
32
+ # * +detailed_logs+ (log.detailed) set log level to debug. Also disables rolling logs (if +detailed_logs+ is +false+, ERiC will create a maximum of ten log files on disk, each with 1 MB of size. The oldest file will be deleted when rolling over). *WARNING*: Logging to disk is disabled after instantiating +Config+, unless +log_file+ is +true+. See +logger=+ and +log_file=+.
33
+ # * +connect_timeout+ (transfer.connect_timeout) maximum time in seconds to wait for a connection, 0 for no limit
34
+ # * +response_timeout+ (transfer.response_timeout) maximum time in seconds to wait for a response, 0 for no limit
32
35
  # * +validation_error_limit+ (validieren.fehler_max) limits the amount of errors that are returned when processing or checking tax filings. This means even though 50 fields inside the tax report are missing, only the first 30 are reported as part of the response.
33
- # * +online+ (transfer.netz.doi) allow connecting to the actual tax authority's production systems.
36
+ # * +validation_hint_limit+ (validieren.hinweise_max) limits the amount of hints in the same way
37
+ # * +network+ (transfer.netz) the network of the ELSTER servers: empty for the public internet, "ndb" for the Netz des Bundes
38
+ # * +test_date+ (test.datum) date and time (JJJJMMTThhmmss) used as the current time when checking test cases
39
+ # * +proxy_host+, +proxy_port+, +proxy_username+, +proxy_password+, +proxy_auth+ (http.proxy_*) proxy configuration
40
+ #
41
+ # The following accessors refer to settings that ERiC 43 no longer has.
42
+ # They raise +UnsupportedSettingError+ with a hint to the replacement:
43
+ #
44
+ # * +eric_home+ (basis.home_dir): use +Liberic.eric_home+
45
+ # * +log_path+ (basis.log_dir): pass +log_path:+ to +Liberic.boot!+; read it with +Liberic.log_path+
46
+ # * +data_path+ (basis.data_dir): pass +:filename+ to +Process#execute+ (ERiC has no default PDF directory)
47
+ # * +online+ (transfer.netz.doi): use +network+
34
48
  #
35
49
  class Config
36
50
  attr_reader :logger
37
51
 
52
+ # +true+ if ERiC keeps writing +eric.log+, see +log_file=+.
53
+ attr_reader :log_file
54
+
38
55
  def initialize
56
+ @log_file = false
39
57
  install_logger
40
58
  end
41
59
 
60
+ # Set to +true+ to keep ERiC writing +eric.log+ (to the +log_path+ passed
61
+ # to +Liberic.boot!+) while the log callback is registered, so that its
62
+ # messages go to the file as well as to +logger+. Defaults to +false+:
63
+ # ERiC stops writing +eric.log+ when +Config+ is created. Set it right
64
+ # after +Liberic.boot!+:
65
+ #
66
+ # Liberic.config.log_file = true
67
+ #
68
+ def log_file=(log_file)
69
+ log_file = log_file ? true : false
70
+ register_log_callback(log_file)
71
+ @log_file = log_file
72
+ end
73
+
42
74
  # Assign an instance of Logger that will be called whenever ERiC creates
43
75
  # log output.
44
- # Please note that ERiC's mechanism to write log files to disk is disabled
45
- # as soon as a +Config+ class is instantiated!
76
+ #
77
+ # *WARNING*: +Config+ registers its log callback when it is created, that
78
+ # is the first time +Liberic.config+ is used, also just to read or change
79
+ # a setting. From then on ERiC no longer writes +eric.log+ (to the
80
+ # +log_path+ passed to +Liberic.boot!+) for the rest of the process, and
81
+ # its log messages are discarded until a logger is assigned (measured with
82
+ # ERiC 43.5.4.0). Set +log_file+ to +true+ to keep +eric.log+.
46
83
  #
47
84
  # ==== Attributes
48
85
  #
@@ -67,22 +104,40 @@ module Liberic
67
104
  @logger = logger
68
105
  end
69
106
 
70
- {
71
- 'basis.home_dir' => :eric_home,
72
- 'basis.log_dir' => :log_path,
73
- 'basis.data_dir' => :data_path,
107
+ # ERiC settings available as accessors, see the ERiC developer handbook,
108
+ # chapter "Bedeutung der ERiC-Einstellungen".
109
+ SETTINGS = {
74
110
  'basis.test_id_erlaubt' => :allow_test_id,
75
111
  'log.detailed' => :detailed_logs,
76
112
  'transfer.connect_timeout' => :connect_timeout,
77
113
  'transfer.response_timeout' => :response_timeout,
78
114
  'validieren.fehler_max' => :validation_error_limit,
79
- 'transfer.netz.doi' => :online,
115
+ 'validieren.hinweise_max' => :validation_hint_limit,
116
+ 'transfer.netz' => :network,
117
+ 'test.datum' => :test_date,
80
118
  'http.proxy_host' => :proxy_host,
81
119
  'http.proxy_port' => :proxy_port,
82
120
  'http.proxy_username' => :proxy_username,
83
121
  'http.proxy_password' => :proxy_password,
84
122
  'http.proxy_auth' => :proxy_auth
85
- }.each do |setting_in_eric, setting_in_ruby|
123
+ }.freeze
124
+
125
+ # Accessors of settings that ERiC no longer supports, with the replacement.
126
+ UNSUPPORTED_SETTINGS = {
127
+ eric_home: 'basis.home_dir is not an ERiC setting anymore; use Liberic.eric_home',
128
+ log_path: 'basis.log_dir is not an ERiC setting anymore; pass log_path: to Liberic.boot! ' \
129
+ '(read it with Liberic.log_path)',
130
+ data_path: 'basis.data_dir is not an ERiC setting anymore; pass :filename to Liberic::Process#execute',
131
+ online: 'transfer.netz.doi is not an ERiC setting anymore; use Liberic.config.network ' \
132
+ '(transfer.netz, "ndb" for the Netz des Bundes)'
133
+ }.freeze
134
+
135
+ # Raised by accessors of settings that ERiC no longer supports. It is a
136
+ # +Helpers::Invocation::Error+, which these accessors raised before.
137
+ class UnsupportedSettingError < Helpers::Invocation::Error
138
+ end
139
+
140
+ SETTINGS.each do |setting_in_eric, setting_in_ruby|
86
141
  define_method setting_in_ruby do
87
142
  send(:[], setting_in_eric)
88
143
  end
@@ -92,6 +147,11 @@ module Liberic
92
147
  end
93
148
  end
94
149
 
150
+ UNSUPPORTED_SETTINGS.each do |setting_in_ruby, message|
151
+ define_method(setting_in_ruby) { raise UnsupportedSettingError.new(message) }
152
+ define_method("#{setting_in_ruby}=") { |_value| raise UnsupportedSettingError.new(message) }
153
+ end
154
+
95
155
  def [](key)
96
156
  convert_to_ruby(
97
157
  Helpers::Invocation.with_result_buffer do |handle|
@@ -112,14 +172,23 @@ module Liberic
112
172
  private
113
173
 
114
174
  def install_logger
175
+ # ERiC keeps calling the callback after registration. Keep a reference,
176
+ # otherwise the GC frees the FFI::Function and ERiC jumps into freed memory.
177
+ @log_callback = SDK::API.generate_log_callback do |category, level, message|
178
+ if @logger.respond_to?(:add)
179
+ @logger.add(SDK::Types::LOGGER_SEVERITY[level], message, category)
180
+ end
181
+ end
182
+ register_log_callback(@log_file)
183
+ end
184
+
185
+ # Registers the callback (again). The second argument of
186
+ # EricRegistriereLogCallback, schreibeEricLogDatei, is 0 to stop ERiC from
187
+ # writing eric.log and 1 to write it as well. In ERiC 43.5.4.0 it alone
188
+ # decides about eric.log, also when deregistering with NULL.
189
+ def register_log_callback(log_file)
115
190
  Helpers::Invocation.raise_on_error(
116
- SDK::API.registriere_log_callback(
117
- SDK::API.generate_log_callback do |category, level, message|
118
- if @logger.respond_to?(:add)
119
- @logger.add(SDK::Types::LOGGER_SEVERITY[level], message, category)
120
- end
121
- end,
122
- 0, nil)
191
+ SDK::API.registriere_log_callback(@log_callback, log_file ? 1 : 0, nil)
123
192
  )
124
193
  end
125
194
 
@@ -0,0 +1,24 @@
1
+ require 'ffi'
2
+ require 'nokogiri'
3
+ require 'logger'
4
+ require 'liberic/version'
5
+ require 'liberic/boot'
6
+ require 'liberic/certificate'
7
+ require 'liberic/helpers'
8
+ require 'liberic/response'
9
+ require 'liberic/sdk'
10
+ require 'liberic/process'
11
+ require 'liberic/config'
12
+
13
+ # Loads Liberic without loading or initializing ERiC. Call Liberic.boot!
14
+ # before using any other part of the library:
15
+ #
16
+ # require 'liberic/core'
17
+ # Liberic.boot!(eric_home: '/opt/ERiC-43.5.4.0/Linux-x86_64', log_path: 'log')
18
+ #
19
+ # <tt>require 'liberic'</tt> does both in one step.
20
+ module Liberic
21
+ def config
22
+ @config ||= Config.new
23
+ end
24
+ end
@@ -1,9 +1,21 @@
1
1
  require "fileutils"
2
2
  require "net/http"
3
3
  require "uri"
4
- require_relative "../lib/liberic/sdk/configuration"
4
+ require "liberic/sdk/configuration"
5
5
 
6
6
  module Liberic
7
+ # Downloads and extracts the official ERiC SDK for Linux x86-64.
8
+ #
9
+ # This file is not loaded by <tt>require "liberic"</tt>, so the installer can
10
+ # run before ERiC is available. Rake users can load the +eric:install+ task
11
+ # with <tt>require "liberic/tasks"</tt>.
12
+ #
13
+ # Extracting the archives requires rubyzip 3.4 or newer, which is not a
14
+ # runtime dependency of this gem. Add <tt>gem "rubyzip", ">= 3.4"</tt> to the
15
+ # Gemfile of the project that runs the installer.
16
+ #
17
+ # Liberic::EricInstaller.new(root: Rails.root.to_s).install
18
+ # # => ".../.eric/ERiC-43.5.4.0/Linux-x86_64"
7
19
  class EricInstaller
8
20
  DEFAULT_VERSION = SDK::Configuration::LIBERICAPI_VERSION.last
9
21
  BASE_URL = "https://download.elster.de/download/eric"
@@ -12,14 +24,18 @@ module Liberic
12
24
  "Dokumentation.zip",
13
25
  "Schemadokumentation.zip"
14
26
  ].freeze
27
+ # rubyzip before 3.4 allows path traversal during extraction.
28
+ MINIMUM_RUBYZIP_VERSION = "3.4"
15
29
 
16
30
  class InstallError < StandardError; end
17
31
 
18
32
  attr_reader :version, :root
19
33
 
20
- def initialize(version: DEFAULT_VERSION, root: File.expand_path("..", __dir__), output: $stdout)
34
+ # +version+ full ERiC release, such as "43.5.4.0"
35
+ # +root+ directory that receives the +.eric+ folder (default: current directory)
36
+ def initialize(version: DEFAULT_VERSION, root: Dir.pwd, output: $stdout)
21
37
  @version = version
22
- @root = root
38
+ @root = File.expand_path(root)
23
39
  @output = output
24
40
  validate_version!
25
41
  end
@@ -101,7 +117,7 @@ module Liberic
101
117
  return
102
118
  end
103
119
 
104
- require "zip"
120
+ load_rubyzip!
105
121
  destination_root = File.expand_path(install_root)
106
122
 
107
123
  Zip::File.open(path) do |archive|
@@ -112,17 +128,31 @@ module Liberic
112
128
  end
113
129
 
114
130
  FileUtils.mkdir_p(File.dirname(destination))
115
- entry.extract(destination) { true }
131
+ entry.extract(entry.name, destination_directory: destination_root) { true }
116
132
  end
117
133
  end
118
- rescue LoadError
119
- raise InstallError, "rubyzip is required; run bundle install before eric:install"
134
+ rescue InstallError
135
+ # Listed first so a missing rubyzip is not masked by resolving Zip::Error.
136
+ raise
120
137
  rescue Zip::Error, Errno::ENOENT, Errno::EACCES => error
121
138
  raise InstallError, "invalid archive #{path}: #{error.message}"
122
139
  end
123
140
 
124
141
  private
125
142
 
143
+ def load_rubyzip!
144
+ require "zip"
145
+ return if Gem::Version.new(Zip::VERSION) >= Gem::Version.new(MINIMUM_RUBYZIP_VERSION)
146
+
147
+ raise InstallError,
148
+ "rubyzip >= #{MINIMUM_RUBYZIP_VERSION} is required (found #{Zip::VERSION}); " \
149
+ "older versions are vulnerable to path traversal"
150
+ rescue LoadError
151
+ raise InstallError,
152
+ "rubyzip is required; add gem \"rubyzip\", \">= #{MINIMUM_RUBYZIP_VERSION}\" to your Gemfile " \
153
+ "and run bundle install before eric:install"
154
+ end
155
+
126
156
  def installation_marker
127
157
  File.join(install_root, ".installed-#{version}")
128
158
  end
@@ -173,17 +203,8 @@ module Liberic
173
203
  def print_environment_setup
174
204
  @output.puts
175
205
  @output.puts "Set ERIC_HOME in your shell:"
176
- @output.puts %(export ERIC_HOME="$PWD/.eric/ERiC-#{version}/Linux-x86_64")
206
+ @output.puts %(export ERIC_HOME="#{sdk_home}")
177
207
  @output.puts "Rake cannot permanently modify the environment of its parent shell."
178
208
  end
179
209
  end
180
210
  end
181
-
182
- namespace :eric do
183
- desc "Download and install the ERiC Linux x86-64 SDK and documentation"
184
- task :install do
185
- Liberic::EricInstaller.new(version: ENV.fetch("ERIC_VERSION", Liberic::EricInstaller::DEFAULT_VERSION)).install
186
- rescue Liberic::EricInstaller::InstallError => error
187
- abort "eric:install failed: #{error.message}"
188
- end
189
- end
@@ -1,26 +1,63 @@
1
1
  module Liberic
2
2
  module Helpers
3
3
  module Invocation
4
+ # Raised when an ERiC function returns a code other than +ERIC_OK+.
5
+ #
6
+ # The message is the name of the code (as in earlier versions); +code+,
7
+ # +error+ and +buffer+ carry the numeric code, its name and the content
8
+ # of the result buffer (if any).
4
9
  class Error < StandardError
10
+ attr_reader :code, :buffer
11
+
12
+ def initialize(message = nil, code: nil, buffer: nil)
13
+ @code = code
14
+ @buffer = buffer
15
+ super(message || Invocation.error_name(code))
16
+ end
17
+
18
+ # The name of the ERiC return code, e.g. "ERIC_GLOBAL_PRUEF_FEHLER".
19
+ def error
20
+ Invocation.error_name(code) if code
21
+ end
5
22
  end
6
23
 
7
24
  extend self
8
25
 
9
- def raise_on_error(value)
26
+ def raise_on_error(value, buffer = nil)
10
27
  return value if value == SDK::Fehlercodes::ERIC_OK
11
- raise Error.new(SDK::Fehlercodes::CODES[value])
28
+ raise Error.new(code: value, buffer: buffer)
12
29
  end
13
30
 
31
+ # Creates a result buffer, yields its handle and returns the buffer's
32
+ # content.
33
+ #
34
+ # With +raise_on_error+ (the default), a return code of the block other
35
+ # than +ERIC_OK+ raises +Error+, which carries the code and the buffer
36
+ # content. With +raise_on_error = false+ the return code is ignored; use
37
+ # +call_with_result_buffer+ to receive it.
14
38
  def with_result_buffer(raise_on_error = true, &block)
39
+ code, result = call_with_result_buffer(&block)
40
+ raise_on_error(code, result) if raise_on_error
41
+ result
42
+ end
43
+
44
+ # Creates a result buffer, yields its handle and returns
45
+ # <tt>[return_code, buffer_content]</tt>, where +return_code+ is the
46
+ # block's value (the return code of the ERiC function called in it).
47
+ def call_with_result_buffer
15
48
  handle = SDK::API.rueckgabepuffer_erzeugen
16
- if raise_on_error
17
- raise_on_error(yield(handle))
18
- else
19
- yield(handle)
49
+ begin
50
+ code = yield(handle)
51
+ [code, SDK::API.rueckgabepuffer_inhalt(handle)]
52
+ ensure
53
+ SDK::API.rueckgabepuffer_freigeben(handle)
20
54
  end
21
- result = Liberic::SDK::API.rueckgabepuffer_inhalt(handle)
22
- SDK::API.rueckgabepuffer_freigeben(handle)
23
- result
55
+ end
56
+
57
+ # The name of an ERiC return code, e.g. "ERIC_OK". Unknown codes are
58
+ # returned as "ERIC_UNKNOWN_CODE_<code>".
59
+ def error_name(code)
60
+ SDK::Fehlercodes::CODES[code] || "ERIC_UNKNOWN_CODE_#{code}"
24
61
  end
25
62
  end
26
63
  end