Class: Aspera::Environment

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/aspera/environment.rb

Overview

detect OS, architecture, and specific stuff

Constant Summary collapse

OS_WINDOWS =
:windows
OS_MACOS =
:osx
OS_LINUX =
:linux
OS_AIX =
:aix
OS_LIST =
[OS_WINDOWS, OS_MACOS, OS_LINUX, OS_AIX].freeze
CPU_X86_64 =
:x86_64
CPU_ARM64 =
:arm64
CPU_PPC64 =
:ppc64
CPU_PPC64LE =
:ppc64le
CPU_S390 =
:s390
CPU_LIST =
[CPU_X86_64, CPU_ARM64, CPU_PPC64, CPU_PPC64LE, CPU_S390].freeze
BITS_PER_BYTE =
8
I18N_VARS =
%w(LC_ALL LC_CTYPE LANG).freeze
UNICODE_TO_ASCII =

Unicode characters used in messages, and their ASCII equivalent when Unicode is not supported (see Environment.char) Key: hidden secret, hieroglyph: app switcher menu of web apps, bust: user menu of web apps

{
  '🔑' => '***',
  '✓' => 'Y',
  '✗' => ' ',
  '→' => '->',
  '…' => '...',
  '—' => '-',
  '𓃑' => '(App switcher)',
  '👤' => '(User)'
}.freeze
WINDOWS_FILENAME_INVALID_CHARACTERS =

"/" is invalid on both Unix and Windows, other are Windows special characters See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file

'<>:"/\\|?*'
REPLACE_CHARACTER =
'_'
RB_EXT =
'.rb'
PROCESS_MODES =
%i[execute background capture].freeze
CA_BUNDLE_FILES =

System CA certificate bundles, used when the default locations of Ruby's OpenSSL do not exist

[
  '/etc/ssl/certs/ca-certificates.crt', # Debian, Ubuntu, Alpine, Arch
  '/etc/pki/tls/certs/ca-bundle.crt',   # RHEL, Fedora
  '/etc/ssl/ca-bundle.pem',             # SUSE
  '/etc/ssl/cert.pem'                   # macOS, BSD
].freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Environment

Returns a new instance of Environment.



299
300
301
# File 'lib/aspera/environment.rb', line 299

def initialize
  initialize_fields
end

Class Attribute Details

.unicode=(value) ⇒ Object (writeonly)

Override detection of Unicode support: true or false, or nil for auto-detection



240
241
242
# File 'lib/aspera/environment.rb', line 240

def unicode=(value)
  @unicode = value
end

Instance Attribute Details

#browser_command ⇒ Object

url_method: :text or :graphical, how URLs, secrets and files are presented to the user browser_command: [Array, nil] command (and arguments) that opens a URL (URL is appended), instead of the system default web_auth: :port or :paste, how the result of a web login is received: local port, or URL pasted by the user hidden_silent: if true, hidden input shows no mark of its state



296
297
298
# File 'lib/aspera/environment.rb', line 296

def browser_command
  @browser_command
end

#cpu ⇒ Object (readonly)

Returns the value of attribute cpu.



297
298
299
# File 'lib/aspera/environment.rb', line 297

def cpu
  @cpu
end

#default_gui_mode ⇒ Object (readonly)

Returns the value of attribute default_gui_mode.



297
298
299
# File 'lib/aspera/environment.rb', line 297

def default_gui_mode
  @default_gui_mode
end

#file_illegal_characters ⇒ Object

url_method: :text or :graphical, how URLs, secrets and files are presented to the user browser_command: [Array, nil] command (and arguments) that opens a URL (URL is appended), instead of the system default web_auth: :port or :paste, how the result of a web login is received: local port, or URL pasted by the user hidden_silent: if true, hidden input shows no mark of its state



296
297
298
# File 'lib/aspera/environment.rb', line 296

def file_illegal_characters
  @file_illegal_characters
end

#hidden_silent ⇒ Object

url_method: :text or :graphical, how URLs, secrets and files are presented to the user browser_command: [Array, nil] command (and arguments) that opens a URL (URL is appended), instead of the system default web_auth: :port or :paste, how the result of a web login is received: local port, or URL pasted by the user hidden_silent: if true, hidden input shows no mark of its state



296
297
298
# File 'lib/aspera/environment.rb', line 296

def hidden_silent
  @hidden_silent
end

#os ⇒ Object (readonly)

Returns the value of attribute os.



297
298
299
# File 'lib/aspera/environment.rb', line 297

def os
  @os
end

#url_method ⇒ Object

url_method: :text or :graphical, how URLs, secrets and files are presented to the user browser_command: [Array, nil] command (and arguments) that opens a URL (URL is appended), instead of the system default web_auth: :port or :paste, how the result of a web login is received: local port, or URL pasted by the user hidden_silent: if true, hidden input shows no mark of its state



296
297
298
# File 'lib/aspera/environment.rb', line 296

def url_method
  @url_method
end

#web_auth ⇒ Object

url_method: :text or :graphical, how URLs, secrets and files are presented to the user browser_command: [Array, nil] command (and arguments) that opens a URL (URL is appended), instead of the system default web_auth: :port or :paste, how the result of a web login is received: local port, or URL pasted by the user hidden_silent: if true, hidden input shows no mark of its state



296
297
298
# File 'lib/aspera/environment.rb', line 296

def web_auth
  @web_auth
end

Class Method Details

.build_spawn_argv(cmd, kwargs) ⇒ Object

Build argv for Process.spawn / Kernel.system (no shell)

Parameters:

  • cmd (Array) —

    Command and arguments

  • kwargs (Hash) —

    Additional arguments to secure_execute



98
99
100
101
102
103
104
105
# File 'lib/aspera/environment.rb', line 98

def build_spawn_argv(cmd, kwargs)
  env = kwargs.delete(:env)
  argv = []
  argv << env if env
  argv << [cmd.first, cmd.first] # no shell, preserve argv[0]
  argv.concat(cmd.drop(1))
  argv
end

.char(char, unicode: terminal_supports_unicode?) ) ⇒ String

Returns The character, or its ASCII equivalent if Unicode is not supported.

Parameters:

  • char (String) —

    Unicode character, key of UNICODE_TO_ASCII

  • unicode (Boolean) (defaults to: terminal_supports_unicode?) ) —

    true if Unicode is supported

Returns:

  • (String) —

    The character, or its ASCII equivalent if Unicode is not supported



264
265
266
267
# File 'lib/aspera/environment.rb', line 264

def char(char, unicode: terminal_supports_unicode?)
  Aspera.assert(UNICODE_TO_ASCII.key?(char), "No ASCII equivalent for: #{char}", type: Aspera::InternalError)
  unicode ? char : UNICODE_TO_ASCII[char]
end

.empty_binding ⇒ Object

Fresh binding: no local variables, self is a plain Object (not a sandbox). Constants still resolve through the Aspera nesting.



83
84
85
# File 'lib/aspera/environment.rb', line 83

def empty_binding
  return Object.new.instance_eval { binding }
end

.force_terminal_c ⇒ Object

force locale to C so that unicode characters are not used



235
236
237
# File 'lib/aspera/environment.rb', line 235

def force_terminal_c
  I18N_VARS.each { |var| ENV[var] = 'C' }
end

.instance ⇒ Environment

Returns the singleton instance of Environment

Returns:



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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/aspera/environment.rb', line 26

class Environment
  include Singleton

  OS_WINDOWS = :windows
  OS_MACOS = :osx
  OS_LINUX = :linux
  OS_AIX = :aix
  OS_LIST = [OS_WINDOWS, OS_MACOS, OS_LINUX, OS_AIX].freeze

  CPU_X86_64 = :x86_64
  CPU_ARM64 = :arm64
  CPU_PPC64 = :ppc64
  CPU_PPC64LE = :ppc64le
  CPU_S390 = :s390
  CPU_LIST = [CPU_X86_64, CPU_ARM64, CPU_PPC64, CPU_PPC64LE, CPU_S390].freeze

  BITS_PER_BYTE = 8

  I18N_VARS = %w(LC_ALL LC_CTYPE LANG).freeze

  # Unicode characters used in messages, and their ASCII equivalent when Unicode is not supported (see `Environment.char`)
  # Key: hidden secret, hieroglyph: app switcher menu of web apps, bust: user menu of web apps
  UNICODE_TO_ASCII = {
    '🔑' => '***',
    '✓' => 'Y',
    '✗' => ' ',
    '→' => '->',
    '…' => '...',
    '—' => '-',
    '𓃑' => '(App switcher)',
    '👤' => '(User)'
  }.freeze

  # "/" is invalid on both Unix and Windows, other are Windows special characters
  # See: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  WINDOWS_FILENAME_INVALID_CHARACTERS = '<>:"/\\|?*'
  REPLACE_CHARACTER = '_'

  RB_EXT = '.rb'

  PROCESS_MODES = %i[execute background capture].freeze

  # System CA certificate bundles, used when the default locations of Ruby's OpenSSL do not exist
  CA_BUNDLE_FILES = [
    '/etc/ssl/certs/ca-certificates.crt', # Debian, Ubuntu, Alpine, Arch
    '/etc/pki/tls/certs/ca-bundle.crt',   # RHEL, Fedora
    '/etc/ssl/ca-bundle.pem',             # SUSE
    '/etc/ssl/cert.pem'                   # macOS, BSD
  ].freeze

  class << self
    def ruby_version
      return RbConfig::CONFIG['RUBY_PROGRAM_VERSION']
    end

    # Fresh binding: no local variables, `self` is a plain `Object` (not a sandbox).
    # Constants still resolve through the `Aspera` nesting.
    def empty_binding
      return Object.new.instance_eval { binding }
    end

    # Secure execution of Ruby code
    # @param code [String] Ruby code to execute
    # @param file [String] File name for error reporting
    # @param line [Integer] Line number for error reporting
    def secure_eval(code, file, line, user_binding = nil)
      Kernel.send('lave'.reverse, code, user_binding || empty_binding, file, line)
    end

    # Build argv for Process.spawn / Kernel.system (no shell)
    # @param cmd    [Array]  Command and arguments
    # @param kwargs [Hash]   Additional arguments to `secure_execute`
    def build_spawn_argv(cmd, kwargs)
      env = kwargs.delete(:env)
      argv = []
      argv << env if env
      argv << [cmd.first, cmd.first] # no shell, preserve argv[0]
      argv.concat(cmd.drop(1))
      argv
    end

    # Like `Shellwords.shellescape`, but does not escape `=`
    # @param str [String] String to escape for shell usage
    # @return [String] Shell-safe string
    def shell_escape_pretty(str)
      # Safe unquoted characters + '=' explicitly allowed
      return str if str.match?(%r{\A[A-Za-z0-9_.,:/@+=-]+\z})
      # return str if Shellwords.shellescape(str) == str

      # Otherwise use single quotes (gsub with block: in a replacement string, \' is the post-match)
      "'#{str.gsub("'") { %q('\'') }}'"
    end

    # Executes a command without invoking a shell.
    #
    # The command is provided as an array to avoid shell interpolation and
    # ensure safer execution.
    #
    # @param cmd [Array<#to_s>] The executable and its arguments.
    # @param mode [:execute, :background, :capture] The execution strategy:
    #   - `:execute`    Uses {Kernel.system}. Returns `true`, `false`, or `nil`. (Default)
    #   - `:background` Uses {Process.spawn}. Returns the spawned process PID.
    #   - `:capture`    Uses {Open3.capture3}. Returns captured out, err, and status.
    #
    # @param kwargs [Hash] Additional options forwarded to the underlying call.
    #
    # @option kwargs [Hash{String => String}] :env Environment variables to set for the process.
    # @option kwargs [Boolean] :exception (false) When `true` in `:capture` mode,
    #   raises an error if the command exits with a non-zero status.
    # @option kwargs [Boolean] :close_others (true) When `true` in `:background` mode,
    #   closes all other file descriptors in the child process.
    #
    # @return [Boolean, nil] For `:execute` mode (`true`, `false`, or `nil`).
    # @return [Integer] For `:background` mode (process ID).
    # @return [Array(String, String, Process::Status)] For `:capture` mode
    #   (`stdout`, `stderr`, `status`).
    #
    # @raise [RuntimeError] If `:exception` is `true` and the process fails in `:capture` mode.
    def secure_execute(*cmd, mode: :execute, **kwargs)
      cmd = cmd.map(&:to_s)
      Aspera.assert(cmd.size.positive?, 'executable must be present', type: ArgumentError)
      Aspera.assert_values(mode, PROCESS_MODES, type: ArgumentError) { 'mode' }
      Log.log.debug do
        parts = [mode.to_s, 'command:']
        kwargs[:env]&.each { |k, v| parts << "#{k}=#{shell_escape_pretty(v.to_s)}" }
        cmd.each { |a| parts << shell_escape_pretty(a) }
        parts.join(' ')
      end
      case mode
      when :execute
        # https://docs.ruby-lang.org/en/master/Kernel.html#method-i-system
        # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
        kwargs[:exception] = true unless kwargs.key?(:exception)
        Kernel.system(*build_spawn_argv(cmd, kwargs), **kwargs)
      when :background
        # https://docs.ruby-lang.org/en/master/Process.html#method-c-spawn
        # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
        kwargs[:close_others] = true unless kwargs.key?(:close_others)
        pid = ::Process.spawn(*build_spawn_argv(cmd, kwargs), **kwargs)
        Log.dump(:pid, pid)
        pid
      when :capture
        # https://docs.ruby-lang.org/en/master/Open3.html#method-c-capture3
        # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
        argv = [kwargs.delete(:env)].compact + cmd
        exception = kwargs.delete(:exception) { true }
        result = Open3.capture3(*argv, **kwargs)
        Log.dump(:stdout, result[0], level: :trace1)
        Log.dump(:stderr, result[1], level: :trace1)
        Log.dump(:status, result[2])
        raise "Process failed: #{result[2].exitstatus} (#{result[1]})" if exception && !result[2].success?
        result
      else Aspera.error_unreachable_line
      end
    end

    # Write content to a file, with restricted access
    # @param path [String] the file path
    # @param force [Boolean] if true, overwrite the file
    # @param mode [Integer] the file mode (permissions)
    # @yieldreturn [String] The content to write to the file
    def write_file_restricted(path, force: false, mode: nil)
      Aspera.assert(block_given?, 'block required for write_file_restricted', type: Aspera::InternalError)
      if force || !File.exist?(path)
        # Windows may give error
        File.unlink(path) rescue nil
        # content provided by block, file created with restricted access: never readable by others, even briefly
        File.write(path, yield, perm: mode || 0o600)
        restrict_file_access(path, mode: mode)
      end
      return path
    end

    # Restrict access to a file or folder to the current user only (chmod 600/700)
    # @param path [String]       Path to the file or directory
    # @param mode [Integer, nil] Octal permission mode; if nil, inferred from path type
    # @return [nil]
    def restrict_file_access(path, mode: nil)
      if mode.nil?
        # or FileUtils ?
        if File.file?(path)
          mode = 0o600
        elsif File.directory?(path)
          mode = 0o700
        else
          Log.log.debug { "No restriction can be set for #{path}" }
        end
      end
      File.chmod(mode, path) unless mode.nil?
      nil
    rescue => e
      Log.log.warn(e.message)
    end

    # @return [Boolean] true if we are in a terminal
    def terminal?
      $stdout.tty?
    end

    # @return [Integer, nil] Number of columns of the terminal, or `nil` if not a terminal or unknown
    def terminal_columns
      return unless terminal?
      columns = $stdout.winsize[1]
      columns.positive? ? columns : nil
    rescue SystemCallError
      nil
    end

    # force locale to C so that unicode characters are not used
    def force_terminal_c
      I18N_VARS.each { |var| ENV[var] = 'C' }
    end

    # Override detection of Unicode support: `true` or `false`, or `nil` for auto-detection
    attr_writer :unicode

    # @return [Boolean] true if we can display Unicode characters on stdout
    def terminal_supports_unicode?
      return @unicode unless @unicode.nil?
      terminal? && unicode_environment?
    end

    # @return [Boolean] true if the locale, or the terminal host on Windows, supports Unicode, whether stdout is a terminal or not
    # Uses Encoding.locale_charmap for OS-independent detection.
    # On Windows, also detects terminal hosts that render Unicode whatever the console code page.
    # Falls back to the locale env var with highest precedence, for locales not installed.
    # https://www.gnu.org/software/libc/manual/html_node/Locale-Categories.html
    # https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html
    def unicode_environment?
      return true if locale_charmap_utf8?
      return true if instance.os.eql?(OS_WINDOWS) && windows_unicode_terminal?
      locale = ENV.values_at(*I18N_VARS).find { |value| !value.to_s.empty? }
      locale&.match?(/UTF-?8/i) || false
    end

    # @param char    [String]  Unicode character, key of UNICODE_TO_ASCII
    # @param unicode [Boolean] `true` if Unicode is supported
    # @return [String] The character, or its ASCII equivalent if Unicode is not supported
    def char(char, unicode: terminal_supports_unicode?)
      Aspera.assert(UNICODE_TO_ASCII.key?(char), "No ASCII equivalent for: #{char}", type: Aspera::InternalError)
      unicode ? char : UNICODE_TO_ASCII[char]
    end

    private

    # @return [Boolean] true if the terminal host renders Unicode
    # Ruby writes to the Windows console with WriteConsoleW (UTF-16): the code page does not matter, the font does.
    # Legacy conhost may lack glyphs (e.g. check marks), while these hosts render them.
    def windows_unicode_terminal?
      # Windows Terminal, VS Code, Git Bash, ConEmu or Cmder, MSYS2 or Cygwin or SSH
      ENV.key?('WT_SESSION') ||
        %w[vscode mintty].include?(ENV.fetch('TERM_PROGRAM', nil)) ||
        ENV.fetch('ConEmuANSI', nil).eql?('ON') ||
        ENV.fetch('TERM', '').match?(/xterm|256color/)
    end

    # @return [Boolean] true if the locale charmap resolves to UTF-8
    # Unix: nl_langinfo(CODESET) returns "UTF-8"
    # Windows: console code page (GetConsoleCP), else ANSI code page (GetACP): "CP65001" resolves as UTF-8
    def locale_charmap_utf8?
      Encoding.find(Encoding.locale_charmap) == Encoding::UTF_8
    rescue ArgumentError
      false
    end
  end
  # url_method:      :text or :graphical, how URLs, secrets and files are presented to the user
  # browser_command: [Array<String>, nil] command (and arguments) that opens a URL (URL is appended), instead of
  #                  the system default
  # web_auth:        :port or :paste, how the result of a web login is received: local port, or URL pasted by the user
  # hidden_silent:   if true, hidden input shows no mark of its state
  attr_accessor :url_method, :browser_command, :web_auth, :hidden_silent, :file_illegal_characters
  attr_reader :os, :cpu, :default_gui_mode

  def initialize
    initialize_fields
  end

  # initialize fields from environment
  def initialize_fields
    @os =
      case RbConfig::CONFIG['host_os']
      when /mswin/, /msys/, /mingw/, /cygwin/, /bccwin/, /wince/, /emc/
        OS_WINDOWS
      when /darwin/, /mac os/
        OS_MACOS
      when /linux/, /cosmo/
        OS_LINUX
      when /aix/
        OS_AIX
      else Aspera.error_unexpected_value(RbConfig::CONFIG['host_os']) { 'host_os' }
      end
    @cpu =
      case RbConfig::CONFIG['host_cpu']
      when /x86_64/, /x64/
        CPU_X86_64
      when /powerpc/, /ppc64/
        @os.eql?(OS_LINUX) ? CPU_PPC64LE : CPU_PPC64
      when /s390/
        CPU_S390
      when /arm/, /aarch64/
        CPU_ARM64
      else Aspera.error_unexpected_value(RbConfig::CONFIG['host_cpu']) { 'host_cpu' }
      end
    @executable_extension = @os.eql?(OS_WINDOWS) ? '.exe' : nil
    # :text or :graphical depending on the environment
    @default_gui_mode =
      if [Environment::OS_WINDOWS, Environment::OS_MACOS].include?(os) ||
          (ENV.key?('DISPLAY') && !ENV['DISPLAY'].empty?)
        # assume not remotely connected on macos and windows or unix family
        :graphical
      else
        :text
      end
    @url_method = @default_gui_mode
    @browser_command = nil
    @web_auth = :port
    @hidden_silent = false
    @file_illegal_characters = REPLACE_CHARACTER + WINDOWS_FILENAME_INVALID_CHARACTERS
    nil
  end

  # Normalized architecture name
  # See constants: OS_* and CPU_*
  def architecture
    "#{@os}-#{@cpu}"
  end

  # Add executable file extension (e.g. ".exe") for current OS
  # @param name [String,nil] Path or file name
  # @return [String] Executable name with extension
  def exe_file(name = nil)
    return name unless @executable_extension
    return "#{name}#{@executable_extension}"
  end

  # on Windows, the env var %USERPROFILE% provides the path to user's home more reliably than %HOMEDRIVE%%HOMEPATH%
  # so, tell Ruby the right way
  def fix_home
    return unless @os.eql?(OS_WINDOWS) && ENV.key?('USERPROFILE') && Dir.exist?(ENV.fetch('USERPROFILE', nil))
    ENV['HOME'] = ENV.fetch('USERPROFILE', nil)
    Log.log.debug { "Windows: set HOME to USERPROFILE: #{Dir.home}" }
    nil
  end

  # When Ruby's OpenSSL was built on another system (e.g. single executable built on RHEL, used on Ubuntu),
  # its default CA locations may not exist: use the system CA bundle instead.
  # @return [String, nil] CA bundle file used, or nil if no change
  def fix_ca_certificates
    return if defined?(JRUBY_VERSION)
    return if [OpenSSL::X509::DEFAULT_CERT_FILE_ENV, OpenSSL::X509::DEFAULT_CERT_DIR_ENV].any? { |var| ENV.key?(var) }
    return if File.exist?(OpenSSL::X509::DEFAULT_CERT_FILE) || Dir.exist?(OpenSSL::X509::DEFAULT_CERT_DIR)
    ca_file = CA_BUNDLE_FILES.find { |file| File.file?(file) }
    return if ca_file.nil?
    # Used by OpenSSL for new default stores, and by child processes
    ENV[OpenSSL::X509::DEFAULT_CERT_FILE_ENV] = ca_file
    # Default store of SSL contexts is initialized when openssl is loaded
    OpenSSL::SSL::SSLContext::DEFAULT_CERT_STORE.add_file(ca_file)
    Log.log.debug { "Using system CA certificates: #{ca_file}" }
    ca_file
  end

  def graphical?
    @default_gui_mode == :graphical
  end

  # Open a URI in the browser (non-blocking).
  # The browser is, by priority: `browser_command`, the system default.
  # @param uri [String, URI] the URI to open
  # @return [nil]
  def open_uri_graphical(uri)
    if @browser_command
      begin
        self.class.secure_execute(*@browser_command, uri.to_s)
      rescue Errno::ENOENT
        raise ParameterError, "Browser command not found (option ui.command): #{@browser_command.first}. Check that it is in PATH, or use its full path."
      end
    else
      case @os
      when Environment::OS_MACOS then self.class.secure_execute('open', uri.to_s)
      when Environment::OS_WINDOWS then self.class.secure_execute('start', 'explorer', %Q{"#{uri}"})
      when Environment::OS_LINUX   then self.class.secure_execute('xdg-open', uri.to_s)
      else Aspera.error_unexpected_value(os) { 'no graphical open method' }
      end
    end
    nil
  end

  # open a file in an editor
  def open_editor(file_path)
    if ENV.key?('EDITOR')
      self.class.secure_execute(ENV['EDITOR'], file_path.to_s)
    elsif @os.eql?(Environment::OS_WINDOWS)
      self.class.secure_execute('notepad.exe', %Q{"#{file_path}"})
    else
      open_uri_graphical(file_path.to_s)
    end
  end

  # Allows a user to open a URL
  # if a browser command is defined (`browser_command`), then it is used, whatever the method
  # if method is :text, then URL is displayed on terminal
  # if method is :graphical, then the URL will be opened with the default browser.
  # this is non blocking
  def open_uri(the_url)
    if @browser_command
      open_uri_graphical(the_url)
    else
      case @url_method
      when :graphical
        open_uri_graphical(the_url)
      when :text
        case the_url.to_s
        when /^http/
          puts "USER ACTION: please enter this URL in a browser:\n#{the_url.to_s.red}\n"
        else
          puts "USER ACTION: open this:\n#{the_url.to_s.red}\n"
        end
      else Aspera.error_unexpected_value(@url_method) { 'URL open method' }
      end
    end
  end

  # Replacement character for illegal filename characters
  # Can also be used as safe "join" character
  # @return [String] One character
  def safe_filename_character
    return REPLACE_CHARACTER if @file_illegal_characters.nil? || @file_illegal_characters.empty?
    @file_illegal_characters[0]
  end

  # Sanitize a filename by replacing illegal characters
  # @param filename [String] the original filename
  # @return [String] A file name safe to use on file system
  def sanitized_filename(filename)
    safe_char = safe_filename_character
    # Windows does not allow file name:
    # - with control characters anywhere
    # - ending with space or dot
    filename = filename.gsub(/[\x00-\x1F\x7F]/, safe_char)
    filename = filename.chop while filename.end_with?(' ', '.')
    if @file_illegal_characters&.size.to_i >= 2
      # replace all illegal characters with safe_char
      filename = filename.tr(@file_illegal_characters[1..], safe_char)
    end
    # ensure only one safe_char is used at a time
    return filename.gsub(/#{Regexp.escape(safe_char)}+/, safe_char).chomp(safe_char)
  end
end

.restrict_file_access(path, mode: nil) ⇒ nil

Restrict access to a file or folder to the current user only (chmod 600/700)

Parameters:

  • path (String) —

    Path to the file or directory

  • mode (Integer, nil) (defaults to: nil) —

    Octal permission mode; if nil, inferred from path type

Returns:

  • (nil)


203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/aspera/environment.rb', line 203

def restrict_file_access(path, mode: nil)
  if mode.nil?
    # or FileUtils ?
    if File.file?(path)
      mode = 0o600
    elsif File.directory?(path)
      mode = 0o700
    else
      Log.log.debug { "No restriction can be set for #{path}" }
    end
  end
  File.chmod(mode, path) unless mode.nil?
  nil
rescue => e
  Log.log.warn(e.message)
end

.ruby_version ⇒ Object



77
78
79
# File 'lib/aspera/environment.rb', line 77

def ruby_version
  return RbConfig::CONFIG['RUBY_PROGRAM_VERSION']
end

.secure_eval(code, file, line, user_binding = nil) ⇒ Object

Secure execution of Ruby code

Parameters:

  • code (String) —

    Ruby code to execute

  • file (String) —

    File name for error reporting

  • line (Integer) —

    Line number for error reporting



91
92
93
# File 'lib/aspera/environment.rb', line 91

def secure_eval(code, file, line, user_binding = nil)
  Kernel.send('lave'.reverse, code, user_binding || empty_binding, file, line)
end

.secure_execute(*cmd, mode: :execute, **kwargs) ⇒ Boolean, ...

Executes a command without invoking a shell.

The command is provided as an array to avoid shell interpolation and ensure safer execution.

Parameters:

  • cmd (Array<#to_s>) —

    The executable and its arguments.

  • mode (:execute, :background, :capture) (defaults to: :execute) —

    The execution strategy:

    • :execute Uses Kernel.system. Returns true, false, or nil. (Default)
    • :background Uses Process.spawn. Returns the spawned process PID.
    • :capture Uses Open3.capture3. Returns captured out, err, and status.
  • kwargs (Hash) —

    Additional options forwarded to the underlying call.

Options Hash (**kwargs):

  • :env (Hash{String => String}) —

    Environment variables to set for the process.

  • :exception (Boolean) — default: false —

    When true in :capture mode, raises an error if the command exits with a non-zero status.

  • :close_others (Boolean) — default: true —

    When true in :background mode, closes all other file descriptors in the child process.

Returns:

  • (Boolean, nil) —

    For :execute mode (true, false, or nil).

  • (Integer) —

    For :background mode (process ID).

  • (Array(String, String, Process::Status)) —

    For :capture mode (stdout, stderr, status).

Raises:

  • (RuntimeError) —

    If :exception is true and the process fails in :capture mode.



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/aspera/environment.rb', line 144

def secure_execute(*cmd, mode: :execute, **kwargs)
  cmd = cmd.map(&:to_s)
  Aspera.assert(cmd.size.positive?, 'executable must be present', type: ArgumentError)
  Aspera.assert_values(mode, PROCESS_MODES, type: ArgumentError) { 'mode' }
  Log.log.debug do
    parts = [mode.to_s, 'command:']
    kwargs[:env]&.each { |k, v| parts << "#{k}=#{shell_escape_pretty(v.to_s)}" }
    cmd.each { |a| parts << shell_escape_pretty(a) }
    parts.join(' ')
  end
  case mode
  when :execute
    # https://docs.ruby-lang.org/en/master/Kernel.html#method-i-system
    # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
    kwargs[:exception] = true unless kwargs.key?(:exception)
    Kernel.system(*build_spawn_argv(cmd, kwargs), **kwargs)
  when :background
    # https://docs.ruby-lang.org/en/master/Process.html#method-c-spawn
    # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
    kwargs[:close_others] = true unless kwargs.key?(:close_others)
    pid = ::Process.spawn(*build_spawn_argv(cmd, kwargs), **kwargs)
    Log.dump(:pid, pid)
    pid
  when :capture
    # https://docs.ruby-lang.org/en/master/Open3.html#method-c-capture3
    # https://docs.ruby-lang.org/en/master/Process.html#module-Process-label-Execution+Options
    argv = [kwargs.delete(:env)].compact + cmd
    exception = kwargs.delete(:exception) { true }
    result = Open3.capture3(*argv, **kwargs)
    Log.dump(:stdout, result[0], level: :trace1)
    Log.dump(:stderr, result[1], level: :trace1)
    Log.dump(:status, result[2])
    raise "Process failed: #{result[2].exitstatus} (#{result[1]})" if exception && !result[2].success?
    result
  else Aspera.error_unreachable_line
  end
end

.shell_escape_pretty(str) ⇒ String

Like Shellwords.shellescape, but does not escape =

Parameters:

  • str (String) —

    String to escape for shell usage

Returns:

  • (String) —

    Shell-safe string



110
111
112
113
114
115
116
117
# File 'lib/aspera/environment.rb', line 110

def shell_escape_pretty(str)
  # Safe unquoted characters + '=' explicitly allowed
  return str if str.match?(%r{\A[A-Za-z0-9_.,:/@+=-]+\z})
  # return str if Shellwords.shellescape(str) == str

  # Otherwise use single quotes (gsub with block: in a replacement string, \' is the post-match)
  "'#{str.gsub("'") { %q('\'') }}'"
end

.terminal? ⇒ Boolean

Returns true if we are in a terminal.

Returns:

  • (Boolean) —

    true if we are in a terminal



221
222
223
# File 'lib/aspera/environment.rb', line 221

def terminal?
  $stdout.tty?
end

.terminal_columns ⇒ Integer?

Returns Number of columns of the terminal, or nil if not a terminal or unknown.

Returns:

  • (Integer, nil) —

    Number of columns of the terminal, or nil if not a terminal or unknown



226
227
228
229
230
231
232
# File 'lib/aspera/environment.rb', line 226

def terminal_columns
  return unless terminal?
  columns = $stdout.winsize[1]
  columns.positive? ? columns : nil
rescue SystemCallError
  nil
end

.terminal_supports_unicode? ⇒ Boolean

Returns true if we can display Unicode characters on stdout.

Returns:

  • (Boolean) —

    true if we can display Unicode characters on stdout



243
244
245
246
# File 'lib/aspera/environment.rb', line 243

def terminal_supports_unicode?
  return @unicode unless @unicode.nil?
  terminal? && unicode_environment?
end

.unicode_environment? ⇒ Boolean

Uses Encoding.locale_charmap for OS-independent detection. On Windows, also detects terminal hosts that render Unicode whatever the console code page. Falls back to the locale env var with highest precedence, for locales not installed. https://www.gnu.org/software/libc/manual/html_node/Locale-Categories.html https://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html

Returns:

  • (Boolean) —

    true if the locale, or the terminal host on Windows, supports Unicode, whether stdout is a terminal or not



254
255
256
257
258
259
# File 'lib/aspera/environment.rb', line 254

def unicode_environment?
  return true if locale_charmap_utf8?
  return true if instance.os.eql?(OS_WINDOWS) && windows_unicode_terminal?
  locale = ENV.values_at(*I18N_VARS).find { |value| !value.to_s.empty? }
  locale&.match?(/UTF-?8/i) || false
end

.write_file_restricted(path, force: false, mode: nil) ⇒ Object

Write content to a file, with restricted access

Parameters:

  • path (String) —

    the file path

  • force (Boolean) (defaults to: false) —

    if true, overwrite the file

  • mode (Integer) (defaults to: nil) —

    the file mode (permissions)

Yield Returns:

  • (String) —

    The content to write to the file



187
188
189
190
191
192
193
194
195
196
197
# File 'lib/aspera/environment.rb', line 187

def write_file_restricted(path, force: false, mode: nil)
  Aspera.assert(block_given?, 'block required for write_file_restricted', type: Aspera::InternalError)
  if force || !File.exist?(path)
    # Windows may give error
    File.unlink(path) rescue nil
    # content provided by block, file created with restricted access: never readable by others, even briefly
    File.write(path, yield, perm: mode || 0o600)
    restrict_file_access(path, mode: mode)
  end
  return path
end

Instance Method Details

#architecture ⇒ Object

Normalized architecture name See constants: OS_* and CPU_*



349
350
351
# File 'lib/aspera/environment.rb', line 349

def architecture
  "#{@os}-#{@cpu}"
end

#exe_file(name = nil) ⇒ String

Add executable file extension (e.g. ".exe") for current OS

Parameters:

  • name (String, nil) (defaults to: nil) —

    Path or file name

Returns:

  • (String) —

    Executable name with extension



356
357
358
359
# File 'lib/aspera/environment.rb', line 356

def exe_file(name = nil)
  return name unless @executable_extension
  return "#{name}#{@executable_extension}"
end

#fix_ca_certificates ⇒ String?

When Ruby's OpenSSL was built on another system (e.g. single executable built on RHEL, used on Ubuntu), its default CA locations may not exist: use the system CA bundle instead.

Returns:

  • (String, nil) —

    CA bundle file used, or nil if no change



373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/aspera/environment.rb', line 373

def fix_ca_certificates
  return if defined?(JRUBY_VERSION)
  return if [OpenSSL::X509::DEFAULT_CERT_FILE_ENV, OpenSSL::X509::DEFAULT_CERT_DIR_ENV].any? { |var| ENV.key?(var) }
  return if File.exist?(OpenSSL::X509::DEFAULT_CERT_FILE) || Dir.exist?(OpenSSL::X509::DEFAULT_CERT_DIR)
  ca_file = CA_BUNDLE_FILES.find { |file| File.file?(file) }
  return if ca_file.nil?
  # Used by OpenSSL for new default stores, and by child processes
  ENV[OpenSSL::X509::DEFAULT_CERT_FILE_ENV] = ca_file
  # Default store of SSL contexts is initialized when openssl is loaded
  OpenSSL::SSL::SSLContext::DEFAULT_CERT_STORE.add_file(ca_file)
  Log.log.debug { "Using system CA certificates: #{ca_file}" }
  ca_file
end

#fix_home ⇒ Object

on Windows, the env var %USERPROFILE% provides the path to user's home more reliably than %HOMEDRIVE%%HOMEPATH% so, tell Ruby the right way



363
364
365
366
367
368
# File 'lib/aspera/environment.rb', line 363

def fix_home
  return unless @os.eql?(OS_WINDOWS) && ENV.key?('USERPROFILE') && Dir.exist?(ENV.fetch('USERPROFILE', nil))
  ENV['HOME'] = ENV.fetch('USERPROFILE', nil)
  Log.log.debug { "Windows: set HOME to USERPROFILE: #{Dir.home}" }
  nil
end

#graphical? ⇒ Boolean

Returns:

  • (Boolean)


387
388
389
# File 'lib/aspera/environment.rb', line 387

def graphical?
  @default_gui_mode == :graphical
end

#initialize_fields ⇒ Object

initialize fields from environment



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/aspera/environment.rb', line 304

def initialize_fields
  @os =
    case RbConfig::CONFIG['host_os']
    when /mswin/, /msys/, /mingw/, /cygwin/, /bccwin/, /wince/, /emc/
      OS_WINDOWS
    when /darwin/, /mac os/
      OS_MACOS
    when /linux/, /cosmo/
      OS_LINUX
    when /aix/
      OS_AIX
    else Aspera.error_unexpected_value(RbConfig::CONFIG['host_os']) { 'host_os' }
    end
  @cpu =
    case RbConfig::CONFIG['host_cpu']
    when /x86_64/, /x64/
      CPU_X86_64
    when /powerpc/, /ppc64/
      @os.eql?(OS_LINUX) ? CPU_PPC64LE : CPU_PPC64
    when /s390/
      CPU_S390
    when /arm/, /aarch64/
      CPU_ARM64
    else Aspera.error_unexpected_value(RbConfig::CONFIG['host_cpu']) { 'host_cpu' }
    end
  @executable_extension = @os.eql?(OS_WINDOWS) ? '.exe' : nil
  # :text or :graphical depending on the environment
  @default_gui_mode =
    if [Environment::OS_WINDOWS, Environment::OS_MACOS].include?(os) ||
        (ENV.key?('DISPLAY') && !ENV['DISPLAY'].empty?)
      # assume not remotely connected on macos and windows or unix family
      :graphical
    else
      :text
    end
  @url_method = @default_gui_mode
  @browser_command = nil
  @web_auth = :port
  @hidden_silent = false
  @file_illegal_characters = REPLACE_CHARACTER + WINDOWS_FILENAME_INVALID_CHARACTERS
  nil
end

#open_editor(file_path) ⇒ Object

open a file in an editor



414
415
416
417
418
419
420
421
422
# File 'lib/aspera/environment.rb', line 414

def open_editor(file_path)
  if ENV.key?('EDITOR')
    self.class.secure_execute(ENV['EDITOR'], file_path.to_s)
  elsif @os.eql?(Environment::OS_WINDOWS)
    self.class.secure_execute('notepad.exe', %Q{"#{file_path}"})
  else
    open_uri_graphical(file_path.to_s)
  end
end

#open_uri(the_url) ⇒ Object

Allows a user to open a URL if a browser command is defined (browser_command), then it is used, whatever the method if method is :text, then URL is displayed on terminal if method is :graphical, then the URL will be opened with the default browser. this is non blocking



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/aspera/environment.rb', line 429

def open_uri(the_url)
  if @browser_command
    open_uri_graphical(the_url)
  else
    case @url_method
    when :graphical
      open_uri_graphical(the_url)
    when :text
      case the_url.to_s
      when /^http/
        puts "USER ACTION: please enter this URL in a browser:\n#{the_url.to_s.red}\n"
      else
        puts "USER ACTION: open this:\n#{the_url.to_s.red}\n"
      end
    else Aspera.error_unexpected_value(@url_method) { 'URL open method' }
    end
  end
end

#open_uri_graphical(uri) ⇒ nil

Open a URI in the browser (non-blocking). The browser is, by priority: browser_command, the system default.

Parameters:

Returns:

  • (nil)


395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/aspera/environment.rb', line 395

def open_uri_graphical(uri)
  if @browser_command
    begin
      self.class.secure_execute(*@browser_command, uri.to_s)
    rescue Errno::ENOENT
      raise ParameterError, "Browser command not found (option ui.command): #{@browser_command.first}. Check that it is in PATH, or use its full path."
    end
  else
    case @os
    when Environment::OS_MACOS then self.class.secure_execute('open', uri.to_s)
    when Environment::OS_WINDOWS then self.class.secure_execute('start', 'explorer', %Q{"#{uri}"})
    when Environment::OS_LINUX   then self.class.secure_execute('xdg-open', uri.to_s)
    else Aspera.error_unexpected_value(os) { 'no graphical open method' }
    end
  end
  nil
end

#safe_filename_character ⇒ String

Replacement character for illegal filename characters Can also be used as safe "join" character

Returns:



451
452
453
454
# File 'lib/aspera/environment.rb', line 451

def safe_filename_character
  return REPLACE_CHARACTER if @file_illegal_characters.nil? || @file_illegal_characters.empty?
  @file_illegal_characters[0]
end

#sanitized_filename(filename) ⇒ String

Sanitize a filename by replacing illegal characters

Parameters:

  • filename (String) —

    the original filename

Returns:

  • (String) —

    A file name safe to use on file system



459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/aspera/environment.rb', line 459

def sanitized_filename(filename)
  safe_char = safe_filename_character
  # Windows does not allow file name:
  # - with control characters anywhere
  # - ending with space or dot
  filename = filename.gsub(/[\x00-\x1F\x7F]/, safe_char)
  filename = filename.chop while filename.end_with?(' ', '.')
  if @file_illegal_characters&.size.to_i >= 2
    # replace all illegal characters with safe_char
    filename = filename.tr(@file_illegal_characters[1..], safe_char)
  end
  # ensure only one safe_char is used at a time
  return filename.gsub(/#{Regexp.escape(safe_char)}+/, safe_char).chomp(safe_char)
end