repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/exec/shell.rb | lib/puppet/provider/exec/shell.rb | # frozen_string_literal: true
Puppet::Type.type(:exec).provide :shell, :parent => :posix do
include Puppet::Util::Execution
confine :feature => :posix
desc <<-EOT
Passes the provided command through `/bin/sh`; only available on
POSIX systems. This allows the use of shell globbing and built-ins, and
does not require that the path to a command be fully-qualified. Although
this can be more convenient than the `posix` provider, it also means that
you need to be more careful with escaping; as ever, with great power comes
etc. etc.
This provider closely resembles the behavior of the `exec` type
in Puppet 0.25.x.
EOT
def run(command, check = false)
super(['/bin/sh', '-c', command], check)
end
def validatecmd(command)
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/exec/posix.rb | lib/puppet/provider/exec/posix.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/exec'
Puppet::Type.type(:exec).provide :posix, :parent => Puppet::Provider::Exec do
has_feature :umask
confine :feature => :posix
defaultfor :feature => :posix
desc <<-EOT
Executes external binaries by invoking Ruby's `Kernel.exec`.
When the command is a string, it will be executed directly,
without a shell, if it follows these rules:
- no meta characters
- no shell reserved word and no special built-in
When the command is an Array of Strings, passed as `[cmdname, arg1, ...]`
it will be executed directly(the first element is taken as a command name
and the rest are passed as parameters to command with no shell expansion)
This is a safer and more predictable way to execute most commands,
but prevents the use of globbing and shell built-ins (including control
logic like "for" and "if" statements).
If the use of globbing and shell built-ins is desired, please check
the `shell` provider
EOT
# Verify that we have the executable
def checkexe(command)
exe = extractexe(command)
if File.expand_path(exe) == exe
if !Puppet::FileSystem.exist?(exe)
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
elsif !File.file?(exe)
raise ArgumentError, _("'%{exe}' is a %{klass}, not a file") % { exe: exe, klass: File.ftype(exe) }
elsif !File.executable?(exe)
raise ArgumentError, _("'%{exe}' is not executable") % { exe: exe }
end
return
end
if resource[:path]
Puppet::Util.withenv :PATH => resource[:path].join(File::PATH_SEPARATOR) do
return if which(exe)
end
end
# 'which' will only return the command if it's executable, so we can't
# distinguish not found from not executable
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
end
def run(command, check = false)
if resource[:umask]
Puppet::Util.withumask(resource[:umask]) { super(command, check) }
else
super(command, check)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/exec/windows.rb | lib/puppet/provider/exec/windows.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/exec'
Puppet::Type.type(:exec).provide :windows, :parent => Puppet::Provider::Exec do
confine 'os.name' => :windows
defaultfor 'os.name' => :windows
desc <<-'EOT'
Execute external binaries on Windows systems. As with the `posix`
provider, this provider directly calls the command with the arguments
given, without passing it through a shell or performing any interpolation.
To use shell built-ins --- that is, to emulate the `shell` provider on
Windows --- a command must explicitly invoke the shell:
exec {'echo foo':
command => 'cmd.exe /c echo "foo"',
}
If no extension is specified for a command, Windows will use the `PATHEXT`
environment variable to locate the executable.
**Note on PowerShell scripts:** PowerShell's default `restricted`
execution policy doesn't allow it to run saved scripts. To run PowerShell
scripts, specify the `remotesigned` execution policy as part of the
command:
exec { 'test':
path => 'C:/Windows/System32/WindowsPowerShell/v1.0',
command => 'powershell -executionpolicy remotesigned -file C:/test.ps1',
}
EOT
# Verify that we have the executable
def checkexe(command)
exe = extractexe(command)
if absolute_path?(exe)
if !Puppet::FileSystem.exist?(exe)
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
elsif !File.file?(exe)
raise ArgumentError, _("'%{exe}' is a %{klass}, not a file") % { exe: exe, klass: File.ftype(exe) }
end
return
end
if resource[:path]
Puppet::Util.withenv('PATH' => resource[:path].join(File::PATH_SEPARATOR)) do
return if which(exe)
end
end
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/windows_adsi.rb | lib/puppet/provider/group/windows_adsi.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
Puppet::Type.type(:group).provide :windows_adsi do
desc "Local group management for Windows. Group members can be both users and groups.
Additionally, local groups can contain domain users."
defaultfor 'os.name' => :windows
confine 'os.name' => :windows
has_features :manages_members
def initialize(value = {})
super(value)
@deleted = false
end
def members_insync?(current, should)
return false unless current
# By comparing account SIDs we don't have to worry about case
# sensitivity, or canonicalization of account names.
# Cannot use munge of the group property to canonicalize @should
# since the default array_matching comparison is not commutative
# dupes automatically weeded out when hashes built
current_members = Puppet::Util::Windows::ADSI::Group.name_sid_hash(current, true)
specified_members = Puppet::Util::Windows::ADSI::Group.name_sid_hash(should)
current_sids = current_members.keys.to_a
specified_sids = specified_members.keys.to_a
if @resource[:auth_membership]
current_sids.sort == specified_sids.sort
else
(specified_sids & current_sids) == specified_sids
end
end
def members_to_s(users)
return '' if users.nil? or !users.is_a?(Array)
users = users.map do |user_name|
sid = Puppet::Util::Windows::SID.name_to_principal(user_name)
unless sid
resource.debug("#{user_name} (unresolvable to SID)")
next user_name
end
if sid.account =~ /\\/
account, _ = Puppet::Util::Windows::ADSI::User.parse_name(sid.account)
else
account = sid.account
end
resource.debug("#{sid.domain}\\#{account} (#{sid.sid})")
sid.domain ? "#{sid.domain}\\#{account}" : account
end
users.join(',')
end
def member_valid?(user_name)
!Puppet::Util::Windows::SID.name_to_principal(user_name).nil?
end
def group
@group ||= Puppet::Util::Windows::ADSI::Group.new(@resource[:name])
end
def members
@members ||= Puppet::Util::Windows::ADSI::Group.name_sid_hash(group.members, true)
# @members.keys returns an array of SIDs. We need to convert those SIDs into
# names so that `puppet resource` prints the right output.
members_to_s(@members.keys).split(',')
end
def members=(members)
group.set_members(members, @resource[:auth_membership])
end
def create
@group = Puppet::Util::Windows::ADSI::Group.create(@resource[:name])
@group.commit
self.members = @resource[:members]
end
def exists?
Puppet::Util::Windows::ADSI::Group.exists?(@resource[:name])
end
def delete
Puppet::Util::Windows::ADSI::Group.delete(@resource[:name])
@deleted = true
end
# Only flush if we created or modified a group, not deleted
def flush
@group.commit if @group && !@deleted
end
def gid
Puppet::Util::Windows::SID.name_to_sid(@resource[:name])
end
def gid=(value)
fail "gid is read-only"
end
def self.instances
Puppet::Util::Windows::ADSI::Group.map { |g| new(:ensure => :present, :name => g.name) }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/aix.rb | lib/puppet/provider/group/aix.rb | # frozen_string_literal: true
# Group Puppet provider for AIX. It uses standard commands to manage groups:
# mkgroup, rmgroup, lsgroup, chgroup
require_relative '../../../puppet/provider/aix_object'
Puppet::Type.type(:group).provide :aix, :parent => Puppet::Provider::AixObject do
desc "Group management for AIX."
# This will the default provider for this platform
defaultfor 'os.name' => :aix
confine 'os.name' => :aix
# Commands that manage the element
commands :list => "/usr/sbin/lsgroup"
commands :add => "/usr/bin/mkgroup"
commands :delete => "/usr/sbin/rmgroup"
commands :modify => "/usr/bin/chgroup"
# Provider features
has_features :manages_aix_lam
has_features :manages_members
has_features :manages_local_users_and_groups
class << self
# Used by the AIX user provider. Returns a hash of:
# {
# :name => <group_name>,
# :gid => <gid>
# }
#
# that matches the group, which can either be the group name or
# the gid. Takes an optional set of ia_module_args
def find(group, ia_module_args = [])
groups = list_all(ia_module_args)
id_property = mappings[:puppet_property][:id]
if group.is_a?(String)
# Find by name
group_hash = groups.find { |cur_group| cur_group[:name] == group }
else
# Find by gid
group_hash = groups.find do |cur_group|
id_property.convert_attribute_value(cur_group[:id]) == group
end
end
unless group_hash
raise ArgumentError, _("No AIX group exists with a group name or gid of %{group}!") % { group: group }
end
# Convert :id => :gid
id = group_hash.delete(:id)
group_hash[:gid] = id_property.convert_attribute_value(id)
group_hash
end
# Define some Puppet Property => AIX Attribute (and vice versa)
# conversion functions here. This is so we can unit test them.
def members_to_users(provider, members)
members = members.split(',') if members.is_a?(String)
unless provider.resource[:auth_membership]
current_members = provider.members
current_members = [] if current_members == :absent
members = (members + current_members).uniq
end
members.join(',')
end
def users_to_members(users)
users.split(',')
end
end
mapping puppet_property: :members,
aix_attribute: :users,
property_to_attribute: method(:members_to_users),
attribute_to_property: method(:users_to_members)
numeric_mapping puppet_property: :gid,
aix_attribute: :id
# Now that we have all of our mappings, let's go ahead and make
# the resource methods (property getters + setters for our mapped
# properties + a getter for the attributes property).
mk_resource_methods
# We could add this to the top-level members property since the
# implementation is not platform-specific; however, it is best
# to do it this way so that we do not accidentally break something.
# This is ok for now, since we do plan on moving this and the
# auth_membership management over to the property class in a future
# Puppet release.
def members_insync?(current, should)
current.sort == @resource.parameter(:members).actual_should(current, should)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/directoryservice.rb | lib/puppet/provider/group/directoryservice.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/directoryservice'
Puppet::Type.type(:group).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do
desc "Group management using DirectoryService on OS X.
"
commands :dscl => "/usr/bin/dscl"
confine 'os.name' => :darwin
defaultfor 'os.name' => :darwin
has_feature :manages_members
def members_insync?(current, should)
return false unless current
if current == :absent
should.empty?
else
current.sort.uniq == should.sort.uniq
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/pw.rb | lib/puppet/provider/group/pw.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/pw'
Puppet::Type.type(:group).provide :pw, :parent => Puppet::Provider::NameService::PW do
desc "Group management via `pw` on FreeBSD and DragonFly BSD."
commands :pw => "pw"
has_features :manages_members
defaultfor 'os.name' => [:freebsd, :dragonfly]
confine 'os.name' => [:freebsd, :dragonfly]
options :members, :flag => "-M", :method => :mem
verify :gid, _("GID must be an integer") do |value|
value.is_a? Integer
end
def addcmd
cmd = [command(:pw), "groupadd", @resource[:name]]
gid = @resource.should(:gid)
if gid
unless gid == :absent
cmd << flag(:gid) << gid
end
end
members = @resource.should(:members)
if members
unless members == :absent
if members.is_a?(Array)
members = members.join(",")
end
cmd << "-M" << members
end
end
cmd << "-o" if @resource.allowdupe?
cmd
end
def modifycmd(param, value)
# members may be an array, need a comma separated list
if param == :members and value.is_a?(Array)
value = value.join(",")
end
super(param, value)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/groupadd.rb | lib/puppet/provider/group/groupadd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/objectadd'
require_relative '../../../puppet/util/libuser'
Puppet::Type.type(:group).provide :groupadd, :parent => Puppet::Provider::NameService::ObjectAdd do
desc "Group management via `groupadd` and its ilk. The default for most platforms.
To use the `forcelocal` parameter, you need to install the `libuser` package (providing
`/usr/sbin/lgroupadd` and `/usr/sbin/luseradd`)."
commands :add => "groupadd", :delete => "groupdel", :modify => "groupmod"
has_feature :system_groups unless %w[HP-UX Solaris].include? Puppet.runtime[:facter].value('os.name')
verify :gid, _("GID must be an integer") do |value|
value.is_a? Integer
end
optional_commands :localadd => "lgroupadd", :localdelete => "lgroupdel", :localmodify => "lgroupmod", :purgemember => "usermod"
has_feature :manages_local_users_and_groups if Puppet.features.libuser?
has_feature :manages_members if Puppet.features.libuser? ||
(Puppet.runtime[:facter].value('os.name') == "Fedora" &&
Puppet.runtime[:facter].value('os.release.major').to_i >= 40)
# Libuser's modify command 'lgroupmod' requires '-M' flag for member additions.
# 'groupmod' command requires the '-aU' flags for it.
if Puppet.features.libuser?
options :members, :flag => '-M', :method => :mem
else
options :members, :flag => '-aU', :method => :mem
end
def exists?
return !!localgid if @resource.forcelocal?
super
end
def gid
return localgid if @resource.forcelocal?
get(:gid)
end
def localgid
group = findgroup(:group_name, resource[:name])
return group[:gid] if group
false
end
def check_allow_dup
# We have to manually check for duplicates when using libuser
# because by default duplicates are allowed. This check is
# to ensure consistent behaviour of the useradd provider when
# using both useradd and luseradd
if !@resource.allowdupe? and @resource.forcelocal?
if @resource.should(:gid) and findgroup(:gid, @resource.should(:gid).to_s)
raise(Puppet::Error, _("GID %{resource} already exists, use allowdupe to force group creation") % { resource: @resource.should(:gid).to_s })
end
elsif @resource.allowdupe? and !@resource.forcelocal?
return ["-o"]
end
[]
end
def create
super
set(:members, @resource[:members]) if @resource[:members]
end
def addcmd
# The localadd command (lgroupadd) must only be called when libuser is supported.
if Puppet.features.libuser? && @resource.forcelocal?
cmd = [command(:localadd)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:add)]
end
gid = @resource.should(:gid)
if gid
unless gid == :absent
cmd << flag(:gid) << gid
end
end
cmd += check_allow_dup
cmd << "-r" if @resource.system? and self.class.system_groups?
cmd << @resource[:name]
cmd
end
def validate_members(members)
members.each do |member|
member.split(',').each do |user|
Etc.getpwnam(user.strip)
end
end
end
def modifycmd(param, value)
# The localmodify command (lgroupmod) must only be called when libuser is supported.
if Puppet.features.libuser? && (@resource.forcelocal? || @resource[:members])
cmd = [command(:localmodify)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:modify)]
end
if param == :members
validate_members(value)
value = members_to_s(value)
purge_members if @resource[:auth_membership] && !members.empty?
end
cmd << flag(param) << value
# TODO the group type only really manages gid, so there are currently no
# tests for this behavior
cmd += check_allow_dup if param == :gid
cmd << @resource[:name]
cmd
end
def deletecmd
# The localdelete command (lgroupdel) must only be called when libuser is supported.
if Puppet.features.libuser? && @resource.forcelocal?
@custom_environment = Puppet::Util::Libuser.getenv
[command(:localdelete), @resource[:name]]
else
[command(:delete), @resource[:name]]
end
end
def members_insync?(current, should)
current.uniq.sort == @resource.parameter(:members).actual_should(current, should)
end
def members_to_s(current)
return '' if current.nil? || !current.is_a?(Array)
current.join(',')
end
def purge_members
# The groupadd provider doesn't have the ability currently to remove members from a group, libuser does.
# Use libuser's lgroupmod command to achieve purging members if libuser is supported.
# Otherwise use the 'usermod' command.
if Puppet.features.libuser?
localmodify('-m', members_to_s(members), @resource.name)
else
members.each do |member|
purgemember('-rG', @resource.name, member)
end
end
end
private
def findgroup(key, value)
group_file = '/etc/group'
group_keys = [:group_name, :password, :gid, :user_list]
unless @groups
unless Puppet::FileSystem.exist?(group_file)
raise Puppet::Error, "Forcelocal set for group resource '#{resource[:name]}', but #{group_file} does not exist"
end
@groups = []
Puppet::FileSystem.each_line(group_file) do |line|
group = line.chomp.split(':')
@groups << group_keys.zip(group).to_h
end
end
@groups.find { |param| param[key] == value } || false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/group/ldap.rb | lib/puppet/provider/group/ldap.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/ldap'
Puppet::Type.type(:group).provide :ldap, :parent => Puppet::Provider::Ldap do
desc "Group management via LDAP.
This provider requires that you have valid values for all of the
LDAP-related settings in `puppet.conf`, including `ldapbase`. You will
almost definitely need settings for `ldapuser` and `ldappassword` in order
for your clients to write to LDAP.
Note that this provider will automatically generate a GID for you if you do
not specify one, but it is a potentially expensive operation, as it
iterates across all existing groups to pick the appropriate next one."
confine :feature => :ldap, :false => (Puppet[:ldapuser] == "")
# We're mapping 'members' here because we want to make it
# easy for the ldap user provider to manage groups. This
# way it can just use the 'update' method in the group manager,
# whereas otherwise it would need to replicate that code.
manages(:posixGroup).at("ou=Groups").and.maps :name => :cn, :gid => :gidNumber, :members => :memberUid
# Find the next gid after the current largest gid.
provider = self
manager.generates(:gidNumber).with do
largest = 500
existing = provider.manager.search
if existing
existing.each do |hash|
value = hash[:gid]
next unless value
num = value[0].to_i
largest = num if num > largest
end
end
largest + 1
end
# Convert a group name to an id.
def self.name2id(group)
result = manager.search("cn=#{group}")
return nil unless result and result.length > 0
# Only use the first result.
group = result[0]
group[:gid][0]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/nameservice/directoryservice.rb | lib/puppet/provider/nameservice/directoryservice.rb | # frozen_string_literal: true
require_relative '../../../puppet'
require_relative '../../../puppet/provider/nameservice'
require_relative '../../../puppet/util/plist' if Puppet.features.cfpropertylist?
require 'fileutils'
class Puppet::Provider::NameService::DirectoryService < Puppet::Provider::NameService
# JJM: Dive into the singleton_class
class << self
# JJM: This allows us to pass information when calling
# Puppet::Type.type
# e.g. Puppet::Type.type(:user).provide :directoryservice, :ds_path => "Users"
# This is referenced in the get_ds_path class method
attr_writer :ds_path
end
initvars
commands :dscl => "/usr/bin/dscl"
commands :dseditgroup => "/usr/sbin/dseditgroup"
commands :sw_vers => "/usr/bin/sw_vers"
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
defaultfor 'os.name' => :darwin
# There is no generalized mechanism for provider cache management, but we can
# use post_resource_eval, which will be run for each suitable provider at the
# end of each transaction. Use this to clear @all_present after each run.
def self.post_resource_eval
@all_present = nil
end
# JJM 2007-07-25: This map is used to map NameService attributes to their
# corresponding DirectoryService attribute names.
# See: http://images.apple.com/server/docs.Open_Directory_v10.4.pdf
# JJM: Note, this is de-coupled from the Puppet::Type, and must
# be actively maintained. There may also be collisions with different
# types (Users, Groups, Mounts, Hosts, etc...)
def ds_to_ns_attribute_map; self.class.ds_to_ns_attribute_map; end
def self.ds_to_ns_attribute_map
{
'RecordName' => :name,
'PrimaryGroupID' => :gid,
'NFSHomeDirectory' => :home,
'UserShell' => :shell,
'UniqueID' => :uid,
'RealName' => :comment,
'Password' => :password,
'GeneratedUID' => :guid,
'IPAddress' => :ip_address,
'ENetAddress' => :en_address,
'GroupMembership' => :members,
}
end
# JJM The same table as above, inverted.
def ns_to_ds_attribute_map; self.class.ns_to_ds_attribute_map end
def self.ns_to_ds_attribute_map
@ns_to_ds_attribute_map ||= ds_to_ns_attribute_map.invert
end
def self.password_hash_dir
'/var/db/shadow/hash'
end
def self.users_plist_dir
'/var/db/dslocal/nodes/Default/users'
end
def self.instances
# JJM Class method that provides an array of instance objects of this
# type.
# JJM: Properties are dependent on the Puppet::Type we're managing.
type_property_array = [:name] + @resource_type.validproperties
# Create a new instance of this Puppet::Type for each object present
# on the system.
list_all_present.collect do |name_string|
new(single_report(name_string, *type_property_array))
end
end
def self.get_ds_path
# JJM: 2007-07-24 This method dynamically returns the DS path we're concerned with.
# For example, if we're working with an user type, this will be /Users
# with a group type, this will be /Groups.
# @ds_path is an attribute of the class itself.
return @ds_path if defined?(@ds_path)
# JJM: "Users" or "Groups" etc ... (Based on the Puppet::Type)
# Remember this is a class method, so self.class is Class
# Also, @resource_type seems to be the reference to the
# Puppet::Type this class object is providing for.
@resource_type.name.to_s.capitalize + "s"
end
def self.list_all_present
# rubocop:disable Naming/MemoizedInstanceVariableName
@all_present ||= begin
# rubocop:enable Naming/MemoizedInstanceVariableName
# JJM: List all objects of this Puppet::Type already present on the system.
begin
dscl_output = execute(get_exec_preamble("-list"))
rescue Puppet::ExecutionFailure
fail(_("Could not get %{resource} list from DirectoryService") % { resource: @resource_type.name })
end
dscl_output.split("\n")
end
end
def self.parse_dscl_plist_data(dscl_output)
Puppet::Util::Plist.parse_plist(dscl_output)
end
def self.generate_attribute_hash(input_hash, *type_properties)
attribute_hash = {}
input_hash.each_key do |key|
ds_attribute = key.sub("dsAttrTypeStandard:", "")
next unless ds_to_ns_attribute_map.keys.include?(ds_attribute) and type_properties.include? ds_to_ns_attribute_map[ds_attribute]
ds_value = input_hash[key]
case ds_to_ns_attribute_map[ds_attribute]
when :members
# do nothing, only members uses arrays so far
when :gid, :uid
# OS X stores objects like uid/gid as strings.
# Try casting to an integer for these cases to be
# consistent with the other providers and the group type
# validation
begin
ds_value = Integer(ds_value[0])
rescue ArgumentError
ds_value = ds_value[0]
end
else ds_value = ds_value[0]
end
attribute_hash[ds_to_ns_attribute_map[ds_attribute]] = ds_value
end
# NBK: need to read the existing password here as it's not actually
# stored in the user record. It is stored at a path that involves the
# UUID of the user record for non-Mobile local accounts.
# Mobile Accounts are out of scope for this provider for now
attribute_hash[:password] = get_password(attribute_hash[:guid], attribute_hash[:name]) if @resource_type.validproperties.include?(:password) and Puppet.features.root?
attribute_hash
end
def self.single_report(resource_name, *type_properties)
# JJM 2007-07-24:
# Given a the name of an object and a list of properties of that
# object, return all property values in a hash.
#
# This class method returns nil if the object doesn't exist
# Otherwise, it returns a hash of the object properties.
all_present_str_array = list_all_present
# NBK: shortcut the process if the resource is missing
return nil unless all_present_str_array.include? resource_name
dscl_vector = get_exec_preamble("-read", resource_name)
begin
dscl_output = execute(dscl_vector)
rescue Puppet::ExecutionFailure
fail(_("Could not get report. command execution failed."))
end
dscl_plist = parse_dscl_plist_data(dscl_output)
generate_attribute_hash(dscl_plist, *type_properties)
end
def self.get_exec_preamble(ds_action, resource_name = nil)
# JJM 2007-07-24
# DSCL commands are often repetitive and contain the same positional
# arguments over and over. See https://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html
# for an example of what I mean.
# This method spits out proper DSCL commands for us.
# We EXPECT name to be @resource[:name] when called from an instance object.
command_vector = [command(:dscl), "-plist", "."]
# JJM: The actual action to perform. See "man dscl".
# Common actions: -create, -delete, -merge, -append, -passwd
command_vector << ds_action
# JJM: get_ds_path will spit back "Users" or "Groups",
# etc... Depending on the Puppet::Type of our self.
if resource_name
command_vector << "/#{get_ds_path}/#{resource_name}"
else
command_vector << "/#{get_ds_path}"
end
# JJM: This returns most of the preamble of the command.
# e.g. 'dscl / -create /Users/mccune'
command_vector
end
def self.set_password(resource_name, guid, password_hash)
# 10.7 uses salted SHA512 password hashes which are 128 characters plus
# an 8 character salt. Previous versions used a SHA1 hash padded with
# zeroes. If someone attempts to use a password hash that worked with
# a previous version of OS X, we will fail early and warn them.
if password_hash.length != 136
# TRANSLATORS 'OS X 10.7' is an operating system and should not be translated, 'Salted SHA512' is the name of a hashing algorithm
fail(_("OS X 10.7 requires a Salted SHA512 hash password of 136 characters.") +
' ' + _("Please check your password and try again."))
end
plist_file = "#{users_plist_dir}/#{resource_name}.plist"
if Puppet::FileSystem.exist?(plist_file)
# If a plist already exists in /var/db/dslocal/nodes/Default/users, then
# we will need to extract the binary plist from the 'ShadowHashData'
# key, log the new password into the resultant plist's 'SALTED-SHA512'
# key, and then save the entire structure back.
users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
# users_plist['ShadowHashData'][0] is actually a binary plist
# that's nested INSIDE the user's plist (which itself is a binary
# plist). If we encounter a user plist that DOESN'T have a
# ShadowHashData field, create one.
if users_plist['ShadowHashData']
password_hash_plist = users_plist['ShadowHashData'][0]
converted_hash_plist = convert_binary_to_hash(password_hash_plist)
else
users_plist['ShadowHashData'] = ''.dup
converted_hash_plist = { 'SALTED-SHA512' => ''.dup }
end
# converted_hash_plist['SALTED-SHA512'] expects a Base64 encoded
# string. The password_hash provided as a resource attribute is a
# hex value. We need to convert the provided hex value to a Base64
# encoded string to nest it in the converted hash plist.
converted_hash_plist['SALTED-SHA512'] = \
password_hash.unpack('a2' * (password_hash.size / 2)).collect { |i| i.hex.chr }.join
# Finally, we can convert the nested plist back to binary, embed it
# into the user's plist, and convert the resultant plist back to
# a binary plist.
changed_plist = convert_hash_to_binary(converted_hash_plist)
users_plist['ShadowHashData'][0] = changed_plist
Puppet::Util::Plist.write_plist_file(users_plist, plist_file, :binary)
end
end
def self.get_password(guid, username)
plist_file = "#{users_plist_dir}/#{username}.plist"
if Puppet::FileSystem.exist?(plist_file)
# If a plist exists in /var/db/dslocal/nodes/Default/users, we will
# extract the binary plist from the 'ShadowHashData' key, decode the
# salted-SHA512 password hash, and then return it.
users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
if users_plist['ShadowHashData']
# users_plist['ShadowHashData'][0] is actually a binary plist
# that's nested INSIDE the user's plist (which itself is a binary
# plist).
password_hash_plist = users_plist['ShadowHashData'][0]
converted_hash_plist = convert_binary_to_hash(password_hash_plist)
# converted_hash_plist['SALTED-SHA512'] is a Base64 encoded
# string. The password_hash provided as a resource attribute is a
# hex value. We need to convert the Base64 encoded string to a
# hex value and provide it back to Puppet.
converted_hash_plist['SALTED-SHA512'].unpack1("H*")
end
end
end
# This method will accept a hash and convert it to a binary plist (string value).
def self.convert_hash_to_binary(plist_data)
Puppet.debug('Converting plist hash to binary')
Puppet::Util::Plist.dump_plist(plist_data, :binary)
end
# This method will accept a binary plist (as a string) and convert it to a hash.
def self.convert_binary_to_hash(plist_data)
Puppet.debug('Converting binary plist to hash')
Puppet::Util::Plist.parse_plist(plist_data)
end
# Unlike most other *nixes, OS X doesn't provide built in functionality
# for automatically assigning uids and gids to accounts, so we set up these
# methods for consumption by functionality like --mkusers
# By default we restrict to a reasonably sane range for system accounts
def self.next_system_id(id_type, min_id = 20)
dscl_args = ['.', '-list']
case id_type
when 'uid'
dscl_args << '/Users' << 'uid'
when 'gid'
dscl_args << '/Groups' << 'gid'
else
fail(_("Invalid id_type %{id_type}. Only 'uid' and 'gid' supported") % { id_type: id_type })
end
dscl_out = dscl(dscl_args)
# We're ok with throwing away negative uids here.
ids = dscl_out.split.compact.collect { |l| l.to_i if l =~ /^\d+$/ }
ids.compact!.sort_by!(&:to_f)
# We're just looking for an unused id in our sorted array.
ids.each_index do |i|
next_id = ids[i] + 1
return next_id if ids[i + 1] != next_id and next_id >= min_id
end
end
def ensure=(ensure_value)
super
# We need to loop over all valid properties for the type we're
# managing and call the method which sets that property value
# dscl can't create everything at once unfortunately.
if ensure_value == :present
@resource.class.validproperties.each do |name|
next if name == :ensure
# LAK: We use property.sync here rather than directly calling
# the settor method because the properties might do some kind
# of conversion. In particular, the user gid property might
# have a string and need to convert it to a number
if @resource.should(name)
@resource.property(name).sync
else
value = autogen(name)
if value
send(name.to_s + "=", value)
else
next
end
end
end
end
end
def password=(passphrase)
exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
exec_arg_vector << ns_to_ds_attribute_map[:guid]
begin
guid_output = execute(exec_arg_vector)
guid_plist = Puppet::Util::Plist.parse_plist(guid_output)
# Although GeneratedUID like all DirectoryService values can be multi-valued
# according to the schema, in practice user accounts cannot have multiple UUIDs
# otherwise Bad Things Happen, so we just deal with the first value.
guid = guid_plist["dsAttrTypeStandard:#{ns_to_ds_attribute_map[:guid]}"][0]
self.class.set_password(@resource.name, guid, passphrase)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
# NBK: we override @parent.set as we need to execute a series of commands
# to deal with array values, rather than the single command nameservice.rb
# expects to be returned by modifycmd. Thus we don't bother defining modifycmd.
def set(param, value)
self.class.validate(param, value)
current_members = @property_value_cache_hash[:members]
if param == :members
# If we are meant to be authoritative for the group membership
# then remove all existing members who haven't been specified
# in the manifest.
remove_unwanted_members(current_members, value) if @resource[:auth_membership] and !current_members.nil?
# if they're not a member, make them one.
add_members(current_members, value)
else
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
# JJM: The following line just maps the NS name to the DS name
# e.g. { :uid => 'UniqueID' }
exec_arg_vector << ns_to_ds_attribute_map[param.intern]
# JJM: The following line sends the actual value to set the property to
exec_arg_vector << value.to_s
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
end
# NBK: we override @parent.create as we need to execute a series of commands
# to create objects with dscl, rather than the single command nameservice.rb
# expects to be returned by addcmd. Thus we don't bother defining addcmd.
def create
if exists?
info _("already exists")
return nil
end
# NBK: First we create the object with a known guid so we can set the contents
# of the password hash if required
# Shelling out sucks, but for a single use case it doesn't seem worth
# requiring people install a UUID library that doesn't come with the system.
# This should be revisited if Puppet starts managing UUIDs for other platform
# user records.
guid = %x(/usr/bin/uuidgen).chomp
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
exec_arg_vector << ns_to_ds_attribute_map[:guid] << guid
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set GeneratedUID for %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
end
value = @resource.should(:password)
if value && value != ""
self.class.set_password(@resource[:name], guid, value)
end
# Now we create all the standard properties
Puppet::Type.type(@resource.class.name).validproperties.each do |property|
next if property == :ensure
value = @resource.should(property)
if property == :gid and value.nil?
value = self.class.next_system_id('gid')
end
if property == :uid and value.nil?
value = self.class.next_system_id('uid')
end
if value != "" and !value.nil?
if property == :members
add_members(nil, value)
else
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
exec_arg_vector << ns_to_ds_attribute_map[property.intern]
next if property == :password # skip setting the password here
exec_arg_vector << value.to_s
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
end
end
end
def remove_unwanted_members(current_members, new_members)
current_members.each do |member|
next if new_members.flatten.include?(member)
cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
begin
execute(cmd)
rescue Puppet::ExecutionFailure
# TODO: We're falling back to removing the member using dscl due to rdar://8481241
# This bug causes dseditgroup to fail to remove a member if that member doesn't exist
cmd = [:dscl, ".", "-delete", "/Groups/#{@resource.name}", "GroupMembership", member]
begin
execute(cmd)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not remove %{member} from group: %{resource}, %{detail}") % { member: member, resource: @resource.name, detail: detail })
end
end
end
end
def add_members(current_members, new_members)
new_members.flatten.each do |new_member|
next unless current_members.nil? or !current_members.include?(new_member)
cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
begin
execute(cmd)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not add %{new_member} to group: %{name}, %{detail}") % { new_member: new_member, name: @resource.name, detail: detail })
end
end
end
def deletecmd
# JJM: Like addcmd, only called when deleting the object itself
# Note, this isn't used to delete properties of the object,
# at least that's how I understand it...
self.class.get_exec_preamble("-delete", @resource[:name])
end
def getinfo(refresh = false)
# JJM 2007-07-24:
# Override the getinfo method, which is also defined in nameservice.rb
# This method returns and sets @infohash
# I'm not re-factoring the name "getinfo" because this method will be
# most likely called by nameservice.rb, which I didn't write.
if refresh or (!defined?(@property_value_cache_hash) or !@property_value_cache_hash)
# JJM 2007-07-24: OK, there's a bit of magic that's about to
# happen... Let's see how strong my grip has become... =)
#
# self is a provider instance of some Puppet::Type, like
# Puppet::Type::User::ProviderDirectoryservice for the case of the
# user type and this provider.
#
# self.class looks like "user provider directoryservice", if that
# helps you ...
#
# self.class.resource_type is a reference to the Puppet::Type class,
# probably Puppet::Type::User or Puppet::Type::Group, etc...
#
# self.class.resource_type.validproperties is a class method,
# returning an Array of the valid properties of that specific
# Puppet::Type.
#
# So... something like [:comment, :home, :password, :shell, :uid,
# :groups, :ensure, :gid]
#
# Ultimately, we add :name to the list, delete :ensure from the
# list, then report on the remaining list. Pretty whacky, ehh?
type_properties = [:name] + self.class.resource_type.validproperties
type_properties.delete(:ensure) if type_properties.include? :ensure
type_properties << :guid # append GeneratedUID so we just get the report here
@property_value_cache_hash = self.class.single_report(@resource[:name], *type_properties)
[:uid, :gid].each do |param|
@property_value_cache_hash[param] = @property_value_cache_hash[param].to_i if @property_value_cache_hash and @property_value_cache_hash.include?(param)
end
end
@property_value_cache_hash
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/nameservice/pw.rb | lib/puppet/provider/nameservice/pw.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/objectadd'
class Puppet::Provider::NameService
class PW < ObjectAdd
def deletecmd
[command(:pw), "#{@resource.class.name}del", @resource[:name]]
end
def modifycmd(param, value)
[
command(:pw),
"#{@resource.class.name}mod",
@resource[:name],
flag(param),
munge(param, value)
]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/nameservice/objectadd.rb | lib/puppet/provider/nameservice/objectadd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice'
class Puppet::Provider::NameService
class ObjectAdd < Puppet::Provider::NameService
def deletecmd
[command(:delete), @resource[:name]]
end
# Determine the flag to pass to our command.
def flag(name)
name = name.intern if name.is_a? String
self.class.option(name, :flag) || "-" + name.to_s[0, 1]
end
def posixmethod(name)
name = name.intern if name.is_a? String
self.class.option(name, :method) || name
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/freebsd.rb | lib/puppet/provider/package/freebsd.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :freebsd, :parent => :openbsd do
desc "The specific form of package management on FreeBSD. This is an
extremely quirky packaging system, in that it freely mixes between
ports and packages. Apparently all of the tools are written in Ruby,
so there are plans to rewrite this support to directly use those
libraries."
commands :pkginfo => "/usr/sbin/pkg_info",
:pkgadd => "/usr/sbin/pkg_add",
:pkgdelete => "/usr/sbin/pkg_delete"
confine 'os.name' => :freebsd
def self.listcmd
command(:pkginfo)
end
def install
if @resource[:source] =~ %r{/$}
if @resource[:source] =~ /^(ftp|https?):/
Puppet::Util.withenv :PACKAGESITE => @resource[:source] do
pkgadd "-r", @resource[:name]
end
else
Puppet::Util.withenv :PKG_PATH => @resource[:source] do
pkgadd @resource[:name]
end
end
else
Puppet.warning _("source is defined but does not have trailing slash, ignoring %{source}") % { source: @resource[:source] } if @resource[:source]
pkgadd "-r", @resource[:name]
end
end
def query
self.class.instances.each do |provider|
if provider.name == @resource.name
return provider.properties
end
end
nil
end
def uninstall
pkgdelete "#{@resource[:name]}-#{@resource.should(:ensure)}"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/urpmi.rb | lib/puppet/provider/package/urpmi.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :urpmi, :parent => :rpm, :source => :rpm do
desc "Support via `urpmi`."
commands :urpmi => "urpmi", :urpmq => "urpmq", :rpm => "rpm", :urpme => "urpme"
defaultfor 'os.name' => [:mandriva, :mandrake]
has_feature :versionable
def install
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
wanted = @resource[:name]
# XXX: We don't actually deal with epochs here.
case should
when true, false, Symbol
# pass
else
# Add the package version
wanted += "-#{should}"
end
urpmi "--auto", wanted
unless query
raise Puppet::Error, _("Package %{name} was not present after trying to install it") % { name: name }
end
end
# What's the latest package version available?
def latest
output = urpmq "-S", @resource[:name]
if output =~ /^#{Regexp.escape @resource[:name]}\s+:\s+.*\(\s+(\S+)\s+\)/
Regexp.last_match(1)
else
# urpmi didn't find updates, pretend the current
# version is the latest
@resource[:ensure]
end
end
def update
# Install in urpmi can be used for update, too
install
end
# For normal package removal the urpmi provider will delegate to the RPM
# provider. If the package to remove has dependencies then uninstalling via
# rpm will fail, but `urpme` can be used to remove a package and its
# dependencies.
def purge
urpme '--auto', @resource[:name]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/aptrpm.rb | lib/puppet/provider/package/aptrpm.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :aptrpm, :parent => :rpm, :source => :rpm do
# Provide sorting functionality
include Puppet::Util::Package
desc "Package management via `apt-get` ported to `rpm`."
has_feature :versionable
commands :aptget => "apt-get"
commands :aptcache => "apt-cache"
commands :rpm => "rpm"
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('-ql', 'rpm')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
# Install a package using 'apt-get'. This function needs to support
# installing a specific version.
def install
should = @resource.should(:ensure)
str = @resource[:name]
case should
when true, false, Symbol
# pass
else
# Add the package version
str += "=#{should}"
end
cmd = %w[-q -y]
cmd << 'install' << str
aptget(*cmd)
end
# What's the latest package version available?
def latest
output = aptcache :showpkg, @resource[:name]
if output =~ /Versions:\s*\n((\n|.)+)^$/
versions = Regexp.last_match(1)
available_versions = versions.split(/\n/).filter_map { |version|
if version =~ /^([^(]+)\(/
Regexp.last_match(1)
else
warning _("Could not match version '%{version}'") % { version: version }
nil
end
}.sort { |a, b| versioncmp(a, b) }
if available_versions.length == 0
debug "No latest version"
print output if Puppet[:debug]
end
# Get the latest and greatest version number
available_versions.pop
else
err _("Could not match string")
end
end
def update
install
end
def uninstall
aptget "-y", "-q", 'remove', @resource[:name]
end
def purge
aptget '-y', '-q', 'remove', '--purge', @resource[:name]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/portage.rb | lib/puppet/provider/package/portage.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require 'fileutils'
Puppet::Type.type(:package).provide :portage, :parent => Puppet::Provider::Package do
desc "Provides packaging support for Gentoo's portage system.
This provider supports the `install_options` and `uninstall_options` attributes, which allows command-line
flags to be passed to emerge. These options should be specified as an array where each element is either a string or a hash."
has_features :install_options, :purgeable, :reinstallable, :uninstall_options, :versionable, :virtual_packages
{
:emerge => '/usr/bin/emerge',
:eix => '/usr/bin/eix',
:qatom_bin => '/usr/bin/qatom',
:update_eix => '/usr/bin/eix-update',
}.each_pair do |name, path|
has_command(name, path) do
environment :HOME => '/'
end
end
confine 'os.family' => :gentoo
defaultfor 'os.family' => :gentoo
def self.instances
result_format = eix_result_format
result_fields = eix_result_fields
limit = eix_limit
version_format = eix_version_format
slot_versions_format = eix_slot_versions_format
installed_versions_format = eix_installed_versions_format
installable_versions_format = eix_install_versions_format
begin
eix_file = File.directory?('/var/cache/eix') ? '/var/cache/eix/portage.eix' : '/var/cache/eix'
update_eix unless FileUtils.uptodate?(eix_file, %w[/usr/bin/eix /usr/portage/metadata/timestamp])
search_output = nil
Puppet::Util.withenv :EIX_LIMIT => limit, :LASTVERSION => version_format, :LASTSLOTVERSIONS => slot_versions_format, :INSTALLEDVERSIONS => installed_versions_format, :STABLEVERSIONS => installable_versions_format do
search_output = eix(*(eix_search_arguments + ['--installed']))
end
packages = []
search_output.each_line do |search_result|
match = result_format.match(search_result)
next unless match
package = {}
result_fields.zip(match.captures) do |field, value|
package[field] = value unless !value or value.empty?
end
package[:provider] = :portage
packages << new(package)
end
packages
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def install
should = @resource.should(:ensure)
cmd = %w[]
name = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
name = qatom[:pfx] + name if qatom[:pfx]
name = name + '-' + qatom[:pv] if qatom[:pv]
name = name + '-' + qatom[:pr] if qatom[:pr]
name = name + ':' + qatom[:slot] if qatom[:slot]
cmd << '--update' if [:latest].include?(should)
cmd += install_options if @resource[:install_options]
cmd << name
emerge(*cmd)
end
def uninstall
should = @resource.should(:ensure)
cmd = %w[--rage-clean]
name = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
name = qatom[:pfx] + name if qatom[:pfx]
name = name + '-' + qatom[:pv] if qatom[:pv]
name = name + '-' + qatom[:pr] if qatom[:pr]
name = name + ':' + qatom[:slot] if qatom[:slot]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << name
if [:purged].include?(should)
Puppet::Util.withenv :CONFIG_PROTECT => "-*" do
emerge(*cmd)
end
else
emerge(*cmd)
end
end
def reinstall
install
end
def update
install
end
def qatom
output_format = qatom_output_format
result_format = qatom_result_format
result_fields = qatom_result_fields
@atom ||= begin
package_info = {}
# do the search
should = @resource[:ensure]
case should
# The terms present, absent, purged, installed, latest in :ensure
# resolve as Symbols, and we do not need specific package version in this case
when true, false, Symbol
search = @resource[:name]
else
search = '=' + @resource[:name] + '-' + should.to_s
end
search_output = qatom_bin(*[search, '--format', output_format])
# verify if the search found anything
match = result_format.match(search_output)
if match
result_fields.zip(match.captures) do |field, value|
# some fields can be empty or (null) (if we are not passed a category in the package name for instance)
if value == '(null)' || value == '<unset>'
package_info[field] = nil
elsif !value or value.empty?
package_info[field] = nil
else
package_info[field] = value
end
end
end
@atom = package_info
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def qatom_output_format
'"[%[CATEGORY]] [%[PN]] [%[PV]] [%[PR]] [%[SLOT]] [%[pfx]] [%[sfx]]"'
end
def qatom_result_format
/^"\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\](.*)"$/
end
def qatom_result_fields
[:category, :pn, :pv, :pr, :slot, :pfx, :sfx]
end
def self.get_sets
@sets ||= @sets = emerge(*['--list-sets'])
end
def query
limit = self.class.eix_limit
result_format = self.class.eix_result_format
result_fields = self.class.eix_result_fields
version_format = self.class.eix_version_format
slot_versions_format = self.class.eix_slot_versions_format
installed_versions_format = self.class.eix_installed_versions_format
installable_versions_format = self.class.eix_install_versions_format
search_field = qatom[:category] ? '--category-name' : '--name'
search_value = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
@eix_result ||= begin
# package sets
package_sets = []
self.class.get_sets.each_line do |package_set|
package_sets << package_set.to_s.strip
end
if @resource[:name] =~ /^@/
if package_sets.include?(@resource[:name][1..].to_s)
return({ :name => (@resource[:name]).to_s, :ensure => '9999', :version_available => nil, :installed_versions => nil, :installable_versions => "9999," })
end
end
eix_file = File.directory?('/var/cache/eix') ? '/var/cache/eix/portage.eix' : '/var/cache/eix'
update_eix unless FileUtils.uptodate?(eix_file, %w[/usr/bin/eix /usr/portage/metadata/timestamp])
search_output = nil
Puppet::Util.withenv :EIX_LIMIT => limit, :LASTVERSION => version_format, :LASTSLOTVERSIONS => slot_versions_format, :INSTALLEDVERSIONS => installed_versions_format, :STABLEVERSIONS => installable_versions_format do
search_output = eix(*(self.class.eix_search_arguments + ['--exact', search_field, search_value]))
end
packages = []
search_output.each_line do |search_result|
match = result_format.match(search_result)
next unless match
package = {}
result_fields.zip(match.captures) do |field, value|
package[field] = value unless !value or value.empty?
end
# dev-lang python [3.4.5] [3.5.2] [2.7.12:2.7,3.4.5:3.4] [2.7.12:2.7,3.4.5:3.4,3.5.2:3.5] https://www.python.org/ An interpreted, interactive, object-oriented programming language
# version_available is what we CAN install / update to
# ensure is what is currently installed
# This DOES NOT choose to install/upgrade or not, just provides current info
# prefer checking versions to slots as versions are finer grained
search = qatom[:pv]
search = search + '-' + qatom[:pr] if qatom[:pr]
if search
package[:version_available] = eix_get_version_for_versions(package[:installable_versions], search)
package[:ensure] = eix_get_version_for_versions(package[:installed_versions], search)
elsif qatom[:slot]
package[:version_available] = eix_get_version_for_slot(package[:slot_versions_available], qatom[:slot])
package[:ensure] = eix_get_version_for_slot(package[:installed_slots], qatom[:slot])
end
package[:ensure] = package[:ensure] || :absent
packages << package
end
case packages.size
when 0
raise Puppet::Error, _("No package found with the specified name [%{name}]") % { name: @resource[:name] }
when 1
@eix_result = packages[0]
else
raise Puppet::Error, _("More than one package with the specified name [%{search_value}], please use the category parameter to disambiguate") % { search_value: search_value }
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def latest
query[:version_available]
end
private
def eix_get_version_for_versions(versions, target)
# [2.7.10-r1,2.7.12,3.4.3-r1,3.4.5,3.5.2] 3.5.2
return nil if versions.nil?
versions = versions.split(',')
# [2.7.10-r1 2.7.12 3.4.3-r1 3.4.5 3.5.2]
versions.find { |version| version == target }
# 3.5.2
end
private
def eix_get_version_for_slot(versions_and_slots, slot)
# [2.7.12:2.7 3.4.5:3.4 3.5.2:3.5] 3.5
return nil if versions_and_slots.nil?
versions_and_slots = versions_and_slots.split(',')
# [2.7.12:2.7 3.4.5:3.4 3.5.2:3.5]
versions_and_slots.map! { |version_and_slot| version_and_slot.split(':') }
# [2.7.12: 2.7
# 3.4.5: 3.4
# 3.5.2: 3.5]
version_for_slot = versions_and_slots.find { |version_and_slot| version_and_slot.last == slot }
# [3.5.2: 3.5]
version_for_slot.first if version_for_slot
# 3.5.2
end
def self.eix_search_format
"'<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] [<installedversions:LASTSLOTVERSIONS>] [<installedversions:INSTALLEDVERSIONS>] [<availableversions:STABLEVERSIONS>] [<bestslotversions:LASTSLOTVERSIONS>] <homepage> <description>\n'"
end
def self.eix_result_format
/^(\S+)\s+(\S+)\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+(\S+)\s+(.*)$/
end
def self.eix_result_fields
# ensure:[3.4.5], version_available:[3.5.2], installed_slots:[2.7.12:2.7,3.4.5:3.4], installable_versions:[2.7.10-r1,2.7.12,3.4.3-r1,3.4.5,3.5.2] slot_versions_available:[2.7.12:2.7,3.4.5:3.4,3.5.2:3.5]
[:category, :name, :ensure, :version_available, :installed_slots, :installed_versions, :installable_versions, :slot_versions_available, :vendor, :description]
end
def self.eix_version_format
'{last}<version>{}'
end
def self.eix_slot_versions_format
'{!first},{}<version>:<slot>'
end
def self.eix_installed_versions_format
'{!first},{}<version>'
end
def self.eix_install_versions_format
'{!first}{!last},{}{}{isstable}<version>{}'
end
def self.eix_limit
'0'
end
def self.eix_search_arguments
['--nocolor', '--pure-packages', '--format', eix_search_format]
end
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pip2.rb | lib/puppet/provider/package/pip2.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip2` package management frontend.
# <http://pip.pypa.io/>
Puppet::Type.type(:package).provide :pip2,
:parent => :pip do
desc "Python packages via `pip2`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip2.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :install_options, :targetable
def self.cmd
["pip2"]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/zypper.rb | lib/puppet/provider/package/zypper.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :zypper, :parent => :rpm, :source => :rpm do
desc "Support for SuSE `zypper` package manager. Found in SLES10sp2+ and SLES11.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to zypper.
These options should be specified as an array where each element is either a
string or a hash."
has_feature :versionable, :install_options, :virtual_packages
commands :zypper => "/usr/bin/zypper"
defaultfor 'os.name' => [:suse, :sles, :sled, :opensuse]
confine 'os.name' => [:suse, :sles, :sled, :opensuse]
# @api private
# Reset the latest version hash to nil
# needed for spec tests to clear cached value
def self.reset!
@latest_versions = nil
end
def self.latest_package_version(package)
if @latest_versions.nil?
@latest_versions = list_updates
end
@latest_versions[package]
end
def self.list_updates
output = zypper 'list-updates'
avail_updates = {}
# split up columns
output.lines.each do |line|
pkg_ver = line.split(/\s*\|\s*/)
# ignore zypper headers
next unless pkg_ver[0] == 'v'
avail_updates[pkg_ver[2]] = pkg_ver[4]
end
avail_updates
end
# on zypper versions <1.0, the version option returns 1
# some versions of zypper output on stderr
def zypper_version
cmd = [self.class.command(:zypper), "--version"]
execute(cmd, { :failonfail => false, :combine => true })
end
def best_version(should)
if should.is_a?(String)
begin
should_range = Puppet::Util::Package::Version::Range.parse(should, Puppet::Util::Package::Version::Rpm)
rescue Puppet::Util::Package::Version::Range::ValidationFailure, Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return should
end
if should_range.is_a?(Puppet::Util::Package::Version::Range::Eq)
return should
end
versions = []
output = zypper('search', '--match-exact', '--type', 'package', '--uninstalled-only', '-s', @resource[:name])
output.lines.each do |line|
pkg_ver = line.split(/\s*\|\s*/)
next unless pkg_ver[1] == @resource[:name]
begin
rpm_version = Puppet::Util::Package::Version::Rpm.parse(pkg_ver[3])
versions << rpm_version if should_range.include?(rpm_version)
rescue Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{pkg_ver[3]} as a RPM version")
end
end
return versions.max if versions.any?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should
end
end
# Install a package using 'zypper'.
def install
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
wanted = @resource[:name]
# XXX: We don't actually deal with epochs here.
case should
when true, false, Symbol
should = nil
else
# Add the package version
should = best_version(should)
wanted = "#{wanted}-#{should}"
end
# This has been tested with following zypper versions
# SLE 10.4: 0.6.201
# SLE 11.3: 1.6.307
# SLE 12.0: 1.11.14
# Assume that this will work on newer zypper versions
# extract version numbers and convert to integers
major, minor, patch = zypper_version.scan(/\d+/).map(&:to_i)
debug "Detected zypper version #{major}.#{minor}.#{patch}"
# zypper version < 1.0 does not support --quiet flag
if major < 1
quiet = '--terse'
else
quiet = '--quiet'
end
inst_opts = []
inst_opts = install_options if resource[:install_options]
options = []
options << quiet
options << '--no-gpg-check' unless inst_opts.delete('--no-gpg-check').nil?
options << '--no-gpg-checks' unless inst_opts.delete('--no-gpg-checks').nil?
options << :install
# zypper 0.6.13 (OpenSuSE 10.2) does not support auto agree with licenses
options << '--auto-agree-with-licenses' unless major < 1 and minor <= 6 and patch <= 13
options << '--no-confirm'
options += inst_opts unless inst_opts.empty?
# Zypper 0.6.201 doesn't recognize '--name'
# It is unclear where this functionality was introduced, but it
# is present as early as 1.0.13
options << '--name' unless major < 1 || @resource.allow_virtual? || should
options << wanted
zypper(*options)
unless query
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name }
end
end
# What's the latest package version available?
def latest
self.class.latest_package_version(@resource[:name]) ||
# zypper didn't find updates, pretend the current
# version is the latest
@property_hash[:ensure]
end
def update
# zypper install can be used for update, too
install
end
def uninstall
# extract version numbers and convert to integers
major, minor, _ = zypper_version.scan(/\d+/).map(&:to_i)
if major < 1
super
else
options = [:remove, '--no-confirm']
if major == 1 && minor < 6
options << '--force-resolution'
end
options << @resource[:name]
zypper(*options)
end
end
def insync?(is)
return false if [:purged, :absent].include?(is)
should = @resource[:ensure]
if should.is_a?(String)
begin
should_version = Puppet::Util::Package::Version::Range.parse(should, Puppet::Util::Package::Version::Rpm)
if should_version.is_a?(RPM_VERSION_RANGE::Eq)
return super
end
rescue Puppet::Util::Package::Version::Range::ValidationFailure, Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return super
end
begin
is_version = Puppet::Util::Package::Version::Rpm.parse(is)
should_version.include?(is_version)
rescue Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{is} as a RPM version")
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/macports.rb | lib/puppet/provider/package/macports.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/provider/command'
Puppet::Type.type(:package).provide :macports, :parent => Puppet::Provider::Package do
desc "Package management using MacPorts on OS X.
Supports MacPorts versions and revisions, but not variants.
Variant preferences may be specified using
[the MacPorts variants.conf file](http://guide.macports.org/chunked/internals.configuration-files.html#internals.configuration-files.variants-conf).
When specifying a version in the Puppet DSL, only specify the version, not the revision.
Revisions are only used internally for ensuring the latest version/revision of a port.
"
confine 'os.name' => :darwin
has_command(:port, "/opt/local/bin/port") do
environment :HOME => "/opt/local"
end
has_feature :installable
has_feature :uninstallable
has_feature :upgradeable
has_feature :versionable
def self.parse_installed_query_line(line)
regex = /(\S+)\s+@(\S+)_(\d+).*\(active\)/
fields = [:name, :ensure, :revision]
hash_from_line(line, regex, fields)
end
def self.parse_info_query_line(line)
regex = /(\S+)\s+(\S+)/
fields = [:version, :revision]
hash_from_line(line, regex, fields)
end
def self.hash_from_line(line, regex, fields)
hash = {}
match = regex.match(line)
if match
fields.zip(match.captures) { |field, value|
hash[field] = value
}
hash[:provider] = name
return hash
end
nil
end
def self.instances
packages = []
port("-q", :installed).each_line do |line|
hash = parse_installed_query_line(line)
if hash
packages << new(hash)
end
end
packages
end
def install
should = @resource.should(:ensure)
if [:latest, :installed, :present].include?(should)
port("-q", :install, @resource[:name])
else
port("-q", :install, @resource[:name], "@#{should}")
end
# MacPorts now correctly exits non-zero with appropriate errors in
# situations where a port cannot be found or installed.
end
def query
result = self.class.parse_installed_query_line(execute([command(:port), "-q", :installed, @resource[:name]], :failonfail => false, :combine => false))
return {} if result.nil?
result
end
def latest
# We need both the version and the revision to be confident
# we've got the latest revision of a specific version
# Note we're still not doing anything with variants here.
info_line = execute([command(:port), "-q", :info, "--line", "--version", "--revision", @resource[:name]], :failonfail => false, :combine => false)
return nil if info_line == ""
newest = self.class.parse_info_query_line(info_line)
if newest
current = query
# We're doing some fiddling behind the scenes here to cope with updated revisions.
# If we're already at the latest version/revision, then just return the version
# so the current and desired values match. Otherwise return version and revision
# to trigger an upgrade to the latest revision.
if newest[:version] == current[:ensure] and newest[:revision] == current[:revision]
return current[:ensure]
else
return "#{newest[:version]}_#{newest[:revision]}"
end
end
nil
end
def uninstall
port("-q", :uninstall, @resource[:name])
end
def update
install
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/hpux.rb | lib/puppet/provider/package/hpux.rb | # frozen_string_literal: true
# HP-UX packaging.
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :hpux, :parent => Puppet::Provider::Package do
desc "HP-UX's packaging system."
commands :swinstall => "/usr/sbin/swinstall",
:swlist => "/usr/sbin/swlist",
:swremove => "/usr/sbin/swremove"
confine 'os.name' => "hp-ux"
defaultfor 'os.name' => "hp-ux"
def self.instances
# TODO: This is very hard on HP-UX!
[]
end
# source and name are required
def install
raise ArgumentError, _("source must be provided to install HP-UX packages") unless resource[:source]
args = standard_args + ["-s", resource[:source], resource[:name]]
swinstall(*args)
end
def query
swlist resource[:name]
{ :ensure => :present }
rescue
{ :ensure => :absent }
end
def uninstall
args = standard_args + [resource[:name]]
swremove(*args)
end
def standard_args
["-x", "mount_all_filesystems=false"]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/opkg.rb | lib/puppet/provider/package/opkg.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :opkg, :source => :opkg, :parent => Puppet::Provider::Package do
desc "Opkg packaging support. Common on OpenWrt, TurrisOS, and OpenEmbedded platforms"
commands :opkg => "opkg"
confine 'os.name' => [:openwrt, :turrisos]
defaultfor 'os.name' => [:openwrt, :turrisos]
def self.instances
packages = []
execpipe("#{command(:opkg)} list-installed") do |process|
regex = /^(\S+) - (\S+)/
fields = [:name, :ensure]
hash = {}
process.each_line { |line|
match = regex.match(line)
if match
fields.zip(match.captures) { |field, value| hash[field] = value }
hash[:provider] = name
packages << new(hash)
hash = {}
else
warning(_("Failed to match line %{line}") % { line: line })
end
}
end
packages
rescue Puppet::ExecutionFailure
nil
end
def latest
output = opkg("list", @resource[:name])
matches = /^(\S+) - (\S+)/.match(output).captures
matches[1]
end
def install
# OpenWrt and TurrisOS package lists are ephemeral, make sure we have at least
# some entries in the list directory for opkg to use
opkg('update') if package_lists.size <= 2
if @resource[:source]
opkg('--force-overwrite', 'install', @resource[:source])
else
opkg('--force-overwrite', 'install', @resource[:name])
end
end
def uninstall
opkg('remove', @resource[:name])
end
def update
install
end
def query
# list out our specific package
output = opkg('list-installed', @resource[:name])
if output =~ /^(\S+) - (\S+)/
return { :ensure => Regexp.last_match(2) }
end
nil
rescue Puppet::ExecutionFailure
{
:ensure => :purged,
:status => 'missing',
:name => @resource[:name],
:error => 'ok',
}
end
private
def package_lists
Dir.entries('/var/opkg-lists/')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/aix.rb | lib/puppet/provider/package/aix.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/package'
Puppet::Type.type(:package).provide :aix, :parent => Puppet::Provider::Package do
desc "Installation from an AIX software directory, using the AIX `installp`
command. The `source` parameter is required for this provider, and should
be set to the absolute path (on the puppet agent machine) of a directory
containing one or more BFF package files.
The `installp` command will generate a table of contents file (named `.toc`)
in this directory, and the `name` parameter (or resource title) that you
specify for your `package` resource must match a package name that exists
in the `.toc` file.
Note that package downgrades are *not* supported; if your resource specifies
a specific version number and there is already a newer version of the package
installed on the machine, the resource will fail with an error message."
# The commands we are using on an AIX box are installed standard
# (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
commands :lslpp => "/usr/bin/lslpp",
:installp => "/usr/sbin/installp"
# AIX supports versionable packages with and without a NIM server
has_feature :versionable
confine 'os.name' => [:aix]
defaultfor 'os.name' => :aix
attr_accessor :latest_info
STATE_CODE = {
'A' => :applied,
'B' => :broken,
'C' => :committed,
'E' => :efix_locked,
'O' => :obsolete,
'?' => :inconsistent,
}.freeze
def self.srclistcmd(source)
[command(:installp), "-L", "-d", source]
end
def self.prefetch(packages)
raise Puppet::Error, _("The aix provider can only be used by root") if Process.euid != 0
return unless packages.detect { |_name, package| package.should(:ensure) == :latest }
sources = packages.collect { |_name, package| package[:source] }.uniq.compact
updates = {}
sources.each do |source|
execute(srclistcmd(source)).each_line do |line|
next unless line =~ /^[^#][^:]*:([^:]*):([^:]*)/
current = {}
current[:name] = Regexp.last_match(1)
current[:version] = Regexp.last_match(2)
current[:source] = source
if updates.key?(current[:name])
previous = updates[current[:name]]
updates[current[:name]] = current unless Puppet::Util::Package.versioncmp(previous[:version], current[:version]) == 1
else
updates[current[:name]] = current
end
end
end
packages.each do |name, package|
if updates.key?(name)
package.provider.latest_info = updates[name]
end
end
end
def uninstall
# Automatically process dependencies when installing/uninstalling
# with the -g option to installp.
installp "-gu", @resource[:name]
# installp will return an exit code of zero even if it didn't uninstall
# anything... so let's make sure it worked.
unless query().nil?
self.fail _("Failed to uninstall package '%{name}'") % { name: @resource[:name] }
end
end
def install(useversion = true)
source = @resource[:source]
unless source
self.fail _("A directory is required which will be used to find packages")
end
pkg = @resource[:name]
pkg += " #{@resource.should(:ensure)}" if (!@resource.should(:ensure).is_a? Symbol) and useversion
output = installp "-acgwXY", "-d", source, pkg
# If the package is superseded, it means we're trying to downgrade and we
# can't do that.
if output =~ /^#{Regexp.escape(@resource[:name])}\s+.*\s+Already superseded by.*$/
self.fail _("aix package provider is unable to downgrade packages")
end
pkg_info = query
if pkg_info && [:broken, :inconsistent].include?(pkg_info[:status])
self.fail _("Package '%{name}' is in a %{status} state and requires manual intervention") % { name: @resource[:name], status: pkg_info[:status] }
end
end
def self.pkglist(hash = {})
cmd = [command(:lslpp), "-qLc"]
name = hash[:pkgname]
if name
cmd << name
end
begin
list = execute(cmd).scan(/^[^#][^:]*:([^:]*):([^:]*):[^:]*:[^:]*:([^:])/).collect { |n, e, s|
e = :absent if [:broken, :inconsistent].include?(STATE_CODE[s])
{ :name => n, :ensure => e, :status => STATE_CODE[s], :provider => self.name }
}
rescue Puppet::ExecutionFailure => detail
if hash[:pkgname]
return nil
else
raise Puppet::Error, _("Could not list installed Packages: %{detail}") % { detail: detail }, detail.backtrace
end
end
if hash[:pkgname]
list.shift
else
list
end
end
def self.instances
pkglist.collect do |hash|
new(hash)
end
end
def latest
upd = latest_info
if upd.nil?
raise Puppet::DevError, _("Tried to get latest on a missing package") if properties[:ensure] == :absent
properties[:ensure]
else
(upd[:version]).to_s
end
end
def query
self.class.pkglist(:pkgname => @resource[:name])
end
def update
install(false)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/yum.rb | lib/puppet/provider/package/yum.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/util/package/version/rpm'
require_relative '../../../puppet/util/rpm_compare'
Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
# provides Rpm parsing and comparison
include Puppet::Util::RpmCompare
desc "Support via `yum`.
Using this provider's `uninstallable` feature will not remove dependent packages. To
remove dependent packages with this provider use the `purgeable` feature, but note this
feature is destructive and should be used with the utmost care.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to yum.
These options should be specified as an array where each element is either a string or a hash."
has_feature :install_options, :versionable, :virtual_packages, :install_only, :version_ranges
RPM_VERSION = Puppet::Util::Package::Version::Rpm
RPM_VERSION_RANGE = Puppet::Util::Package::Version::Range
commands :cmd => "yum", :rpm => "rpm"
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => :amazon
defaultfor 'os.family' => :redhat, 'os.release.major' => (4..7).to_a
def insync?(is)
return false if [:purged, :absent].include?(is)
return false if is.include?(self.class::MULTIVERSION_SEPARATOR) && !@resource[:install_only]
should = @resource[:ensure]
if should.is_a?(String)
begin
should_version = RPM_VERSION_RANGE.parse(should, RPM_VERSION)
if should_version.is_a?(RPM_VERSION_RANGE::Eq)
return super
end
rescue RPM_VERSION_RANGE::ValidationFailure, RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return super
end
is.split(self.class::MULTIVERSION_SEPARATOR).any? do |version|
is_version = RPM_VERSION.parse(version)
should_version.include?(is_version)
rescue RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{is} as a RPM version")
end
end
end
VERSION_REGEX = /^(?:(\d+):)?(\S+)-(\S+)$/
def self.prefetch(packages)
raise Puppet::Error, _("The yum provider can only be used as root") if Process.euid != 0
super
end
# Retrieve the latest package version information for a given package name
# and combination of repos to enable and disable.
#
# @note If multiple package versions are defined (such as in the case where a
# package is built for multiple architectures), the first package found
# will be used.
#
# @api private
# @param package [String] The name of the package to query
# @param disablerepo [Array<String>] A list of repositories to disable for this query
# @param enablerepo [Array<String>] A list of repositories to enable for this query
# @param disableexcludes [Array<String>] A list of repository excludes to disable for this query
# @return [Hash<Symbol, String>]
def self.latest_package_version(package, disablerepo, enablerepo, disableexcludes)
key = [disablerepo, enablerepo, disableexcludes]
@latest_versions ||= {}
if @latest_versions[key].nil?
@latest_versions[key] = check_updates(disablerepo, enablerepo, disableexcludes)
end
if @latest_versions[key][package]
@latest_versions[key][package].first
end
end
# Search for all installed packages that have newer versions, given a
# combination of repositories to enable and disable.
#
# @api private
# @param disablerepo [Array<String>] A list of repositories to disable for this query
# @param enablerepo [Array<String>] A list of repositories to enable for this query
# @param disableexcludes [Array<String>] A list of repository excludes to disable for this query
# @return [Hash<String, Array<Hash<String, String>>>] All packages that were
# found with a list of found versions for each package.
def self.check_updates(disablerepo, enablerepo, disableexcludes)
args = [command(:cmd), '-y', 'check-update']
args.concat(disablerepo.map { |repo| ["--disablerepo=#{repo}"] }.flatten)
args.concat(enablerepo.map { |repo| ["--enablerepo=#{repo}"] }.flatten)
args.concat(disableexcludes.map { |repo| ["--disableexcludes=#{repo}"] }.flatten)
output = Puppet::Util::Execution.execute(args, :failonfail => false, :combine => false)
updates = {}
case output.exitstatus
when 100
updates = parse_updates(output)
when 0
debug "#{command(:cmd)} check-update exited with 0; no package updates available."
else
warning _("Could not check for updates, '%{cmd} check-update' exited with %{status}") % { cmd: command(:cmd), status: output.exitstatus }
end
updates
end
def self.parse_updates(str)
# Strip off all content that contains Obsoleting, Security: or Update
body = str.partition(/^(Obsoleting|Security:|Update)/).first
updates = Hash.new { |h, k| h[k] = [] }
body.split(/^\s*\n/).each do |line|
line.split.each_slice(3) do |tuple|
next unless tuple[0].include?('.') && tuple[1] =~ VERSION_REGEX
hash = update_to_hash(*tuple[0..1])
# Create entries for both the package name without a version and a
# version since yum considers those as mostly interchangeable.
short_name = hash[:name]
long_name = "#{hash[:name]}.#{hash[:arch]}"
updates[short_name] << hash
updates[long_name] << hash
end
end
updates
end
def self.update_to_hash(pkgname, pkgversion)
# The pkgname string has two parts: name, and architecture. Architecture
# is the portion of the string following the last "." character. All
# characters preceding the final dot are the package name. Parse out
# these two pieces of component data.
name, _, arch = pkgname.rpartition('.')
if name.empty?
raise _("Failed to parse package name and architecture from '%{pkgname}'") % { pkgname: pkgname }
end
match = pkgversion.match(VERSION_REGEX)
epoch = match[1] || '0'
version = match[2]
release = match[3]
{
:name => name,
:epoch => epoch,
:version => version,
:release => release,
:arch => arch,
}
end
def self.clear
@latest_versions = nil
end
def self.error_level
'0'
end
def self.update_command
# In yum both `upgrade` and `update` can be used to update packages
# `yum upgrade` == `yum --obsoletes update`
# Quote the DNF docs:
# "Yum does this if its obsoletes config option is enabled but
# the behavior is not properly documented and can be harmful."
# So we'll stick with the safer option
# If a user wants to remove obsoletes, they can use { :install_options => '--obsoletes' }
# More detail here: https://bugzilla.redhat.com/show_bug.cgi?id=1096506
'update'
end
def best_version(should)
if should.is_a?(String)
begin
should_range = RPM_VERSION_RANGE.parse(should, RPM_VERSION)
if should_range.is_a?(RPM_VERSION_RANGE::Eq)
return should
end
rescue RPM_VERSION_RANGE::ValidationFailure, RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return should
end
versions = []
available_versions(@resource[:name], disablerepo, enablerepo, disableexcludes).each do |version|
rpm_version = RPM_VERSION.parse(version)
versions << rpm_version if should_range.include?(rpm_version)
rescue RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{version} as a RPM version")
end
version = versions.max if versions.any?
if version
version = version.to_s.sub(/^\d+:/, '')
return version
end
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should
end
end
def available_versions(package_name, disablerepo, enablerepo, disableexcludes)
args = [command(:cmd), 'list', package_name, '--showduplicates']
args.concat(disablerepo.map { |repo| ["--disablerepo=#{repo}"] }.flatten)
args.concat(enablerepo.map { |repo| ["--enablerepo=#{repo}"] }.flatten)
args.concat(disableexcludes.map { |repo| ["--disableexcludes=#{repo}"] }.flatten)
output = execute("#{args.compact.join(' ')} | sed -e '1,/Available Packages/ d' | awk '{print $2}'")
output.split("\n")
end
def install
wanted = @resource[:name]
update_command = self.class.update_command
# If not allowing virtual packages, do a query to ensure a real package exists
unless @resource.allow_virtual?
execute([command(:cmd), '-y', install_options, :list, wanted].compact)
end
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
operation = :install
case should
when :latest
current_package = query
if current_package && !current_package[:ensure].to_s.empty?
operation = update_command
debug "Ensuring latest, so using #{operation}"
else
debug "Ensuring latest, but package is absent, so using install"
operation = :install
end
should = nil
when true, :present, :installed
# if we have been given a source and we were not asked for a specific
# version feed it to yum directly
if @resource[:source]
wanted = @resource[:source]
debug "Installing directly from #{wanted}"
end
should = nil
when false, :absent
# pass
should = nil
else
if @resource[:source]
# An explicit source was supplied, which means we're ensuring a specific
# version, and also supplying the path to a package that supplies that
# version.
wanted = @resource[:source]
debug "Installing directly from #{wanted}"
else
# No explicit source was specified, so add the package version
should = best_version(should)
wanted += "-#{should}"
if wanted.scan(self.class::ARCH_REGEX)
debug "Detected Arch argument in package! - Moving arch to end of version string"
wanted.gsub!(/(.+)(#{self.class::ARCH_REGEX})(.+)/, '\1\3\2')
end
end
current_package = query
if current_package
if @resource[:install_only]
debug "Updating package #{@resource[:name]} from version #{current_package[:ensure]} to #{should} as install_only packages are never downgraded"
operation = update_command
elsif rpm_compare_evr(should, current_package[:ensure]) < 0
debug "Downgrading package #{@resource[:name]} from version #{current_package[:ensure]} to #{should}"
operation = :downgrade
elsif rpm_compare_evr(should, current_package[:ensure]) > 0
debug "Upgrading package #{@resource[:name]} from version #{current_package[:ensure]} to #{should}"
operation = update_command
end
end
end
command = [command(:cmd)] + ["-y", install_options, operation, wanted].compact
output = execute(command)
if output.to_s =~ /^No package #{wanted} available\.$/
raise Puppet::Error, _("Could not find package %{wanted}") % { wanted: wanted }
end
# If a version was specified, query again to see if it is a matching version
if should
is = query
raise Puppet::Error, _("Could not find package %{name}") % { name: name } unless is
version = is[:ensure]
# FIXME: Should we raise an exception even if should == :latest
# and yum updated us to a version other than @param_hash[:ensure] ?
raise Puppet::Error, _("Failed to update to version %{should}, got version %{version} instead") % { should: should, version: version } unless
insync?(version)
end
end
# What's the latest package version available?
def latest
upd = self.class.latest_package_version(@resource[:name], disablerepo, enablerepo, disableexcludes)
if upd.nil?
# Yum didn't find updates, pretend the current version is the latest
debug "Yum didn't find updates, current version (#{properties[:ensure]}) is the latest"
version = properties[:ensure]
raise Puppet::DevError, _("Tried to get latest on a missing package") if version == :absent || version == :purged
version
else
# FIXME: there could be more than one update for a package
# because of multiarch
"#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}"
end
end
def update
# Install in yum can be used for update, too
install
end
def purge
execute([command(:cmd), "-y", :remove, @resource[:name]])
end
private
def enablerepo
scan_options(resource[:install_options], '--enablerepo')
end
def disablerepo
scan_options(resource[:install_options], '--disablerepo')
end
def disableexcludes
scan_options(resource[:install_options], '--disableexcludes')
end
# Scan a structure that looks like the package type 'install_options'
# structure for all hashes that have a specific key.
#
# @api private
# @param options [Array<String | Hash>, nil] The options structure. If the
# options are nil an empty array will be returned.
# @param key [String] The key to look for in all contained hashes
# @return [Array<String>] All hash values with the given key.
def scan_options(options, key)
return [] unless options.is_a?(Enumerable)
values =
options.map do |repo|
value =
if repo.is_a?(String)
next unless repo.include?('=')
Hash[*repo.strip.split('=')] # make it a hash
else
repo
end
value[key]
end
values.compact.uniq
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pkgutil.rb | lib/puppet/provider/package/pkgutil.rb | # frozen_string_literal: true
# Packaging using Peter Bonivart's pkgutil program.
Puppet::Type.type(:package).provide :pkgutil, :parent => :sun, :source => :sun do
desc "Package management using Peter Bonivart's ``pkgutil`` command on Solaris."
pkgutil_bin = "pkgutil"
if FileTest.executable?("/opt/csw/bin/pkgutil")
pkgutil_bin = "/opt/csw/bin/pkgutil"
end
confine 'os.family' => :solaris
has_command(:pkguti, pkgutil_bin) do
environment :HOME => ENV.fetch('HOME', nil)
end
def self.healthcheck
unless Puppet::FileSystem.exist?("/var/opt/csw/pkgutil/admin")
Puppet.notice _("It is highly recommended you create '/var/opt/csw/pkgutil/admin'.")
Puppet.notice _("See /var/opt/csw/pkgutil")
end
correct_wgetopts = false
["/opt/csw/etc/pkgutil.conf", "/etc/opt/csw/pkgutil.conf"].each do |confpath|
File.open(confpath) do |conf|
conf.each_line { |line| correct_wgetopts = true if line =~ /^\s*wgetopts\s*=.*(-nv|-q|--no-verbose|--quiet)/ }
end
end
unless correct_wgetopts
Puppet.notice _("It is highly recommended that you set 'wgetopts=-nv' in your pkgutil.conf.")
end
end
def self.instances(hash = {})
healthcheck
# Use the available pkg list (-a) to work out aliases
aliases = {}
availlist.each do |pkg|
aliases[pkg[:name]] = pkg[:alias]
end
# The -c pkglist lists installed packages
pkginsts = []
output = pkguti(["-c"])
parse_pkglist(output).each do |pkg|
pkg.delete(:avail)
pkginsts << new(pkg)
# Create a second instance with the alias if it's different
pkgalias = aliases[pkg[:name]]
next unless pkgalias and pkg[:name] != pkgalias
apkg = pkg.dup
apkg[:name] = pkgalias
pkginsts << new(apkg)
end
pkginsts
end
# Turns a pkgutil -a listing into hashes with the common alias, full
# package name and available version
def self.availlist
output = pkguti ["-a"]
output.split("\n").filter_map do |line|
next if line =~ /^common\s+package/ # header of package list
next if noise?(line)
if line =~ /\s*(\S+)\s+(\S+)\s+(.*)/
{ :alias => Regexp.last_match(1), :name => Regexp.last_match(2), :avail => Regexp.last_match(3) }
else
Puppet.warning _("Cannot match %{line}") % { line: line }
end
end
end
# Turn our pkgutil -c listing into a hash for a single package.
def pkgsingle(resource)
# The --single option speeds up the execution, because it queries
# the package management system for one package only.
command = ["-c", "--single", resource[:name]]
self.class.parse_pkglist(run_pkgutil(resource, command), { :justme => resource[:name] })
end
# Turn our pkgutil -c listing into a bunch of hashes.
def self.parse_pkglist(output, hash = {})
output = output.split("\n")
if output[-1] == "Not in catalog"
Puppet.warning _("Package not in pkgutil catalog: %{package}") % { package: hash[:justme] }
return nil
end
list = output.filter_map do |line|
next if line =~ /installed\s+catalog/ # header of package list
next if noise?(line)
pkgsplit(line)
end
if hash[:justme]
# Single queries may have been for an alias so return the name requested
if list.any?
list[-1][:name] = hash[:justme]
list[-1]
end
else
list.reject! { |h| h[:ensure] == :absent }
list
end
end
# Identify common types of pkgutil noise as it downloads catalogs etc
def self.noise?(line)
return true if line =~ /^#/
return true if line =~ /^Checking integrity / # use_gpg
return true if line =~ /^gpg: / # gpg verification
return true if line =~ /^=+> / # catalog fetch
return true if line =~ /\d+:\d+:\d+ URL:/ # wget without -q
false
end
# Split the different lines into hashes.
def self.pkgsplit(line)
if line =~ /\s*(\S+)\s+(\S+)\s+(.*)/
hash = {}
hash[:name] = Regexp.last_match(1)
hash[:ensure] = if Regexp.last_match(2) == "notinst"
:absent
else
Regexp.last_match(2)
end
hash[:avail] = Regexp.last_match(3)
if hash[:avail] =~ /^SAME\s*$/
hash[:avail] = hash[:ensure]
end
# Use the name method, so it works with subclasses.
hash[:provider] = name
hash
else
Puppet.warning _("Cannot match %{line}") % { line: line }
nil
end
end
def run_pkgutil(resource, *args)
# Allow source to be one or more URLs pointing to a repository that all
# get passed to pkgutil via one or more -t options
if resource[:source]
sources = [resource[:source]].flatten
pkguti(*[sources.map { |src| ["-t", src] }, *args].flatten)
else
pkguti(*args.flatten)
end
end
def install
run_pkgutil @resource, "-y", "-i", @resource[:name]
end
# Retrieve the version from the current package file.
def latest
hash = pkgsingle(@resource)
hash[:avail] if hash
end
def query
hash = pkgsingle(@resource)
hash || { :ensure => :absent }
end
def update
run_pkgutil @resource, "-y", "-u", @resource[:name]
end
def uninstall
run_pkgutil @resource, "-y", "-r", @resource[:name]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/sunfreeware.rb | lib/puppet/provider/package/sunfreeware.rb | # frozen_string_literal: true
# At this point, it's an exact copy of the Blastwave stuff.
Puppet::Type.type(:package).provide :sunfreeware, :parent => :blastwave, :source => :sun do
desc "Package management using sunfreeware.com's `pkg-get` command on Solaris.
At this point, support is exactly the same as `blastwave` support and
has not actually been tested."
commands :pkgget => "pkg-get"
confine 'os.family' => :solaris
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/up2date.rb | lib/puppet/provider/package/up2date.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :up2date, :parent => :rpm, :source => :rpm do
desc "Support for Red Hat's proprietary `up2date` package update
mechanism."
commands :up2date => "/usr/sbin/up2date-nox"
defaultfor 'os.family' => :redhat, 'os.distro.release.full' => ["2.1", "3", "4"]
confine 'os.family' => :redhat
# Install a package using 'up2date'.
def install
up2date "-u", @resource[:name]
unless query
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name }
end
end
# What's the latest package version available?
def latest
# up2date can only get a list of *all* available packages?
output = up2date "--showall"
if output =~ /^#{Regexp.escape @resource[:name]}-(\d+.*)\.\w+/
Regexp.last_match(1)
else
# up2date didn't find updates, pretend the current
# version is the latest
@property_hash[:ensure]
end
end
def update
# Install in up2date can be used for update, too
install
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pacman.rb | lib/puppet/provider/package/pacman.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require 'set'
require 'uri'
Puppet::Type.type(:package).provide :pacman, :parent => Puppet::Provider::Package do
desc "Support for the Package Manager Utility (pacman) used in Archlinux.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pacman.
These options should be specified as an array where each element is either a string or a hash."
# If yaourt is installed, we can make use of it
def self.yaourt?
@yaourt ||= Puppet::FileSystem.exist?('/usr/bin/yaourt')
end
commands :pacman => "/usr/bin/pacman"
# Yaourt is a common AUR helper which, if installed, we can use to query the AUR
commands :yaourt => "/usr/bin/yaourt" if yaourt?
confine 'os.name' => [:archlinux, :manjarolinux, :artix]
defaultfor 'os.name' => [:archlinux, :manjarolinux, :artix]
has_feature :install_options
has_feature :uninstall_options
has_feature :upgradeable
has_feature :virtual_packages
has_feature :purgeable
# Checks if a given name is a group
def self.group?(name)
!pacman('--sync', '--groups', name).empty?
rescue Puppet::ExecutionFailure
# pacman returns an expected non-zero exit code when the name is not a group
false
end
# Install a package using 'pacman', or 'yaourt' if available.
# Installs quietly, without confirmation or progress bar, updates package
# list from servers defined in pacman.conf.
def install
if @resource[:source]
install_from_file
else
install_from_repo
end
unless query
fail(_("Could not find package '%{name}'") % { name: @resource[:name] })
end
end
# Fetch the list of packages and package groups that are currently installed on the system.
# Only package groups that are fully installed are included. If a group adds packages over time, it will not
# be considered as fully installed any more, and we would install the new packages on the next run.
# If a group removes packages over time, nothing will happen. This is intended.
def self.instances
instances = []
# Get the installed packages
installed_packages = get_installed_packages
installed_packages.sort_by { |k, _| k }.each do |package, version|
instances << new(to_resource_hash(package, version))
end
# Get the installed groups
get_installed_groups(installed_packages).each do |group, version|
instances << new(to_resource_hash(group, version))
end
instances
end
# returns a hash package => version of installed packages
def self.get_installed_packages
packages = {}
execpipe([command(:pacman), "--query"]) do |pipe|
# pacman -Q output is 'packagename version-rel'
regex = /^(\S+)\s(\S+)/
pipe.each_line do |line|
match = regex.match(line)
if match
packages[match.captures[0]] = match.captures[1]
else
warning(_("Failed to match line '%{line}'") % { line: line })
end
end
end
packages
rescue Puppet::ExecutionFailure
fail(_("Error getting installed packages"))
end
# returns a hash of group => version of installed groups
def self.get_installed_groups(installed_packages, filter = nil)
groups = {}
begin
# Build a hash of group name => list of packages
command = [command(:pacman), '--sync', '-gg']
command << filter if filter
execpipe(command) do |pipe|
pipe.each_line do |line|
name, package = line.split
packages = (groups[name] ||= [])
packages << package
end
end
# Remove any group that doesn't have all its packages installed
groups.delete_if do |_, packages|
!packages.all? { |package| installed_packages[package] }
end
# Replace the list of packages with a version string consisting of packages that make up the group
groups.each do |name, packages|
groups[name] = packages.sort.map { |package| "#{package} #{installed_packages[package]}" }.join ', '
end
rescue Puppet::ExecutionFailure
# pacman returns an expected non-zero exit code when the filter name is not a group
raise unless filter
end
groups
end
# Because Archlinux is a rolling release based distro, installing a package
# should always result in the newest release.
def update
# Install in pacman can be used for update, too
install
end
# We rescue the main check from Pacman with a check on the AUR using yaourt, if installed
def latest
resource_name = @resource[:name]
# If target is a group, construct the group version
return pacman("--sync", "--print", "--print-format", "%n %v", resource_name).lines.map(&:chomp).sort.join(', ') if self.class.group?(resource_name)
# Start by querying with pacman first
# If that fails, retry using yaourt against the AUR
pacman_check = true
begin
if pacman_check
output = pacman "--sync", "--print", "--print-format", "%v", resource_name
output.chomp
else
output = yaourt "-Qma", resource_name
output.split("\n").each do |line|
return line.split[1].chomp if line =~ /^aur/
end
end
rescue Puppet::ExecutionFailure
if pacman_check and self.class.yaourt?
pacman_check = false # now try the AUR
retry
else
raise
end
end
end
# Queries information for a package or package group
def query
installed_packages = self.class.get_installed_packages
resource_name = @resource[:name]
# Check for the resource being a group
version = self.class.get_installed_groups(installed_packages, resource_name)[resource_name]
if version
unless @resource.allow_virtual?
warning(_("%{resource_name} is a group, but allow_virtual is false.") % { resource_name: resource_name })
return nil
end
else
version = installed_packages[resource_name]
end
# Return nil if no package or group found
return nil unless version
self.class.to_resource_hash(resource_name, version)
end
def self.to_resource_hash(name, version)
{
:name => name,
:ensure => version,
:provider => self.name
}
end
# Removes a package from the system.
def uninstall
remove_package(false)
end
def purge
remove_package(true)
end
private
def remove_package(purge_configs = false)
resource_name = @resource[:name]
is_group = self.class.group?(resource_name)
fail(_("Refusing to uninstall package group %{resource_name}, because allow_virtual is false.") % { resource_name: resource_name }) if is_group && !@resource.allow_virtual?
cmd = %w[--noconfirm --noprogressbar]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << "--remove"
cmd << '--recursive' if is_group
cmd << '--nosave' if purge_configs
cmd << resource_name
if self.class.yaourt?
yaourt(*cmd)
else
pacman(*cmd)
end
end
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
def install_from_file
source = @resource[:source]
begin
source_uri = URI.parse source
rescue => detail
self.fail Puppet::Error, _("Invalid source '%{source}': %{detail}") % { source: source, detail: detail }, detail
end
source = case source_uri.scheme
when nil then source
when /https?/i then source
when /ftp/i then source
when /file/i then source_uri.path
when /puppet/i
fail _("puppet:// URL is not supported by pacman")
else
fail _("Source %{source} is not supported by pacman") % { source: source }
end
pacman "--noconfirm", "--noprogressbar", "--update", source
end
def install_from_repo
resource_name = @resource[:name]
# Refuse to install if not allowing virtual packages and the resource is a group
fail(_("Refusing to install package group %{resource_name}, because allow_virtual is false.") % { resource_name: resource_name }) if self.class.group?(resource_name) && !@resource.allow_virtual?
cmd = %w[--noconfirm --needed --noprogressbar]
cmd += install_options if @resource[:install_options]
cmd << "--sync" << resource_name
if self.class.yaourt?
yaourt(*cmd)
else
pacman(*cmd)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/dnf.rb | lib/puppet/provider/package/dnf.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :dnf, :parent => :yum do
desc "Support via `dnf`.
Using this provider's `uninstallable` feature will not remove dependent packages. To
remove dependent packages with this provider use the `purgeable` feature, but note this
feature is destructive and should be used with the utmost care.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to dnf.
These options should be specified as an array where each element is either
a string or a hash."
has_feature :install_options, :versionable, :virtual_packages, :install_only, :version_ranges
commands :cmd => "dnf", :rpm => "rpm"
# Note: this confine was borrowed from the Yum provider. The
# original purpose (from way back in 2007) was to make sure we
# never try to use RPM on a machine without it. We think this
# has probably become obsolete with the way `commands` work, so
# we should investigate removing it at some point.
#
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => :fedora
notdefaultfor 'os.name' => :fedora, 'os.release.major' => (19..21).to_a
defaultfor 'os.family' => :redhat
notdefaultfor 'os.family' => :redhat, 'os.release.major' => (4..7).to_a
defaultfor 'os.name' => :amazon, 'os.release.major' => ["2023"]
def self.update_command
# In DNF, update is deprecated for upgrade
'upgrade'
end
# The value to pass to DNF as its error output level.
# DNF differs from Yum slightly with regards to error outputting.
#
# @param None
# @return [String]
def self.error_level
'1'
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/openbsd.rb | lib/puppet/provider/package/openbsd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
# Packaging on OpenBSD. Doesn't work anywhere else that I know of.
Puppet::Type.type(:package).provide :openbsd, :parent => Puppet::Provider::Package do
desc "OpenBSD's form of `pkg_add` support.
This provider supports the `install_options` and `uninstall_options`
attributes, which allow command-line flags to be passed to pkg_add and pkg_delete.
These options should be specified as an array where each element is either a
string or a hash."
commands :pkginfo => "pkg_info",
:pkgadd => "pkg_add",
:pkgdelete => "pkg_delete"
defaultfor 'os.name' => :openbsd
confine 'os.name' => :openbsd
has_feature :versionable
has_feature :install_options
has_feature :uninstall_options
has_feature :upgradeable
has_feature :supports_flavors
def self.instances
packages = []
begin
execpipe(listcmd) do |process|
# our regex for matching pkg_info output
regex = /^(.*)-(\d[^-]*)-?([\w-]*)(.*)$/
fields = [:name, :ensure, :flavor]
hash = {}
# now turn each returned line into a package object
process.each_line { |line|
match = regex.match(line.split[0])
if match
fields.zip(match.captures) { |field, value|
hash[field] = value
}
hash[:provider] = name
packages << new(hash)
hash = {}
else
unless line =~ /Updating the pkgdb/
# Print a warning on lines we can't match, but move
# on, since it should be non-fatal
warning(_("Failed to match line %{line}") % { line: line })
end
end
}
end
packages
rescue Puppet::ExecutionFailure
nil
end
end
def self.listcmd
[command(:pkginfo), "-a"]
end
def latest
parse_pkgconf
if @resource[:source][-1, 1] == ::File::SEPARATOR
e_vars = { 'PKG_PATH' => @resource[:source] }
else
e_vars = {}
end
if @resource[:flavor]
query = "#{@resource[:name]}--#{@resource[:flavor]}"
else
query = @resource[:name]
end
output = Puppet::Util.withenv(e_vars) { pkginfo "-Q", query }
version = properties[:ensure]
if output.nil? or output.size == 0 or output =~ /Error from /
debug "Failed to query for #{resource[:name]}"
return version
else
# Remove all fuzzy matches first.
output = output.split.select { |p| p =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*)/ }.join
debug "pkg_info -Q for #{resource[:name]}: #{output}"
end
if output =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*) \(installed\)$/
debug "Package is already the latest available"
version
else
match = /^(.*)-(\d[^-]*)-?(\w*)$/.match(output)
debug "Latest available for #{resource[:name]}: #{match[2]}"
if version.to_sym == :absent || version.to_sym == :purged
return match[2]
end
vcmp = version.split('.').map(&:to_i) <=> match[2].split('.').map(&:to_i)
if vcmp > 0
# The locally installed package may actually be newer than what a mirror
# has. Log it at debug, but ignore it otherwise.
debug "Package #{resource[:name]} #{version} newer then available #{match[2]}"
version
else
match[2]
end
end
end
def update
install(true)
end
def parse_pkgconf
unless @resource[:source]
if Puppet::FileSystem.exist?("/etc/pkg.conf")
File.open("/etc/pkg.conf", "rb").readlines.each do |line|
matchdata = line.match(/^installpath\s*=\s*(.+)\s*$/i)
if matchdata
@resource[:source] = matchdata[1]
else
matchdata = line.match(/^installpath\s*\+=\s*(.+)\s*$/i)
if matchdata
if @resource[:source].nil?
@resource[:source] = matchdata[1]
else
@resource[:source] += ":" + matchdata[1]
end
end
end
end
unless @resource[:source]
raise Puppet::Error,
_("No valid installpath found in /etc/pkg.conf and no source was set")
end
else
raise Puppet::Error,
_("You must specify a package source or configure an installpath in /etc/pkg.conf")
end
end
end
def install(latest = false)
cmd = []
parse_pkgconf
if @resource[:source][-1, 1] == ::File::SEPARATOR
e_vars = { 'PKG_PATH' => @resource[:source] }
full_name = get_full_name(latest)
else
e_vars = {}
full_name = @resource[:source]
end
cmd << install_options
cmd << full_name
if latest
cmd.unshift('-rz')
end
Puppet::Util.withenv(e_vars) { pkgadd cmd.flatten.compact }
end
def get_full_name(latest = false)
# In case of a real update (i.e., the package already exists) then
# pkg_add(8) can handle the flavors. However, if we're actually
# installing with 'latest', we do need to handle the flavors. This is
# done so we can feed pkg_add(8) the full package name to install to
# prevent ambiguity.
if latest && resource[:flavor]
"#{resource[:name]}--#{resource[:flavor]}"
elsif latest
# Don't depend on get_version for updates.
@resource[:name]
else
# If :ensure contains a version, use that instead of looking it up.
# This allows for installing packages with the same stem, but multiple
# version such as openldap-server.
if @resource[:ensure].to_s =~ /(\d[^-]*)$/
use_version = @resource[:ensure]
else
use_version = get_version
end
[@resource[:name], use_version, @resource[:flavor]].join('-').gsub(/-+$/, '')
end
end
def get_version
execpipe([command(:pkginfo), "-I", @resource[:name]]) do |process|
# our regex for matching pkg_info output
regex = /^(.*)-(\d[^-]*)-?(\w*)(.*)$/
master_version = 0
version = -1
process.each_line do |line|
match = regex.match(line.split[0])
next unless match
# now we return the first version, unless ensure is latest
version = match.captures[1]
return version unless @resource[:ensure] == "latest"
master_version = version unless master_version > version
end
return master_version unless master_version == 0
return '' if version == -1
raise Puppet::Error, _("%{version} is not available for this package") % { version: version }
end
rescue Puppet::ExecutionFailure
nil
end
def query
# Search for the version info
if pkginfo(@resource[:name]) =~ /Information for (inst:)?#{@resource[:name]}-(\S+)/
{ :ensure => Regexp.last_match(2) }
else
nil
end
end
def install_options
join_options(resource[:install_options])
end
def uninstall_options
join_options(resource[:uninstall_options])
end
def uninstall
pkgdelete uninstall_options.flatten.compact, @resource[:name]
end
def purge
pkgdelete "-c", "-q", @resource[:name]
end
def flavor
@property_hash[:flavor]
end
def flavor=(value)
if flavor != @resource.should(:flavor)
uninstall
install
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/puppetserver_gem.rb | lib/puppet/provider/package/puppetserver_gem.rb | # frozen_string_literal: true
require 'English'
unless Puppet::Util::Platform.jruby_fips?
require 'rubygems/commands/list_command'
end
require 'stringio'
require 'uri'
# Ruby gems support.
Puppet::Type.type(:package).provide :puppetserver_gem, :parent => :gem do
desc "Puppet Server Ruby Gem support. If a URL is passed via `source`, then
that URL is appended to the list of remote gem repositories which by default
contains rubygems.org; To ensure that only the specified source is used also
pass `--clear-sources` in via `install_options`; if a source is present but
is not a valid URL, it will be interpreted as the path to a local gem file.
If source is not present at all, the gem will be installed from the default
gem repositories."
has_feature :versionable, :install_options, :uninstall_options
confine :feature => :hocon
# see SERVER-2578
confine :fips_enabled => false
# Define the default provider package command name, as the parent 'gem' provider is targetable.
# Required by Puppet::Provider::Package::Targetable::resource_or_provider_command
def self.provider_command
command(:puppetservercmd)
end
# The gem command uses HOME to locate a gemrc file.
# CommandDefiner in provider.rb will set failonfail, combine, and environment.
has_command(:puppetservercmd, '/opt/puppetlabs/bin/puppetserver') do
environment(HOME: ENV.fetch('HOME', nil))
end
def self.gemlist(options)
command_options = %w[gem list]
if options[:local]
command_options << '--local'
else
command_options << '--remote'
end
if options[:source]
command_options << '--source' << options[:source]
end
if options[:justme]
gem_regex = '\A' + options[:justme] + '\z'
command_options << gem_regex
end
if options[:local]
list = execute_rubygems_list_command(command_options)
else
begin
list = puppetservercmd(command_options)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not list gems: %{detail}") % { detail: detail }, detail.backtrace
end
end
# When `/tmp` is mounted `noexec`, `puppetserver gem list` will output:
# *** LOCAL GEMS ***
# causing gemsplit to output:
# Warning: Could not match *** LOCAL GEMS ***
gem_list = list
.lines
.select { |x| x =~ /^(\S+)\s+\((.+)\)/ }
.map { |set| gemsplit(set) }
if options[:justme]
gem_list.shift
else
gem_list
end
end
def install(useversion = true)
command_options = %w[gem install]
command_options += install_options if resource[:install_options]
command_options << '-v' << resource[:ensure] if (!resource[:ensure].is_a? Symbol) && useversion
command_options << '--no-document'
if resource[:source]
begin
uri = URI.parse(resource[:source])
rescue => detail
self.fail Puppet::Error, _("Invalid source '%{uri}': %{detail}") % { uri: uri, detail: detail }, detail
end
case uri.scheme
when nil
# no URI scheme => interpret the source as a local file
command_options << resource[:source]
when /file/i
command_options << uri.path
when 'puppet'
# we don't support puppet:// URLs (yet)
raise Puppet::Error, _('puppet:// URLs are not supported as gem sources')
else
# interpret it as a gem repository
command_options << '--source' << resource[:source].to_s << resource[:name]
end
else
command_options << resource[:name]
end
output = puppetservercmd(command_options)
# Apparently, some gem versions don't exit non-0 on failure.
self.fail _("Could not install: %{output}") % { output: output.chomp } if output.include?('ERROR')
end
def uninstall
command_options = %w[gem uninstall]
command_options << '--executables' << '--all' << resource[:name]
command_options += uninstall_options if resource[:uninstall_options]
output = puppetservercmd(command_options)
# Apparently, some gem versions don't exit non-0 on failure.
self.fail _("Could not uninstall: %{output}") % { output: output.chomp } if output.include?('ERROR')
end
private
# The puppetserver gem cli command is very slow, since it starts a JVM.
#
# Instead, for the list subcommand (which is executed with every puppet run),
# use the rubygems library from puppet ruby: setting GEM_HOME and GEM_PATH
# to the default values, or the values in the puppetserver configuration file.
#
# The rubygems library cannot access java platform gems,
# for example: json (1.8.3 java)
# but java platform gems should not be managed by this (or any) provider.
def self.execute_rubygems_list_command(command_options)
puppetserver_default_gem_home = '/opt/puppetlabs/server/data/puppetserver/jruby-gems'
puppetserver_default_vendored_jruby_gems = '/opt/puppetlabs/server/data/puppetserver/vendored-jruby-gems'
puppet_default_vendor_gems = '/opt/puppetlabs/puppet/lib/ruby/vendor_gems'
puppetserver_default_gem_path = [puppetserver_default_gem_home, puppetserver_default_vendored_jruby_gems, puppet_default_vendor_gems].join(':')
pe_puppetserver_conf_file = '/etc/puppetlabs/puppetserver/conf.d/pe-puppet-server.conf'
os_puppetserver_conf_file = '/etc/puppetlabs/puppetserver/puppetserver.conf'
puppetserver_conf_file = Puppet.runtime[:facter].value(:pe_server_version) ? pe_puppetserver_conf_file : os_puppetserver_conf_file
puppetserver_conf = Hocon.load(puppetserver_conf_file)
gem_env = {}
if puppetserver_conf.empty? || puppetserver_conf.key?('jruby-puppet') == false
gem_env['GEM_HOME'] = puppetserver_default_gem_home
gem_env['GEM_PATH'] = puppetserver_default_gem_path
else
gem_env['GEM_HOME'] = puppetserver_conf['jruby-puppet'].key?('gem-home') ? puppetserver_conf['jruby-puppet']['gem-home'] : puppetserver_default_gem_home
gem_env['GEM_PATH'] = puppetserver_conf['jruby-puppet'].key?('gem-path') ? puppetserver_conf['jruby-puppet']['gem-path'].join(':') : puppetserver_default_gem_path
end
gem_env['GEM_SPEC_CACHE'] = "/tmp/#{$PROCESS_ID}"
# Remove the 'gem' from the command_options
command_options.shift
gem_out = execute_gem_command(Puppet::Type::Package::ProviderPuppet_gem.provider_command, command_options, gem_env)
# There is no method exclude default gems from the local gem list,
# for example: psych (default: 2.2.2)
# but default gems should not be managed by this (or any) provider.
gem_list = gem_out.lines.reject { |gem| gem =~ / \(default: / }
gem_list.join("\n")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pkgng.rb | lib/puppet/provider/package/pkgng.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :pkgng, :parent => Puppet::Provider::Package do
desc "A PkgNG provider for FreeBSD and DragonFly."
commands :pkg => "/usr/local/sbin/pkg"
confine 'os.name' => [:freebsd, :dragonfly]
defaultfor 'os.name' => [:freebsd, :dragonfly]
has_feature :versionable
has_feature :upgradeable
has_feature :install_options
def self.get_query
pkg(['query', '-a', '%n %v %o'])
end
def self.get_resource_info(name)
pkg(['query', '%n %v %o', name])
end
def self.cached_version_list
# rubocop:disable Naming/MemoizedInstanceVariableName
@version_list ||= get_version_list
# rubocop:enable Naming/MemoizedInstanceVariableName
end
def self.get_version_list
@version_list = pkg(['version', '-voRL='])
end
def self.get_latest_version(origin)
latest_version = cached_version_list.lines.find { |l| l =~ /^#{origin} / }
if latest_version
_name, compare, status = latest_version.chomp.split(' ', 3)
if ['!', '?'].include?(compare)
return nil
end
latest_version = status.split(' ').last.split(')').first
return latest_version
end
nil
end
def self.parse_pkg_query_line(line)
name, version, origin = line.chomp.split(' ', 3)
latest_version = get_latest_version(origin) || version
{
:ensure => version,
:name => name,
:provider => self.name,
:origin => origin,
:version => version,
:latest => latest_version
}
end
def self.instances
packages = []
begin
info = get_query
get_version_list
unless info
return packages
end
info.lines.each do |line|
hash = parse_pkg_query_line(line)
packages << new(hash)
end
packages
rescue Puppet::ExecutionFailure
[]
end
end
def self.prefetch(resources)
packages = instances
resources.each_key do |name|
provider = packages.find { |p| p.name == name or p.origin == name }
if provider
resources[name].provider = provider
end
end
end
def repo_tag_from_urn(urn)
# extract repo tag from URN: urn:freebsd:repo:<tag>
match = /^urn:freebsd:repo:(.+)$/.match(urn)
raise ArgumentError urn.inspect unless match
match[1]
end
def install
source = resource[:source]
source = URI(source) unless source.nil?
# Ensure we handle the version
case resource[:ensure]
when true, false, Symbol
installname = resource[:name]
else
# If resource[:name] is actually an origin (e.g. 'www/curl' instead of
# just 'curl'), drop the category prefix. pkgng doesn't support version
# pinning with the origin syntax (pkg install curl-1.2.3 is valid, but
# pkg install www/curl-1.2.3 is not).
if resource[:name] =~ %r{/}
installname = resource[:name].split('/')[1] + '-' + resource[:ensure]
else
installname = resource[:name] + '-' + resource[:ensure]
end
end
if !source # install using default repo logic
args = ['install', '-qy']
elsif source.scheme == 'urn' # install from repo named in URN
tag = repo_tag_from_urn(source.to_s)
args = ['install', '-qy', '-r', tag]
else # add package located at URL
args = ['add', '-q']
installname = source.to_s
end
args += install_options if @resource[:install_options]
args << installname
pkg(args)
end
def uninstall
pkg(['remove', '-qy', resource[:name]])
end
def query
begin
output = self.class.get_resource_info(resource[:name])
rescue Puppet::ExecutionFailure
return nil
end
self.class.parse_pkg_query_line(output)
end
def version
@property_hash[:version]
end
def version=
pkg(['install', '-qfy', "#{resource[:name]}-#{resource[:version]}"])
end
# Upgrade to the latest version
def update
install
end
# Return the latest version of the package
def latest
debug "returning the latest #{@property_hash[:name].inspect} version #{@property_hash[:latest].inspect}"
@property_hash[:latest]
end
def origin
@property_hash[:origin]
end
def install_options
join_options(@resource[:install_options])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pkgin.rb | lib/puppet/provider/package/pkgin.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :pkgin, :parent => Puppet::Provider::Package do
desc "Package management using pkgin, a binary package manager for pkgsrc."
commands :pkgin => "pkgin"
defaultfor 'os.name' => [:smartos, :netbsd]
has_feature :installable, :uninstallable, :upgradeable, :versionable
def self.parse_pkgin_line(package)
# e.g.
# vim-7.2.446;Vim editor (vi clone) without GUI
match, name, version, status = *package.match(/([^\s;]+)-([^\s;]+)[;\s](=|>|<)?.+$/)
if match
{
:name => name,
:status => status,
:ensure => version
}
end
end
def self.prefetch(packages)
super
# Without -f, no fresh pkg_summary files are downloaded
pkgin("-yf", :update)
end
def self.instances
pkgin(:list).split("\n").map do |package|
new(parse_pkgin_line(package))
end
end
def query
packages = parse_pkgsearch_line
if packages.empty?
if @resource[:ensure] == :absent
notice _("declared as absent but unavailable %{file}:%{line}") % { file: @resource.file, line: resource.line }
return false
else
@resource.fail _("No candidate to be installed")
end
end
packages.first.update(:ensure => :absent)
end
def parse_pkgsearch_line
packages = pkgin(:search, resource[:name]).split("\n")
return [] if packages.length == 1
# Remove the last three lines of help text.
packages.slice!(-4, 4)
pkglist = packages.map { |line| self.class.parse_pkgin_line(line) }
pkglist.select { |package| resource[:name] == package[:name] }
end
def install
if @resource[:ensure].is_a?(String)
pkgin("-y", :install, "#{resource[:name]}-#{resource[:ensure]}")
else
pkgin("-y", :install, resource[:name])
end
end
def uninstall
pkgin("-y", :remove, resource[:name])
end
def latest
package = parse_pkgsearch_line.detect { |p| p[:status] == '<' }
return properties[:ensure] unless package
package[:ensure]
end
def update
pkgin("-y", :install, resource[:name])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/sun.rb | lib/puppet/provider/package/sun.rb | # frozen_string_literal: true
# Sun packaging.
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :sun, :parent => Puppet::Provider::Package do
desc "Sun's packaging system. Requires that you specify the source for
the packages you're managing.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pkgadd.
These options should be specified as an array where each element is either a string
or a hash."
commands :pkginfo => "/usr/bin/pkginfo",
:pkgadd => "/usr/sbin/pkgadd",
:pkgrm => "/usr/sbin/pkgrm"
confine 'os.family' => :solaris
defaultfor 'os.family' => :solaris
has_feature :install_options
self::Namemap = {
"PKGINST" => :name,
"CATEGORY" => :category,
"ARCH" => :platform,
"VERSION" => :ensure,
"BASEDIR" => :root,
"VENDOR" => :vendor,
"DESC" => :description,
}
def self.namemap(hash)
self::Namemap.keys.inject({}) do |hsh, k|
hsh.merge(self::Namemap[k] => hash[k])
end
end
def self.parse_pkginfo(out)
# collect all the lines with : in them, and separate them out by ^$
pkgs = []
pkg = {}
out.each_line do |line|
case line.chomp
when /^\s*$/
pkgs << pkg unless pkg.empty?
pkg = {}
when /^\s*([^:]+):\s+(.+)$/
pkg[Regexp.last_match(1)] = Regexp.last_match(2)
end
end
pkgs << pkg unless pkg.empty?
pkgs
end
def self.instances
parse_pkginfo(pkginfo('-l')).collect do |p|
hash = namemap(p)
hash[:provider] = :sun
new(hash)
end
end
# Get info on a package, optionally specifying a device.
def info2hash(device = nil)
args = ['-l']
args << '-d' << device if device
args << @resource[:name]
begin
pkgs = self.class.parse_pkginfo(pkginfo(*args))
errmsg = case pkgs.size
when 0
'No message'
when 1
pkgs[0]['ERROR']
end
return self.class.namemap(pkgs[0]) if errmsg.nil?
# according to commit 41356a7 some errors do not raise an exception
# so even though pkginfo passed, we have to check the actual output
raise Puppet::Error, _("Unable to get information about package %{name} because of: %{errmsg}") % { name: @resource[:name], errmsg: errmsg }
rescue Puppet::ExecutionFailure
{ :ensure => :absent }
end
end
# Retrieve the version from the current package file.
def latest
info2hash(@resource[:source])[:ensure]
end
def query
info2hash
end
# only looking for -G now
def install
# TRANSLATORS Sun refers to the company name, do not translate
raise Puppet::Error, _("Sun packages must specify a package source") unless @resource[:source]
options = {
:adminfile => @resource[:adminfile],
:responsefile => @resource[:responsefile],
:source => @resource[:source],
:cmd_options => @resource[:install_options]
}
pkgadd prepare_cmd(options)
end
def uninstall
pkgrm prepare_cmd(:adminfile => @resource[:adminfile])
end
# Remove the old package, and install the new one. This will probably
# often fail.
def update
uninstall if (@property_hash[:ensure] || info2hash[:ensure]) != :absent
install
end
def prepare_cmd(opt)
[if_have_value('-a', opt[:adminfile]),
if_have_value('-r', opt[:responsefile]),
if_have_value('-d', opt[:source]),
opt[:cmd_options] || [],
['-n', @resource[:name]]].flatten
end
def if_have_value(prefix, value)
if value
[prefix, value]
else
[]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/blastwave.rb | lib/puppet/provider/package/blastwave.rb | # frozen_string_literal: true
# Packaging using Blastwave's pkg-get program.
Puppet::Type.type(:package).provide :blastwave, :parent => :sun, :source => :sun do
desc "Package management using Blastwave.org's `pkg-get` command on Solaris."
pkgget = "pkg-get"
pkgget = "/opt/csw/bin/pkg-get" if FileTest.executable?("/opt/csw/bin/pkg-get")
confine 'os.family' => :solaris
commands :pkgget => pkgget
def pkgget_with_cat(*args)
Puppet::Util.withenv(:PAGER => "/usr/bin/cat") { pkgget(*args) }
end
def self.extended(mod)
unless command(:pkgget) != "pkg-get"
raise Puppet::Error,
_("The pkg-get command is missing; blastwave packaging unavailable")
end
unless Puppet::FileSystem.exist?("/var/pkg-get/admin")
Puppet.notice _("It is highly recommended you create '/var/pkg-get/admin'.")
Puppet.notice _("See /var/pkg-get/admin-fullauto")
end
end
def self.instances(hash = {})
blastlist(hash).collect do |bhash|
bhash.delete(:avail)
new(bhash)
end
end
# Turn our blastwave listing into a bunch of hashes.
def self.blastlist(hash)
command = ["-c"]
command << hash[:justme] if hash[:justme]
output = Puppet::Util.withenv(:PAGER => "/usr/bin/cat") { pkgget command }
list = output.split("\n").filter_map do |line|
next if line =~ /^#/
next if line =~ /^WARNING/
next if line =~ /localrev\s+remoterev/
blastsplit(line)
end
if hash[:justme]
list[0]
else
list.reject! { |h|
h[:ensure] == :absent
}
list
end
end
# Split the different lines into hashes.
def self.blastsplit(line)
if line =~ /\s*(\S+)\s+((\[Not installed\])|(\S+))\s+(\S+)/
hash = {}
hash[:name] = Regexp.last_match(1)
hash[:ensure] = if Regexp.last_match(2) == "[Not installed]"
:absent
else
Regexp.last_match(2)
end
hash[:avail] = Regexp.last_match(5)
hash[:avail] = hash[:ensure] if hash[:avail] == "SAME"
# Use the name method, so it works with subclasses.
hash[:provider] = name
hash
else
Puppet.warning _("Cannot match %{line}") % { line: line }
nil
end
end
def install
pkgget_with_cat "-f", :install, @resource[:name]
end
# Retrieve the version from the current package file.
def latest
hash = self.class.blastlist(:justme => @resource[:name])
hash[:avail]
end
def query
hash = self.class.blastlist(:justme => @resource[:name])
hash || { :ensure => :absent }
end
# Remove the old package, and install the new one
def update
pkgget_with_cat "-f", :upgrade, @resource[:name]
end
def uninstall
pkgget_with_cat "-f", :remove, @resource[:name]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/appdmg.rb | lib/puppet/provider/package/appdmg.rb | # frozen_string_literal: true
# Jeff McCune <mccune.jeff@gmail.com>
# Changed to app.dmg by: Udo Waechter <root@zoide.net>
# Mac OS X Package Installer which handles application (.app)
# bundles inside an Apple Disk Image.
#
# Motivation: DMG files provide a true HFS file system
# and are easier to manage.
#
# Note: the 'apple' Provider checks for the package name
# in /L/Receipts. Since we possibly install multiple apps from
# a single source, we treat the source .app.dmg file as the package name.
# As a result, we store installed .app.dmg file names
# in /var/db/.puppet_appdmg_installed_<name>
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/plist' if Puppet.features.cfpropertylist?
Puppet::Type.type(:package).provide(:appdmg, :parent => Puppet::Provider::Package) do
desc "Package management which copies application bundles to a target."
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
commands :hdiutil => "/usr/bin/hdiutil"
commands :curl => "/usr/bin/curl"
commands :ditto => "/usr/bin/ditto"
# JJM We store a cookie for each installed .app.dmg in /var/db
def self.instances_by_name
Dir.entries("/var/db").find_all { |f|
f =~ /^\.puppet_appdmg_installed_/
}.collect do |f|
name = f.sub(/^\.puppet_appdmg_installed_/, '')
yield name if block_given?
name
end
end
def self.instances
instances_by_name.collect do |name|
new(:name => name, :provider => :appdmg, :ensure => :installed)
end
end
def self.installapp(source, name, orig_source)
appname = File.basename(source);
ditto "--rsrc", source, "/Applications/#{appname}"
Puppet::FileSystem.open("/var/db/.puppet_appdmg_installed_#{name}", nil, "w:UTF-8") do |t|
t.print "name: '#{name}'\n"
t.print "source: '#{orig_source}'\n"
end
end
def self.installpkgdmg(source, name)
require 'open-uri'
cached_source = source
tmpdir = Dir.mktmpdir
begin
if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source
cached_source = File.join(tmpdir, name)
begin
curl "-o", cached_source, "-C", "-", "-L", "-s", "--url", source
Puppet.debug "Success: curl transferred [#{name}]"
rescue Puppet::ExecutionFailure
Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
cached_source = source
end
end
File.open(cached_source) do |dmg|
xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path
ptable = Puppet::Util::Plist.parse_plist(xml_str)
# JJM Filter out all mount-paths into a single array, discard the rest.
mounts = ptable['system-entities'].collect { |entity|
entity['mount-point']
}.select { |mountloc|; mountloc }
begin
found_app = false
mounts.each do |fspath|
Dir.entries(fspath).select { |f|
f =~ /\.app$/i
}.each do |pkg|
found_app = true
installapp("#{fspath}/#{pkg}", name, source)
end
end
Puppet.debug "Unable to find .app in .appdmg. #{name} will not be installed." unless found_app
ensure
hdiutil "eject", mounts[0]
end
end
ensure
FileUtils.remove_entry_secure(tmpdir, true)
end
end
def query
Puppet::FileSystem.exist?("/var/db/.puppet_appdmg_installed_#{@resource[:name]}") ? { :name => @resource[:name], :ensure => :present } : nil
end
def install
source = @resource[:source]
unless source
self.fail _("Mac OS X PKG DMGs must specify a package source.")
end
name = @resource[:name]
unless name
self.fail _("Mac OS X PKG DMGs must specify a package name.")
end
self.class.installpkgdmg(source, name)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/apple.rb | lib/puppet/provider/package/apple.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
# OS X Packaging sucks. We can install packages, but that's about it.
Puppet::Type.type(:package).provide :apple, :parent => Puppet::Provider::Package do
desc "Package management based on OS X's built-in packaging system. This is
essentially the simplest and least functional package system in existence --
it only supports installation; no deletion or upgrades. The provider will
automatically add the `.pkg` extension, so leave that off when specifying
the package name."
confine 'os.name' => :darwin
commands :installer => "/usr/sbin/installer"
def self.instances
instance_by_name.collect do |name|
new(
:name => name,
:provider => :apple,
:ensure => :installed
)
end
end
def self.instance_by_name
Dir.entries("/Library/Receipts").find_all { |f|
f =~ /\.pkg$/
}.collect { |f|
name = f.sub(/\.pkg/, '')
yield name if block_given?
name
}
end
def query
Puppet::FileSystem.exist?("/Library/Receipts/#{@resource[:name]}.pkg") ? { :name => @resource[:name], :ensure => :present } : nil
end
def install
source = @resource[:source]
unless source
self.fail _("Mac OS X packages must specify a package source")
end
installer "-pkg", source, "-target", "/"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pip3.rb | lib/puppet/provider/package/pip3.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip3` package management frontend.
# <http://pip.pypa.io/>
Puppet::Type.type(:package).provide :pip3,
:parent => :pip do
desc "Python packages via `pip3`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip3.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :install_options, :targetable
def self.cmd
["pip3"]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pip.rb | lib/puppet/provider/package/pip.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip` package management frontend.
# <http://pip.pypa.io/>
require_relative '../../../puppet/util/package/version/pip'
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/provider/package_targetable'
Puppet::Type.type(:package).provide :pip, :parent => ::Puppet::Provider::Package::Targetable do
desc "Python packages via `pip`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :version_ranges, :install_options, :targetable
PIP_VERSION = Puppet::Util::Package::Version::Pip
PIP_VERSION_RANGE = Puppet::Util::Package::Version::Range
# Override the specificity method to return 1 if pip is not set as default provider
def self.specificity
match = default_match
length = match ? match.length : 0
return 1 if length == 0
super
end
# Define the default provider package command name when the provider is targetable.
# Required by Puppet::Provider::Package::Targetable::resource_or_provider_command
def self.provider_command
# Ensure pip can upgrade pip, which usually puts pip into a new path /usr/local/bin/pip (compared to /usr/bin/pip)
cmd.map { |c| which(c) }.find { |c| !c.nil? }
end
def self.cmd
if Puppet::Util::Platform.windows?
["pip.exe"]
else
%w[pip pip-python pip2 pip-2]
end
end
def self.pip_version(command)
version = nil
execpipe [quote(command), '--version'] do |process|
process.collect do |line|
md = line.strip.match(/^pip (\d+\.\d+\.?\d*).*$/)
if md
version = md[1]
break
end
end
end
raise Puppet::Error, _("Cannot resolve pip version") unless version
version
end
# Return an array of structured information about every installed package
# that's managed by `pip` or an empty array if `pip` is not available.
def self.instances(target_command = nil)
if target_command
command = target_command
validate_command(command)
else
command = provider_command
end
packages = []
return packages unless command
command_options = ['freeze']
command_version = pip_version(command)
if compare_pip_versions(command_version, '8.1.0') >= 0
command_options << '--all'
end
execpipe [quote(command), command_options] do |process|
process.collect do |line|
pkg = parse(line)
next unless pkg
pkg[:command] = command
packages << new(pkg)
end
end
# Pip can also upgrade pip, but it's not listed in freeze so need to special case it
# Pip list would also show pip installed version, but "pip list" doesn't exist for older versions of pip (E.G v1.0)
# Not needed when "pip freeze --all" is available.
if compare_pip_versions(command_version, '8.1.0') == -1
packages << new({ :ensure => command_version, :name => File.basename(command), :provider => name, :command => command })
end
packages
end
# Parse lines of output from `pip freeze`, which are structured as:
# _package_==_version_ or _package_===_version_
# or _package_ @ someURL@_version_
def self.parse(line)
if line.chomp =~ /^([^=]+)===?([^=]+)$/
{ :ensure => Regexp.last_match(2), :name => Regexp.last_match(1), :provider => name }
elsif line.chomp =~ /^([^@]+) @ [^@]+@(.+)$/
{ :ensure => Regexp.last_match(2), :name => Regexp.last_match(1), :provider => name }
end
end
# Return structured information about a particular package or `nil`
# if the package is not installed or `pip` itself is not available.
def query
command = resource_or_provider_command
self.class.validate_command(command)
self.class.instances(command).each do |pkg|
return pkg.properties if @resource[:name].casecmp(pkg.name).zero?
end
nil
end
# Return latest version available for current package
def latest
command = resource_or_provider_command
self.class.validate_command(command)
command_version = self.class.pip_version(command)
if self.class.compare_pip_versions(command_version, '1.5.4') == -1
available_versions_with_old_pip.last
else
available_versions_with_new_pip(command_version).last
end
end
def self.compare_pip_versions(x, y)
Puppet::Util::Package::Version::Pip.compare(x, y)
rescue PIP_VERSION::ValidationFailure => ex
Puppet.debug("Cannot compare #{x} and #{y}. #{ex.message} Falling through default comparison mechanism.")
Puppet::Util::Package.versioncmp(x, y)
end
# Use pip CLI to look up versions from PyPI repositories,
# honoring local pip config such as custom repositories.
def available_versions
command = resource_or_provider_command
self.class.validate_command(command)
command_version = self.class.pip_version(command)
if self.class.compare_pip_versions(command_version, '1.5.4') == -1
available_versions_with_old_pip
else
available_versions_with_new_pip(command_version)
end
end
def available_versions_with_new_pip(command_version)
command = resource_or_provider_command
self.class.validate_command(command)
command_and_options = [self.class.quote(command), 'install', "#{@resource[:name]}==9!0dev0+x"]
extra_arg = list_extra_flags(command_version)
command_and_options << extra_arg if extra_arg
command_and_options << install_options if @resource[:install_options]
execpipe command_and_options do |process|
process.collect do |line|
# PIP OUTPUT: Could not find a version that satisfies the requirement example==versionplease (from versions: 1.2.3, 4.5.6)
next unless line =~ /from versions: (.+)\)/
versionList = Regexp.last_match(1).split(', ').sort do |x, y|
self.class.compare_pip_versions(x, y)
end
return versionList
end
end
[]
end
def available_versions_with_old_pip
command = resource_or_provider_command
self.class.validate_command(command)
Dir.mktmpdir("puppet_pip") do |dir|
command_and_options = [self.class.quote(command), 'install', (@resource[:name]).to_s, '-d', dir.to_s, '-v']
command_and_options << install_options if @resource[:install_options]
execpipe command_and_options do |process|
process.collect do |line|
# PIP OUTPUT: Using version 0.10.1 (newest of versions: 1.2.3, 4.5.6)
next unless line =~ /Using version .+? \(newest of versions: (.+?)\)/
versionList = Regexp.last_match(1).split(', ').sort do |x, y|
self.class.compare_pip_versions(x, y)
end
return versionList
end
end
return []
end
end
# Finds the most suitable version available in a given range
def best_version(should_range)
included_available_versions = []
available_versions.each do |version|
version = PIP_VERSION.parse(version)
included_available_versions.push(version) if should_range.include?(version)
end
included_available_versions.sort!
return included_available_versions.last unless included_available_versions.empty?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should_range
end
def get_install_command_options
should = @resource[:ensure]
command_options = %w[install -q]
command_options += install_options if @resource[:install_options]
if @resource[:source]
if should.is_a?(String)
command_options << "#{@resource[:source]}@#{should}#egg=#{@resource[:name]}"
else
command_options << "#{@resource[:source]}#egg=#{@resource[:name]}"
end
return command_options
end
if should == :latest
command_options << "--upgrade" << @resource[:name]
return command_options
end
unless should.is_a?(String)
command_options << @resource[:name]
return command_options
end
begin
should_range = PIP_VERSION_RANGE.parse(should, PIP_VERSION)
rescue PIP_VERSION_RANGE::ValidationFailure, PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a pip version range, falling through.")
command_options << "#{@resource[:name]}==#{should}"
return command_options
end
if should_range.is_a?(PIP_VERSION_RANGE::Eq)
command_options << "#{@resource[:name]}==#{should}"
return command_options
end
should = best_version(should_range)
if should == should_range
# when no suitable version for the given range was found, let pip handle
if should.is_a?(PIP_VERSION_RANGE::MinMax)
command_options << "#{@resource[:name]} #{should.split.join(',')}"
else
command_options << "#{@resource[:name]} #{should}"
end
else
command_options << "#{@resource[:name]}==#{should}"
end
command_options
end
# Install a package. The ensure parameter may specify installed,
# latest, a version number, or, in conjunction with the source
# parameter, an SCM revision. In that case, the source parameter
# gives the fully-qualified URL to the repository.
def install
command = resource_or_provider_command
self.class.validate_command(command)
command_options = get_install_command_options
execute([command, command_options])
end
# Uninstall a package. Uninstall won't work reliably on Debian/Ubuntu unless this issue gets fixed.
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=562544
def uninstall
command = resource_or_provider_command
self.class.validate_command(command)
command_options = ["uninstall", "-y", "-q", @resource[:name]]
execute([command, command_options])
end
def update
install
end
def install_options
join_options(@resource[:install_options])
end
def insync?(is)
return false unless is && is != :absent
begin
should = @resource[:ensure]
should_range = PIP_VERSION_RANGE.parse(should, PIP_VERSION)
rescue PIP_VERSION_RANGE::ValidationFailure, PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a pip version range")
return false
end
begin
is_version = PIP_VERSION.parse(is)
rescue PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{is} as a pip version")
return false
end
should_range.include?(is_version)
end
# Quoting is required if the path to the pip command contains spaces.
# Required for execpipe() but not execute(), as execute() already does this.
def self.quote(path)
if path.include?(" ")
"\"#{path}\""
else
path
end
end
private
def list_extra_flags(command_version)
klass = self.class
if klass.compare_pip_versions(command_version, '20.2.4') == 1 &&
klass.compare_pip_versions(command_version, '21.1') == -1
'--use-deprecated=legacy-resolver'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/portupgrade.rb | lib/puppet/provider/package/portupgrade.rb | # frozen_string_literal: true
# Whole new package, so include pack stuff
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :portupgrade, :parent => Puppet::Provider::Package do
include Puppet::Util::Execution
desc "Support for FreeBSD's ports using the portupgrade ports management software.
Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
for the portupgrade port."
## has_features is usually autodetected based on defs below.
# has_features :installable, :uninstallable, :upgradeable
commands :portupgrade => "/usr/local/sbin/portupgrade",
:portinstall => "/usr/local/sbin/portinstall",
:portversion => "/usr/local/sbin/portversion",
:portuninstall => "/usr/local/sbin/pkg_deinstall",
:portinfo => "/usr/sbin/pkg_info"
## Activate this only once approved by someone important.
# defaultfor 'os.name' => :freebsd
# Remove unwanted environment variables.
%w[INTERACTIVE UNAME].each do |var|
if ENV.include?(var)
ENV.delete(var)
end
end
######## instances sub command (builds the installed packages list)
def self.instances
Puppet.debug "portupgrade.rb Building packages list from installed ports"
# regex to match output from pkg_info
regex = /^(\S+)-([^-\s]+):(\S+)$/
# Corresponding field names
fields = [:portname, :ensure, :portorigin]
# define Temporary hash used, packages array of hashes
hash = Hash.new
packages = []
# exec command
cmdline = ["-aoQ"]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# split output and match it and populate temp hash
output.split("\n").each { |data|
# reset hash to nil for each line
hash.clear
match = regex.match(data)
if match
# Output matched regex
fields.zip(match.captures) { |field, value|
hash[field] = value
}
# populate the actual :name field from the :portorigin
# Set :provider to this object name
hash[:name] = hash[:portorigin]
hash[:provider] = name
# Add to the full packages listing
packages << new(hash)
else
# unrecognised output from pkg_info
Puppet.debug "portupgrade.Instances() - unable to match output: #{data}"
end
}
# return the packages array of hashes
packages
end
######## Installation sub command
def install
Puppet.debug "portupgrade.install() - Installation call on #{@resource[:name]}"
# -M: yes, we're a batch, so don't ask any questions
cmdline = ["-M BATCH=yes", @resource[:name]]
# FIXME: it's possible that portinstall prompts for data so locks up.
begin
output = portinstall(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /\*\* No such /
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] }
end
# No return code required, so do nil to be clean
nil
end
######## Latest subcommand (returns the latest version available, or current version if installed is latest)
def latest
Puppet.debug "portupgrade.latest() - Latest check called on #{@resource[:name]}"
# search for latest version available, or return current version.
# cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
# or "** No matching package found: <portname>"
cmdline = ["-v", @resource[:name]]
begin
output = portversion(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# Check: output format.
if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
installedversion = Regexp.last_match(1)
comparison = Regexp.last_match(2)
otherdata = Regexp.last_match(3)
# Only return a new version number when it's clear that there is a new version
# all others return the current version so no unexpected 'upgrades' occur.
case comparison
when "=", ">"
Puppet.debug "portupgrade.latest() - Installed package is latest (#{installedversion})"
installedversion
when "<"
# "portpkg-1.7_5 < needs updating (port has 1.14)"
# "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
if otherdata =~ /\(port has (\S+)\)/
newversion = Regexp.last_match(1)
Puppet.debug "portupgrade.latest() - Installed version needs updating to (#{newversion})"
newversion
else
Puppet.debug "portupgrade.latest() - Unable to determine new version from (#{otherdata})"
installedversion
end
when "?", "!", "#"
Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (#{output})"
installedversion
else
Puppet.debug "portupgrade.latest() - Unknown code from portversion output (#{output})"
installedversion
end
elsif output =~ /^\*\* No matching package /
# error: output not parsed correctly, error out with nil.
# Seriously - this section should never be called in a perfect world.
# as verification that the port is installed has already happened in query.
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] }
else
# Any other error (dump output to log)
raise Puppet::ExecutionFailure, _("Unexpected output from portversion: %{output}") % { output: output }
end
end
###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
# Used to make sure the package is installed
def query
Puppet.debug "portupgrade.query() - Called on #{@resource[:name]}"
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# Check: if output isn't in the right format, return nil
if output =~ /^(\S+)-([^-\s]+)/
# Fill in the details
hash = Hash.new
hash[:portorigin] = name
hash[:portname] = Regexp.last_match(1)
hash[:ensure] = Regexp.last_match(2)
# If more details are required, then we can do another pkg_info
# query here and parse out that output and add to the hash
# return the hash to the caller
hash
else
Puppet.debug "portupgrade.query() - package (#{@resource[:name]}) not installed"
nil
end
end
####### Uninstall command
def uninstall
Puppet.debug "portupgrade.uninstall() - called on #{@resource[:name]}"
# Get full package name from port origin to uninstall with
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /^(\S+)/
# output matches, so uninstall it
portuninstall Regexp.last_match(1)
end
end
######## Update/upgrade command
def update
Puppet.debug "portupgrade.update() - called on (#{@resource[:name]})"
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /^(\S+)/
# output matches, so upgrade the software
cmdline = ["-M BATCH=yes", Regexp.last_match(1)]
begin
output = portupgrade(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
end
end
## EOF
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/xbps.rb | lib/puppet/provider/package/xbps.rb | # frozen_string_literal: true
require_relative "../../../puppet/provider/package"
Puppet::Type.type(:package).provide :xbps, :parent => Puppet::Provider::Package do
desc "Support for the Package Manager Utility (xbps) used in VoidLinux.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to xbps-install.
These options should be specified as an array where each element is either a string or a hash."
commands :xbps_install => "/usr/bin/xbps-install"
commands :xbps_remove => "/usr/bin/xbps-remove"
commands :xbps_query => "/usr/bin/xbps-query"
commands :xbps_pkgdb => "/usr/bin/xbps-pkgdb"
confine 'os.name' => :void
defaultfor 'os.name' => :void
has_feature :install_options, :uninstall_options, :upgradeable, :holdable, :virtual_packages
def self.defaultto_allow_virtual
false
end
# Fetch the list of packages that are currently installed on the system.
def self.instances
packages = []
execpipe([command(:xbps_query), "-l"]) do |pipe|
# xbps-query -l output is 'ii package-name-version desc'
regex = /^\S+\s(\S+)-(\S+)\s+\S+/
pipe.each_line do |line|
match = regex.match(line.chomp)
if match
packages << new({ name: match.captures[0], ensure: match.captures[1], provider: name })
else
warning(_("Failed to match line '%{line}'") % { line: line })
end
end
end
packages
rescue Puppet::ExecutionFailure
fail(_("Error getting installed packages"))
end
# Install a package quietly (without confirmation or progress bar) using 'xbps-install'.
def install
resource_name = @resource[:name]
resource_source = @resource[:source]
cmd = %w[-S -y]
cmd += install_options if @resource[:install_options]
cmd << "--repository=#{resource_source}" if resource_source
cmd << resource_name
unhold if properties[:mark] == :hold
begin
xbps_install(*cmd)
ensure
hold if @resource[:mark] == :hold
end
end
# Because Voidlinux is a rolling release based distro, installing a package
# should always result in the newest release.
def update
install
end
# Removes a package from the system.
def uninstall
resource_name = @resource[:name]
cmd = %w[-R -y]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << resource_name
xbps_remove(*cmd)
end
# The latest version of a given package
def latest
query&.[] :ensure
end
# Queries information for a package
def query
resource_name = @resource[:name]
installed_packages = self.class.instances
installed_packages.each do |pkg|
return pkg.properties if @resource[:name].casecmp(pkg.name).zero?
end
return nil unless @resource.allow_virtual?
# Search for virtual package
output = xbps_query("-Rs", resource_name).chomp
# xbps-query -Rs output is '[*] package-name-version description'
regex = /^\[\*\]+\s(\S+)-(\S+)\s+\S+/
match = regex.match(output)
return nil unless match
{ name: match.captures[0], ensure: match.captures[1], provider: self.class.name }
end
# Puts a package on hold, so it doesn't update by itself on system update
def hold
xbps_pkgdb("-m", "hold", @resource[:name])
end
# Puts a package out of hold
def unhold
xbps_pkgdb("-m", "unhold", @resource[:name])
end
private
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/dnfmodule.rb | lib/puppet/provider/package/dnfmodule.rb | # frozen_string_literal: true
# dnfmodule - A puppet package provider for DNF modules
#
# Installing a module:
# package { 'postgresql':
# provider => 'dnfmodule',
# ensure => '9.6', # install a specific stream
# flavor => 'client', # install a specific profile
# }
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :dnfmodule, :parent => :dnf do
has_feature :installable, :uninstallable, :versionable, :supports_flavors, :disableable
# has_feature :upgradeable
# it's not (yet) feasible to make this upgradeable since module streams don't
# always have matching version types (i.e. idm has streams DL1 and client,
# other modules have semver streams, others have string streams... we cannot
# programatically determine a latest version for ensure => 'latest'
commands :dnf => '/usr/bin/dnf'
def self.current_version
@current_version ||= dnf('--version').split.first
end
def self.prefetch(packages)
if Puppet::Util::Package.versioncmp(current_version, '3.0.1') < 0
raise Puppet::Error, _("Modules are not supported on DNF versions lower than 3.0.1")
end
super
end
def self.instances
packages = []
cmd = "#{command(:dnf)} module list -y"
execute(cmd).each_line do |line|
# select only lines with actual packages since DNF clutters the output
next unless line =~ /\[[eix]\][, ]/
line.gsub!(/\[d\]/, '') # we don't care about the default flag
flavor = if line.include?('[i]')
line.split('[i]').first.split.last
else
:absent
end
packages << new(
name: line.split[0],
ensure: if line.include?('[x]')
:disabled
else
line.split[1]
end,
flavor: flavor,
provider: name
)
end
packages
end
def query
pkg = self.class.instances.find do |package|
@resource[:name] == package.name
end
pkg ? pkg.properties : nil
end
# to install specific streams and profiles:
# $ dnf module install module-name:stream/profile
# $ dnf module install perl:5.24/minimal
# if unspecified, they will be defaulted (see [d] param in dnf module list output)
def install
# ensure we start fresh (remove existing stream)
uninstall unless [:absent, :purged].include?(@property_hash[:ensure])
args = @resource[:name].dup
case @resource[:ensure]
when true, false, Symbol
# pass
else
args << ":#{@resource[:ensure]}"
end
args << "/#{@resource[:flavor]}" if @resource[:flavor]
if @resource[:enable_only] == true
enable(args)
else
begin
execute([command(:dnf), 'module', 'install', '-y', args])
rescue Puppet::ExecutionFailure => e
# module has no default profile and no profile was requested, so just enable the stream
# DNF versions prior to 4.2.8 do not need this workaround
# see https://bugzilla.redhat.com/show_bug.cgi?id=1669527
if @resource[:flavor].nil? && e.message =~ /^(?:missing|broken) groups or modules: #{Regexp.quote(args)}$/
enable(args)
else
raise
end
end
end
end
# should only get here when @resource[ensure] is :disabled
def insync?(is)
if resource[:ensure] == :disabled
# in sync only if package is already disabled
pkg = self.class.instances.find do |package|
@resource[:name] == package.name && package.properties[:ensure] == :disabled
end
return true if pkg
end
false
end
def enable(args = @resource[:name])
execute([command(:dnf), 'module', 'enable', '-y', args])
end
def uninstall
execute([command(:dnf), 'module', 'remove', '-y', @resource[:name]])
reset # reset module to the default stream
end
def disable(args = @resource[:name])
execute([command(:dnf), 'module', 'disable', '-y', args])
end
def reset
execute([command(:dnf), 'module', 'reset', '-y', @resource[:name]])
end
def flavor
@property_hash[:flavor]
end
def flavor=(value)
install if flavor != @resource.should(:flavor)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/apt.rb | lib/puppet/provider/package/apt.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/util/package/version/debian'
Puppet::Type.type(:package).provide :apt, :parent => :dpkg, :source => :dpkg do
# Provide sorting functionality
include Puppet::Util::Package
DebianVersion = Puppet::Util::Package::Version::Debian
VersionRange = Puppet::Util::Package::Version::Range
desc "Package management via `apt-get`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to apt-get.
These options should be specified as an array where each element is either a
string or a hash."
has_feature :versionable, :install_options, :virtual_packages, :version_ranges
commands :aptget => "/usr/bin/apt-get"
commands :aptcache => "/usr/bin/apt-cache"
commands :aptmark => "/usr/bin/apt-mark"
commands :preseed => "/usr/bin/debconf-set-selections"
defaultfor 'os.family' => :debian
ENV['DEBIAN_FRONTEND'] = "noninteractive"
# disable common apt helpers to allow non-interactive package installs
ENV['APT_LISTBUGS_FRONTEND'] = "none"
ENV['APT_LISTCHANGES_FRONTEND'] = "none"
def self.defaultto_allow_virtual
false
end
def self.instances
packages = super
manual_marks = aptmark('showmanual').split("\n")
packages.each do |package|
package.mark = :manual if manual_marks.include?(package.name)
end
packages
end
def query
hash = super
if !%i[absent purged].include?(hash[:ensure]) && aptmark('showmanual', @resource[:name]).strip == @resource[:name]
hash[:mark] = :manual
end
hash
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def mark
@property_flush[:mark]
end
def mark=(value)
@property_flush[:mark] = value
end
def flush
# unless we are removing the package mark it if it hasn't already been marked
if @property_flush
unless @property_flush[:mark] || [:purge, :absent].include?(resource[:ensure])
aptmark('manual', resource[:name])
end
end
end
# A derivative of DPKG; this is how most people actually manage
# Debian boxes, and the only thing that differs is that it can
# install packages from remote sites.
# Double negation confuses Rubocop's Layout cops
# rubocop:disable Layout
def checkforcdrom
have_cdrom = begin
!!(File.read("/etc/apt/sources.list") =~ /^[^#]*cdrom:/)
rescue
# This is basically pathological...
false
end
# rubocop:enable Layout
if have_cdrom and @resource[:allowcdrom] != :true
raise Puppet::Error, _("/etc/apt/sources.list contains a cdrom source; not installing. Use 'allowcdrom' to override this failure.")
end
end
def best_version(should_range)
versions = []
output = aptcache :madison, @resource[:name]
output.each_line do |line|
is = line.split('|')[1].strip
begin
is_version = DebianVersion.parse(is)
versions << is_version if should_range.include?(is_version)
rescue DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{is} as a debian version")
end
end
return versions.max if versions.any?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should_range
end
# Install a package using 'apt-get'. This function needs to support
# installing a specific version.
def install
run_preseed if @resource[:responsefile]
should = @resource[:ensure]
if should.is_a?(String)
begin
should_range = VersionRange.parse(should, DebianVersion)
unless should_range.is_a?(VersionRange::Eq)
should = best_version(should_range)
end
rescue VersionRange::ValidationFailure, DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{should} as a debian version range, falling through")
end
end
checkforcdrom
cmd = %w[-q -y]
config = @resource[:configfiles]
if config
if config == :keep
cmd << "-o" << 'DPkg::Options::=--force-confold'
else
cmd << "-o" << 'DPkg::Options::=--force-confnew'
end
end
str = @resource[:name]
case should
when true, false, Symbol
# pass
else
# Add the package version and --force-yes option
str += "=#{should}"
cmd << "--force-yes"
end
cmd += install_options if @resource[:install_options]
cmd << :install
if source
cmd << source
else
cmd << str
end
unhold if properties[:mark] == :hold
begin
aptget(*cmd)
ensure
hold if @resource[:mark] == :hold
end
# If a source file was specified, we must make sure the expected version was installed from specified file
if source && !%i[present installed].include?(should)
is = query
raise Puppet::Error, _("Could not find package %{name}") % { name: name } unless is
version = is[:ensure]
raise Puppet::Error, _("Failed to update to version %{should}, got version %{version} instead") % { should: should, version: version } unless
insync?(version)
end
end
# What's the latest package version available?
def latest
output = aptcache :policy, @resource[:name]
if output =~ /Candidate:\s+(\S+)\s/
Regexp.last_match(1)
else
err _("Could not find latest version")
nil
end
end
#
# preseeds answers to dpkg-set-selection from the "responsefile"
#
def run_preseed
response = @resource[:responsefile]
if response && Puppet::FileSystem.exist?(response)
info(_("Preseeding %{response} to debconf-set-selections") % { response: response })
preseed response
else
info _("No responsefile specified or non existent, not preseeding anything")
end
end
def uninstall
run_preseed if @resource[:responsefile]
args = ['-y', '-q']
args << '--allow-change-held-packages' if properties[:mark] == :hold
args << :remove << @resource[:name]
aptget(*args)
end
def purge
run_preseed if @resource[:responsefile]
args = ['-y', '-q']
args << '--allow-change-held-packages' if properties[:mark] == :hold
args << :remove << '--purge' << @resource[:name]
aptget(*args)
# workaround a "bug" in apt, that already removed packages are not purged
super
end
def install_options
join_options(@resource[:install_options])
end
def insync?(is)
# this is called after the generic version matching logic (insync? for the
# type), so we only get here if should != is
return false unless is && is != :absent
# if 'should' is a range and 'is' a debian version we should check if 'should' includes 'is'
should = @resource[:ensure]
return false unless is.is_a?(String) && should.is_a?(String)
begin
should_range = VersionRange.parse(should, DebianVersion)
rescue VersionRange::ValidationFailure, DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{should} as a debian version range")
return false
end
begin
is_version = DebianVersion.parse(is)
rescue DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{is} as a debian version")
return false
end
should_range.include?(is_version)
end
private
def source
@source ||= @resource[:source]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/nim.rb | lib/puppet/provider/package/nim.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/package'
Puppet::Type.type(:package).provide :nim, :parent => :aix, :source => :aix do
desc "Installation from an AIX NIM LPP source. The `source` parameter is required
for this provider, and should specify the name of a NIM `lpp_source` resource
that is visible to the puppet agent machine. This provider supports the
management of both BFF/installp and RPM packages.
Note that package downgrades are *not* supported; if your resource specifies
a specific version number and there is already a newer version of the package
installed on the machine, the resource will fail with an error message."
# The commands we are using on an AIX box are installed standard
# (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
commands :nimclient => "/usr/sbin/nimclient",
:lslpp => "/usr/bin/lslpp",
:rpm => "rpm"
# If NIM has not been configured, /etc/niminfo will not be present.
# However, we have no way of knowing if the NIM server is not configured
# properly.
confine :exists => "/etc/niminfo"
has_feature :versionable
attr_accessor :latest_info
def self.srclistcmd(source)
[command(:nimclient), "-o", "showres", "-a", "installp_flags=L", "-a", "resource=#{source}"]
end
def uninstall
output = lslpp("-qLc", @resource[:name]).split(':')
# the 6th index in the colon-delimited output contains a " " for installp/BFF
# packages, and an "R" for RPMS. (duh.)
pkg_type = output[6]
case pkg_type
when " "
installp "-gu", @resource[:name]
when "R"
rpm "-e", @resource[:name]
else
self.fail(_("Unrecognized AIX package type identifier: '%{pkg_type}'") % { pkg_type: pkg_type })
end
# installp will return an exit code of zero even if it didn't uninstall
# anything... so let's make sure it worked.
unless query().nil?
self.fail _("Failed to uninstall package '%{name}'") % { name: @resource[:name] }
end
end
def install(useversion = true)
source = @resource[:source]
unless source
self.fail _("An LPP source location is required in 'source'")
end
pkg = @resource[:name]
version_specified = (useversion and (!@resource.should(:ensure).is_a? Symbol))
# This is unfortunate for a couple of reasons. First, because of a subtle
# difference in the command-line syntax for installing an RPM vs an
# installp/BFF package, we need to know ahead of time which type of
# package we're trying to install. This means we have to execute an
# extra command.
#
# Second, the command is easiest to deal with and runs fastest if we
# pipe it through grep on the shell. Unfortunately, the way that
# the provider `make_command_methods` metaprogramming works, we can't
# use that code path to execute the command (because it treats the arguments
# as an array of args that all apply to `nimclient`, which fails when you
# hit the `|grep`.) So here we just call straight through to P::U.execute
# with a single string argument for the full command, rather than going
# through the metaprogrammed layer. We could get rid of the grep and
# switch back to the metaprogrammed stuff, and just parse all of the output
# in Ruby... but we'd be doing an awful lot of unnecessary work.
showres_command = "/usr/sbin/nimclient -o showres -a resource=#{source} |/usr/bin/grep -p -E "
if version_specified
version = @resource.should(:ensure)
showres_command << "'#{Regexp.escape(pkg)}( |-)#{Regexp.escape(version)}'"
else
version = nil
showres_command << "'#{Regexp.escape(pkg)}'"
end
output = Puppet::Util::Execution.execute(showres_command)
if version_specified
package_type = determine_package_type(output, pkg, version)
else
package_type, version = determine_latest_version(output, pkg)
end
if package_type.nil?
errmsg = if version_specified
_("Unable to find package '%{package}' with version '%{version}' on lpp_source '%{source}'") %
{ package: pkg, version: version, source: source }
else
_("Unable to find package '%{package}' on lpp_source '%{source}'") % { package: pkg, source: source }
end
self.fail errmsg
end
# This part is a bit tricky. If there are multiple versions of the
# package available, then `version` will be set to a value, and we'll need
# to add that value to our installation command. However, if there is only
# one version of the package available, `version` will be set to `nil`, and
# we don't need to add the version string to the command.
if version
# Now we know if the package type is RPM or not, and we can adjust our
# `pkg` string for passing to the install command accordingly.
if package_type == :rpm
# RPMs expect a hyphen between the package name and the version number
version_separator = "-"
else
# installp/BFF packages expect a space between the package name and the
# version number.
version_separator = " "
end
pkg += version_separator + version
end
# NOTE: the installp flags here are ignored (but harmless) for RPMs
output = nimclient "-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=#{source}", "-a", "filesets=#{pkg}"
# If the package is superseded, it means we're trying to downgrade and we
# can't do that.
case package_type
when :installp
if output =~ /^#{Regexp.escape(@resource[:name])}\s+.*\s+Already superseded by.*$/
self.fail _("NIM package provider is unable to downgrade packages")
end
when :rpm
if output =~ /^#{Regexp.escape(@resource[:name])}.* is superseded by.*$/
self.fail _("NIM package provider is unable to downgrade packages")
end
end
end
private
## UTILITY METHODS FOR PARSING `nimclient -o showres` output
# This makes me very sad. These regexes seem pretty fragile, but
# I spent a lot of time trying to figure out a solution that didn't
# require parsing the `nimclient -o showres` output and was unable to
# do so.
self::HEADER_LINE_REGEX = /^([^\s]+)\s+[^@]+@@(I|R|S):(\1)\s+[^\s]+$/
self::PACKAGE_LINE_REGEX = /^.*@@(I|R|S):(.*)$/
self::RPM_PACKAGE_REGEX = /^(.*)-(.*-\d+\w*) \2$/
self::INSTALLP_PACKAGE_REGEX = /^(.*) (.*)$/
# Here is some sample output that shows what the above regexes will be up
# against:
# FOR AN INSTALLP(bff) PACKAGE:
#
# mypackage.foo ALL @@I:mypackage.foo _all_filesets
# + 1.2.3.4 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.4
# + 1.2.3.8 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.8
#
# FOR AN INSTALLP(bff) PACKAGE with security update:
#
# bos.net ALL @@S:bos.net _all_filesets
# + 7.2.0.1 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.1
# + 7.2.0.2 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.2
#
# FOR AN RPM PACKAGE:
#
# mypackage.foo ALL @@R:mypackage.foo _all_filesets
# @@R:mypackage.foo-1.2.3-1 1.2.3-1
# @@R:mypackage.foo-1.2.3-4 1.2.3-4
# @@R:mypackage.foo-1.2.3-8 1.2.3-8
# Parse the output of a `nimclient -o showres` command. Returns a two-dimensional
# hash, where the first-level keys are package names, the second-level keys are
# version number strings for all of the available version numbers for a package,
# and the values indicate the package type (:rpm / :installp)
def parse_showres_output(showres_output)
paragraphs = split_into_paragraphs(showres_output)
packages = {}
paragraphs.each do |para|
lines = para.split(/$/)
parse_showres_header_line(lines.shift)
lines.each do |l|
package, version, type = parse_showres_package_line(l)
packages[package] ||= {}
packages[package][version] = type
end
end
packages
end
# This method basically just splits the multi-line input string into chunks
# based on lines that contain nothing but whitespace. It also strips any
# leading or trailing whitespace (including newlines) from the resulting
# strings and then returns them as an array.
def split_into_paragraphs(showres_output)
showres_output.split(/^\s*$/).map(&:strip!)
end
def parse_showres_header_line(line)
# This method doesn't produce any meaningful output; it's basically just
# meant to validate that the header line for the package listing output
# looks sane, so we know we're dealing with the kind of output that we
# are capable of handling.
unless line.match(self.class::HEADER_LINE_REGEX)
self.fail _("Unable to parse output from nimclient showres: line does not match expected package header format:\n'%{line}'") % { line: line }
end
end
def parse_installp_package_string(package_string)
match = package_string.match(self.class::INSTALLP_PACKAGE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: package string does not match expected installp package string format:\n'%{package_string}'") % { package_string: package_string }
end
package_name = match.captures[0]
version = match.captures[1]
[package_name, version, :installp]
end
def parse_rpm_package_string(package_string)
match = package_string.match(self.class::RPM_PACKAGE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: package string does not match expected rpm package string format:\n'%{package_string}'") % { package_string: package_string }
end
package_name = match.captures[0]
version = match.captures[1]
[package_name, version, :rpm]
end
def parse_showres_package_line(line)
match = line.match(self.class::PACKAGE_LINE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: line does not match expected package line format:\n'%{line}'") % { line: line }
end
package_type_flag = match.captures[0]
package_string = match.captures[1]
case package_type_flag
when "I", "S"
parse_installp_package_string(package_string)
when "R"
parse_rpm_package_string(package_string)
else
self.fail _("Unrecognized package type specifier: '%{package_type_flag}' in package line:\n'%{line}'") % { package_type_flag: package_type_flag, line: line }
end
end
# Given a blob of output from `nimclient -o showres` and a package name,
# this method checks to see if there are multiple versions of the package
# available on the lpp_source. If there are, the method returns
# [package_type, latest_version] (where package_type is one of :installp or :rpm).
# If there is only one version of the package available, it returns
# [package_type, nil], because the caller doesn't need to pass the version
# string to the command-line command if there is only one version available.
# If the package is not available at all, the method simply returns nil (instead
# of a tuple).
def determine_latest_version(showres_output, package_name)
packages = parse_showres_output(showres_output)
unless packages.has_key?(package_name)
return nil
end
if packages[package_name].count == 1
version = packages[package_name].keys[0]
[packages[package_name][version], nil]
else
versions = packages[package_name].keys
latest_version = versions.sort { |a, b| Puppet::Util::Package.versioncmp(b, a) }[0]
[packages[package_name][latest_version], latest_version]
end
end
def determine_package_type(showres_output, package_name, version)
packages = parse_showres_output(showres_output)
unless packages.has_key?(package_name) and packages[package_name].has_key?(version)
return nil
end
packages[package_name][version]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/tdnf.rb | lib/puppet/provider/package/tdnf.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :tdnf, :parent => :dnf do
desc "Support via `tdnf`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to tdnf.
These options should be specified as a string (e.g. `'--flag'`), a hash (e.g. `{'--flag' => 'value'}`), or an
array where each element is either a string or a hash."
has_feature :install_options, :versionable, :virtual_packages
commands :cmd => "tdnf", :rpm => "rpm"
# Note: this confine was borrowed from the Yum provider. The
# original purpose (from way back in 2007) was to make sure we
# never try to use RPM on a machine without it. We think this
# has probably become obsolete with the way `commands` work, so
# we should investigate removing it at some point.
#
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => "PhotonOS"
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/puppet_gem.rb | lib/puppet/provider/package/puppet_gem.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :puppet_gem, :parent => :gem do
desc "Puppet Ruby Gem support. This provider is useful for managing
gems needed by the ruby provided in the puppet-agent package."
has_feature :versionable, :install_options, :uninstall_options
confine :true => Puppet.runtime[:facter].value(:aio_agent_version)
commands :gemcmd => Puppet.run_mode.gem_cmd
def uninstall
super
Puppet.debug("Invalidating rubygems cache after uninstalling gem '#{resource[:name]}'")
Puppet::Util::Autoload.gem_source.clear_paths
end
def self.execute_gem_command(command, command_options, custom_environment = {})
if (pkg_config_path = Puppet.run_mode.pkg_config_path)
custom_environment['PKG_CONFIG_PATH'] = pkg_config_path
end
super(command, command_options, custom_environment)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/aptitude.rb | lib/puppet/provider/package/aptitude.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :aptitude, :parent => :apt, :source => :dpkg do
desc "Package management via `aptitude`."
has_feature :versionable
commands :aptitude => "/usr/bin/aptitude"
commands :aptcache => "/usr/bin/apt-cache"
ENV['DEBIAN_FRONTEND'] = "noninteractive"
def aptget(*args)
args.flatten!
# Apparently aptitude hasn't always supported a -q flag.
args.delete("-q") if args.include?("-q")
args.delete("--force-yes") if args.include?("--force-yes")
output = aptitude(*args)
# Yay, stupid aptitude doesn't throw an error when the package is missing.
if args.include?(:install) and output.to_s =~ /Couldn't find any package/
raise Puppet::Error, _("Could not find package %{name}") % { name: name }
end
end
def purge
aptitude '-y', 'purge', @resource[:name]
end
private
def source
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/ports.rb | lib/puppet/provider/package/ports.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :ports, :parent => :freebsd, :source => :freebsd do
desc "Support for FreeBSD's ports. Note that this, too, mixes packages and ports."
commands :portupgrade => "/usr/local/sbin/portupgrade",
:portversion => "/usr/local/sbin/portversion",
:portuninstall => "/usr/local/sbin/pkg_deinstall",
:portinfo => "/usr/sbin/pkg_info"
%w[INTERACTIVE UNAME].each do |var|
ENV.delete(var) if ENV.include?(var)
end
def install
# -N: install if the package is missing, otherwise upgrade
# -M: yes, we're a batch, so don't ask any questions
cmd = %w[-N -M BATCH=yes] << @resource[:name]
output = portupgrade(*cmd)
if output =~ /\*\* No such /
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] }
end
end
# If there are multiple packages, we only use the last one
def latest
cmd = ["-v", @resource[:name]]
begin
output = portversion(*cmd)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
line = output.split("\n").pop
unless line =~ /^(\S+)\s+(\S)\s+(.+)$/
# There's no "latest" version, so just return a placeholder
return :latest
end
pkgstuff = Regexp.last_match(1)
match = Regexp.last_match(2)
info = Regexp.last_match(3)
unless pkgstuff =~ /^\S+-([^-\s]+)$/
raise Puppet::Error,
_("Could not match package info '%{pkgstuff}'") % { pkgstuff: pkgstuff }
end
version = Regexp.last_match(1)
if match == "=" or match == ">"
# we're up to date or more recent
return version
end
# Else, we need to be updated; we need to pull out the new version
unless info =~ /\((\w+) has (.+)\)/
raise Puppet::Error,
_("Could not match version info '%{info}'") % { info: info }
end
source = Regexp.last_match(1)
newversion = Regexp.last_match(2)
debug "Newer version in #{source}"
newversion
end
def query
# support portorigin_glob such as "mail/postfix"
name = self.name
if name =~ %r{/}
name = self.name.split(%r{/}).slice(1)
end
self.class.instances.each do |instance|
if instance.name == name
return instance.properties
end
end
nil
end
def uninstall
portuninstall @resource[:name]
end
def update
install
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pkg.rb | lib/puppet/provider/package/pkg.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :pkg, :parent => Puppet::Provider::Package do
desc "OpenSolaris image packaging system. See pkg(5) for more information.
This provider supports the `install_options` attribute, which allows
command-line flags to be passed to pkg. These options should be specified as an
array where each element is either a string or a hash."
# https://docs.oracle.com/cd/E19963-01/html/820-6572/managepkgs.html
# A few notes before we start:
# Opensolaris pkg has two slightly different formats (as of now.)
# The first one is what is distributed with the Solaris 11 Express 11/10 dvd
# The latest one is what you get when you update package.
# To make things more interesting, pkg version just returns a sha sum.
# dvd: pkg version => 052adf36c3f4
# updated: pkg version => 630e1ffc7a19
# Thankfully, Solaris has not changed the commands to be used.
# TODO: We still have to allow packages to specify a preferred publisher.
has_feature :versionable
has_feature :upgradable
has_feature :holdable
has_feature :install_options
commands :pkg => "/usr/bin/pkg"
confine 'os.family' => :solaris
defaultfor 'os.family' => :solaris, :kernelrelease => ['5.11', '5.12']
def self.instances
pkg(:list, '-Hv').split("\n").map { |l| new(parse_line(l)) }
end
# The IFO flag field is just what it names, the first field can have either
# i_nstalled or -, and second field f_rozen or -, and last
# o_bsolate or r_rename or -
# so this checks if the installed field is present, and also verifies that
# if not the field is -, else we don't know what we are doing and exit with
# out doing more damage.
def self.ifo_flag(flags)
(
case flags[0..0]
when 'i'
{ :status => 'installed' }
when '-'
{ :status => 'known' }
else
raise ArgumentError, _('Unknown format %{resource_name}: %{full_flags}[%{bad_flag}]') %
{ resource_name: name, full_flags: flags, bad_flag: flags[0..0] }
end
).merge(
case flags[1..1]
when 'f'
{ :mark => :hold }
when '-'
{}
else
raise ArgumentError, _('Unknown format %{resource_name}: %{full_flags}[%{bad_flag}]') %
{ resource_name: name, full_flags: flags, bad_flag: flags[1..1] }
end
)
end
# The UFOXI field is the field present in the older pkg
# (solaris 2009.06 - snv151a)
# similar to IFO, UFOXI is also an either letter or -
# u_pdate indicates that an update for the package is available.
# f_rozen(n/i) o_bsolete x_cluded(n/i) i_constrained(n/i)
# note that u_pdate flag may not be trustable due to constraints.
# so we dont rely on it
# Frozen was never implemented in UFOXI so skipping frozen here.
def self.ufoxi_flag(flags)
{}
end
# pkg state was present in the older version of pkg (with UFOXI) but is
# no longer available with the IFO field version. When it was present,
# it was used to indicate that a particular version was present (installed)
# and later versions were known. Note that according to the pkg man page,
# known never lists older versions of the package. So we can rely on this
# field to make sure that if a known is present, then the pkg is upgradable.
def self.pkg_state(state)
case state
when /installed/
{ :status => 'installed' }
when /known/
{ :status => 'known' }
else
raise ArgumentError, _('Unknown format %{resource_name}: %{state}') % { resource_name: name, state: state }
end
end
# Here is (hopefully) the only place we will have to deal with multiple
# formats of output for different pkg versions.
def self.parse_line(line)
(case line.chomp
# FMRI IFO
# pkg://omnios/SUNWcs@0.5.11,5.11-0.151008:20131204T022241Z ---
when %r{^pkg://([^/]+)/([^@]+)@(\S+) +(...)$}
{ :publisher => Regexp.last_match(1), :name => Regexp.last_match(2), :ensure => Regexp.last_match(3) }.merge ifo_flag(Regexp.last_match(4))
# FMRI STATE UFOXI
# pkg://solaris/SUNWcs@0.5.11,5.11-0.151.0.1:20101105T001108Z installed u----
when %r{^pkg://([^/]+)/([^@]+)@(\S+) +(\S+) +(.....)$}
{ :publisher => Regexp.last_match(1), :name => Regexp.last_match(2), :ensure => Regexp.last_match(3) }.merge pkg_state(Regexp.last_match(4)).merge(ufoxi_flag(Regexp.last_match(5)))
else
raise ArgumentError, _('Unknown line format %{resource_name}: %{parse_line}') % { resource_name: name, parse_line: line }
end).merge({ :provider => name })
end
def hold
pkg(:freeze, @resource[:name])
end
def unhold
r = exec_cmd(command(:pkg), 'unfreeze', @resource[:name])
raise Puppet::Error, _("Unable to unfreeze %{package}") % { package: r[:out] } unless [0, 4].include? r[:exit]
end
def insync?(is)
# this is called after the generic version matching logic (insync? for the
# type), so we only get here if should != is, and 'should' is a version
# number. 'is' might not be, though.
should = @resource[:ensure]
# NB: it is apparently possible for repository administrators to publish
# packages which do not include build or branch versions, but component
# version must always be present, and the timestamp is added by pkgsend
# publish.
if /^[0-9.]+(,[0-9.]+)?(-[0-9.]+)?:[0-9]+T[0-9]+Z$/ !~ should
# We have a less-than-explicit version string, which we must accept for
# backward compatibility. We can find the real version this would match
# by asking pkg for the all matching versions, and selecting the first
# installable one [0]; this can change over time when remote repositories
# are updated, but the principle of least astonishment should still hold:
# if we allow users to specify less-than-explicit versions, the
# functionality should match that of the package manager.
#
# [0]: we could simply get the newest matching version with 'pkg list
# -n', but that isn't always correct, since it might not be installable.
# If that were the case we could potentially end up returning false for
# insync? here but not actually changing the package version in install
# (ie. if the currently installed version is the latest matching version
# that is installable, we would falsely conclude here that since the
# installed version is not the latest matching version, we're not in
# sync). 'pkg list -a' instead of '-n' would solve this, but
# unfortunately it doesn't consider downgrades 'available' (eg. with
# installed foo@1.0, list -a foo@0.9 would fail).
name = @resource[:name]
potential_matches = pkg(:list, '-Hvfa', "#{name}@#{should}").split("\n").map { |l| self.class.parse_line(l) }
n = potential_matches.length
if n > 1
warning(_("Implicit version %{should} has %{n} possible matches") % { should: should, n: n })
end
potential_matches.each { |p|
command = is == :absent ? 'install' : 'update'
options = ['-n']
options.concat(join_options(@resource[:install_options])) if @resource[:install_options]
begin
unhold if properties[:mark] == :hold
status = exec_cmd(command(:pkg), command, *options, "#{name}@#{p[:ensure]}")[:exit]
ensure
hold if properties[:mark] == :hold
end
case status
when 4
# if the first installable match would cause no changes, we're in sync
return true
when 0
warning(_("Selecting version '%{version}' for implicit '%{should}'") % { version: p[:ensure], should: should })
@resource[:ensure] = p[:ensure]
return false
end
}
raise Puppet::DevError, _("No version of %{name} matching %{should} is installable, even though the package is currently installed") %
{ name: name, should: should }
end
false
end
# Return the version of the package. Note that the bug
# http://defect.opensolaris.org/bz/show_bug.cgi?id=19159%
# notes that we can't use -Ha for the same even though the manual page reads that way.
def latest
# Refresh package metadata before looking for latest versions
pkg(:refresh)
lines = pkg(:list, "-Hvn", @resource[:name]).split("\n")
# remove certificate expiration warnings from the output, but report them
cert_warnings = lines.select { |line| line =~ /^Certificate/ }
unless cert_warnings.empty?
Puppet.warning(_("pkg warning: %{warnings}") % { warnings: cert_warnings.join(', ') })
end
lst = lines.select { |line| line !~ /^Certificate/ }.map { |line| self.class.parse_line(line) }
# Now we know there is a newer version. But is that installable? (i.e are there any constraints?)
# return the first known we find. The only way that is currently available is to do a dry run of
# pkg update and see if could get installed (`pkg update -n res`).
known = lst.find { |p| p[:status] == 'known' }
if known
options = ['-n']
options.concat(join_options(@resource[:install_options])) if @resource[:install_options]
return known[:ensure] if exec_cmd(command(:pkg), 'update', *options, @resource[:name])[:exit].zero?
end
# If not, then return the installed, else nil
(lst.find { |p| p[:status] == 'installed' } || {})[:ensure]
end
# install the package and accept all licenses.
def install(nofail = false)
name = @resource[:name]
should = @resource[:ensure]
is = query
if is[:ensure].to_sym == :absent
command = 'install'
else
command = 'update'
end
args = ['--accept']
if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.2') >= 0
args.push('--sync-actuators-timeout', '900')
end
args.concat(join_options(@resource[:install_options])) if @resource[:install_options]
unless should.is_a? Symbol
name += "@#{should}"
end
unhold if properties[:mark] == :hold
begin
tries = 1
# pkg install exits with code 7 when the image is currently in use by another process and cannot be modified
r = exec_cmd(command(:pkg), command, *args, name)
while r[:exit] == 7
if tries > 4
raise Puppet::Error, _("Pkg could not install %{name} after %{tries} tries. Aborting run") % { name: name, tries: tries }
end
sleep 2**tries
tries += 1
r = exec_cmd(command(:pkg), command, *args, name)
end
ensure
hold if @resource[:mark] == :hold
end
return r if nofail
raise Puppet::Error, _("Unable to update %{package}") % { package: r[:out] } if r[:exit] != 0
end
# uninstall the package. The complication comes from the -r_ecursive flag which is no longer
# present in newer package version.
def uninstall
cmd = [:uninstall]
case (pkg :version).chomp
when /052adf36c3f4/
cmd << '-r'
end
cmd << @resource[:name]
unhold if properties[:mark] == :hold
begin
pkg cmd
rescue StandardError, LoadError => e
hold if properties[:mark] == :hold
raise e
end
end
# update the package to the latest version available
def update
r = install(true)
# 4 == /No updates available for this image./
return if [0, 4].include? r[:exit]
raise Puppet::Error, _("Unable to update %{package}") % { package: r[:out] }
end
# list a specific package
def query
r = exec_cmd(command(:pkg), 'list', '-Hv', @resource[:name])
return { :ensure => :absent, :name => @resource[:name] } if r[:exit] != 0
self.class.parse_line(r[:out])
end
def exec_cmd(*cmd)
output = Puppet::Util::Execution.execute(cmd, :failonfail => false, :combine => true)
{ :out => output, :exit => output.exitstatus }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/rug.rb | lib/puppet/provider/package/rug.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :rug, :parent => :rpm do
desc "Support for suse `rug` package manager."
has_feature :versionable
commands :rug => "/usr/bin/rug"
commands :rpm => "rpm"
confine 'os.name' => [:suse, :sles]
# Install a package using 'rug'.
def install
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
wanted = @resource[:name]
# XXX: We don't actually deal with epochs here.
case should
when true, false, Symbol
# pass
else
# Add the package version
wanted += "-#{should}"
end
rug "--quiet", :install, "-y", wanted
unless query
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name }
end
end
# What's the latest package version available?
def latest
# rug can only get a list of *all* available packages?
output = rug "list-updates"
if output =~ /#{Regexp.escape @resource[:name]}\s*\|\s*([^\s|]+)/
Regexp.last_match(1)
else
# rug didn't find updates, pretend the current
# version is the latest
@property_hash[:ensure]
end
end
def update
# rug install can be used for update, too
install
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/windows.rb | lib/puppet/provider/package/windows.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/windows'
require_relative 'windows/package'
Puppet::Type.type(:package).provide(:windows, :parent => Puppet::Provider::Package) do
desc "Windows package management.
This provider supports either MSI or self-extracting executable installers.
This provider requires a `source` attribute when installing the package.
It accepts paths to local files, mapped drives, or UNC paths.
This provider supports the `install_options` and `uninstall_options`
attributes, which allow command-line flags to be passed to the installer.
These options should be specified as an array where each element is either
a string or a hash.
If the executable requires special arguments to perform a silent install or
uninstall, then the appropriate arguments should be specified using the
`install_options` or `uninstall_options` attributes, respectively. Puppet
will automatically quote any option that contains spaces."
confine 'os.name' => :windows
defaultfor 'os.name' => :windows
has_feature :installable
has_feature :uninstallable
has_feature :install_options
has_feature :uninstall_options
has_feature :versionable
attr_accessor :package
class << self
attr_accessor :paths
end
def self.post_resource_eval
@paths.each do |path|
Puppet::FileSystem.unlink(path)
rescue => detail
raise Puppet::Error.new(_("Error when unlinking %{path}: %{detail}") % { path: path, detail: detail.message }, detail)
end if @paths
end
# Return an array of provider instances
def self.instances
Puppet::Provider::Package::Windows::Package.map do |pkg|
provider = new(to_hash(pkg))
provider.package = pkg
provider
end
end
def self.to_hash(pkg)
{
:name => pkg.name,
:ensure => pkg.version || :installed,
:provider => :windows
}
end
# Query for the provider hash for the current resource. The provider we
# are querying, may not have existed during prefetch
def query
Puppet::Provider::Package::Windows::Package.find do |pkg|
if pkg.match?(resource)
return self.class.to_hash(pkg)
end
end
nil
end
def install
installer = Puppet::Provider::Package::Windows::Package.installer_class(resource)
command = [installer.install_command(resource), install_options].flatten.compact.join(' ')
working_dir = File.dirname(resource[:source])
unless Puppet::FileSystem.exist?(working_dir)
working_dir = nil
end
output = execute(command, :failonfail => false, :combine => true, :cwd => working_dir, :suppress_window => true)
check_result(output.exitstatus)
end
def uninstall
command = [package.uninstall_command, uninstall_options].flatten.compact.join(' ')
output = execute(command, :failonfail => false, :combine => true, :suppress_window => true)
check_result(output.exitstatus)
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa368542(v=vs.85).aspx
self::ERROR_SUCCESS = 0
self::ERROR_SUCCESS_REBOOT_INITIATED = 1641
self::ERROR_SUCCESS_REBOOT_REQUIRED = 3010
# (Un)install may "fail" because the package requested a reboot, the system requested a
# reboot, or something else entirely. Reboot requests mean the package was installed
# successfully, but we warn since we don't have a good reboot strategy.
def check_result(hr)
operation = resource[:ensure] == :absent ? 'uninstall' : 'install'
case hr
when self.class::ERROR_SUCCESS
# yeah
when self.class::ERROR_SUCCESS_REBOOT_INITIATED
warning(_("The package %{operation}ed successfully and the system is rebooting now.") % { operation: operation })
when self.class::ERROR_SUCCESS_REBOOT_REQUIRED
warning(_("The package %{operation}ed successfully, but the system must be rebooted.") % { operation: operation })
else
raise Puppet::Util::Windows::Error.new(_("Failed to %{operation}") % { operation: operation }, hr)
end
end
# This only gets called if there is a value to validate, but not if it's absent
def validate_source(value)
fail(_("The source parameter cannot be empty when using the Windows provider.")) if value.empty?
end
def install_options
join_options(resource[:install_options])
end
def uninstall_options
join_options(resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/gem.rb | lib/puppet/provider/package/gem.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package/version/gem'
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/provider/package_targetable'
require 'uri'
# Ruby gems support.
Puppet::Type.type(:package).provide :gem, :parent => Puppet::Provider::Package::Targetable do
desc "Ruby Gem support. If a URL is passed via `source`, then that URL is
appended to the list of remote gem repositories; to ensure that only the
specified source is used, also pass `--clear-sources` via `install_options`.
If source is present but is not a valid URL, it will be interpreted as the
path to a local gem file. If source is not present, the gem will be
installed from the default gem repositories. Note that to modify this for Windows, it has to be a valid URL.
This provider supports the `install_options` and `uninstall_options` attributes,
which allow command-line flags to be passed to the gem command.
These options should be specified as an array where each element is either a
string or a hash."
has_feature :versionable, :install_options, :uninstall_options, :targetable, :version_ranges
GEM_VERSION = Puppet::Util::Package::Version::Gem
GEM_VERSION_RANGE = Puppet::Util::Package::Version::Range
# Override the specificity method to return 1 if gem is not set as default provider
def self.specificity
match = default_match
length = match ? match.length : 0
return 1 if length == 0
super
end
# Define the default provider package command name when the provider is targetable.
# Required by Puppet::Provider::Package::Targetable::resource_or_provider_command
def self.provider_command
if Puppet::Util::Platform.windows?
Puppet::Util.withenv(PATH: windows_path_without_puppet_bin) { command(:gemcmd) }
else
command(:gemcmd)
end
end
# Define the default provider package command as optional when the provider is targetable.
# Doing do defers the evaluation of provider suitability until all commands are evaluated.
has_command(:gemcmd, 'gem') do
is_optional
end
# Having puppet/bin in PATH makes gem provider to use puppet/bin/gem
# This is an utility methods that reads the PATH and returns a string
# that contains the content of PATH but without puppet/bin dir.
# This is used to pass a custom PATH and execute commands in a controlled environment
def self.windows_path_without_puppet_bin
# rubocop:disable Naming/MemoizedInstanceVariableName
@path ||= ENV['PATH'].split(File::PATH_SEPARATOR)
.reject { |dir| dir =~ /puppet\\bin$/ }
.join(File::PATH_SEPARATOR)
# rubocop:enable Naming/MemoizedInstanceVariableName
end
private_class_method :windows_path_without_puppet_bin
# CommandDefiner in provider.rb creates convenience execution methods that set failonfail, combine, and optionally, environment.
# And when a child provider defines its own command via commands() or has_command(), the provider-specific path is always returned by command().
# But when the convenience execution method is invoked, the last convenience method to be defined is executed.
# This makes invoking those convenience execution methods unsuitable for inherited providers.
#
# In this case, causing the puppet_gem provider to inherit the parent gem provider's convenience gemcmd() methods, with the wrong path.
def self.execute_gem_command(command, command_options, custom_environment = {})
validate_command(command)
cmd = [command] << command_options
custom_environment = { 'HOME' => ENV.fetch('HOME', nil) }.merge(custom_environment)
if Puppet::Util::Platform.windows?
custom_environment[:PATH] = windows_path_without_puppet_bin
end
# This uses an unusual form of passing the command and args as [<cmd>, [<arg1>, <arg2>, ...]]
execute(cmd, { :failonfail => true, :combine => true, :custom_environment => custom_environment })
end
def self.instances(target_command = nil)
if target_command
command = target_command
else
command = provider_command
# The default provider package command is optional.
return [] unless command
end
gemlist(:command => command, :local => true).collect do |pkg|
# Track the command when the provider is targetable.
pkg[:command] = command
new(pkg)
end
end
def self.gemlist(options)
command_options = ["list"]
if options[:local]
command_options << "--local"
else
command_options << "--remote"
end
if options[:source]
command_options << "--source" << options[:source]
end
name = options[:justme]
if name
command_options << '\A' + name + '\z'
end
begin
list = execute_gem_command(options[:command], command_options).lines
.filter_map { |set| gemsplit(set) }
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not list gems: %{detail}") % { detail: detail }, detail.backtrace
end
if options[:justme]
list.shift
else
list
end
end
def self.gemsplit(desc)
# `gem list` when output console has a line like:
# *** LOCAL GEMS ***
# but when it's not to the console that line
# and all blank lines are stripped
# so we don't need to check for them
if desc =~ /^(\S+)\s+\((.+)\)/
gem_name = Regexp.last_match(1)
versions = Regexp.last_match(2).sub('default: ', '').split(/,\s*/)
{
:name => gem_name,
:ensure => versions.map { |v| v.split[0] },
:provider => name
}
else
Puppet.warning _("Could not match %{desc}") % { desc: desc } unless desc.chomp.empty?
nil
end
end
def insync?(is)
return false unless is && is != :absent
is = [is] unless is.is_a? Array
should = @resource[:ensure]
unless should =~ Regexp.union(/,/, Gem::Requirement::PATTERN)
begin
should_range = GEM_VERSION_RANGE.parse(should, GEM_VERSION)
rescue GEM_VERSION_RANGE::ValidationFailure, GEM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a ruby gem version range")
return false
end
return is.any? do |version|
should_range.include?(GEM_VERSION.parse(version))
rescue GEM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{version} as a ruby gem version")
false
end
end
begin
# Range intersections are not supported by Gem::Requirement, so just split by comma.
dependency = Gem::Dependency.new('', should.split(','))
rescue ArgumentError
# Bad requirements will cause an error during gem command invocation, so just return not in sync
return false
end
# Check if any version matches the dependency
is.any? { |version| dependency.match?('', version) }
end
def rubygem_version(command)
command_options = ["--version"]
self.class.execute_gem_command(command, command_options)
end
def install(useversion = true)
command = resource_or_provider_command
command_options = ["install"]
command_options += install_options if resource[:install_options]
should = resource[:ensure]
unless should =~ Regexp.union(/,/, Gem::Requirement::PATTERN)
begin
should_range = GEM_VERSION_RANGE.parse(should, GEM_VERSION)
should = should_range.to_gem_version
useversion = true
rescue GEM_VERSION_RANGE::ValidationFailure, GEM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a ruby gem version range. Falling through.")
end
end
if Puppet::Util::Platform.windows?
command_options << "-v" << %Q("#{should}") if useversion && !should.is_a?(Symbol)
elsif useversion && !should.is_a?(Symbol)
command_options << "-v" << should
end
if Puppet::Util::Package.versioncmp(rubygem_version(command), '2.0.0') == -1
command_options << "--no-rdoc" << "--no-ri"
else
command_options << "--no-document"
end
source = resource[:source]
if source
begin
uri = URI.parse(source)
rescue => detail
self.fail Puppet::Error, _("Invalid source '%{uri}': %{detail}") % { uri: uri, detail: detail }, detail
end
case uri.scheme
when nil
# no URI scheme => interpret the source as a local file
command_options << source
when /file/i
command_options << uri.path
when 'puppet'
# we don't support puppet:// URLs (yet)
raise Puppet::Error, _("puppet:// URLs are not supported as gem sources")
else
# check whether it's an absolute file path to help Windows out
if Puppet::Util.absolute_path?(source)
command_options << source
else
# interpret it as a gem repository
command_options << "--source" << source.to_s << resource[:name]
end
end
else
command_options << resource[:name]
end
output = self.class.execute_gem_command(command, command_options)
# Apparently some gem versions don't exit non-0 on failure.
self.fail _("Could not install: %{output}") % { output: output.chomp } if output.include?("ERROR")
end
def latest
command = resource_or_provider_command
options = { :command => command, :justme => resource[:name] }
options[:source] = resource[:source] unless resource[:source].nil?
pkg = self.class.gemlist(options)
pkg[:ensure][0]
end
def query
command = resource_or_provider_command
options = { :command => command, :justme => resource[:name], :local => true }
pkg = self.class.gemlist(options)
pkg[:command] = command unless pkg.nil?
pkg
end
def uninstall
command = resource_or_provider_command
command_options = ["uninstall"]
command_options << "--executables" << "--all" << resource[:name]
command_options += uninstall_options if resource[:uninstall_options]
output = self.class.execute_gem_command(command, command_options)
# Apparently some gem versions don't exit non-0 on failure.
self.fail _("Could not uninstall: %{output}") % { output: output.chomp } if output.include?("ERROR")
end
def update
install(false)
end
def install_options
join_options(resource[:install_options])
end
def uninstall_options
join_options(resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/pkgdmg.rb | lib/puppet/provider/package/pkgdmg.rb | # frozen_string_literal: true
#
# Motivation: DMG files provide a true HFS file system
# and are easier to manage and .pkg bundles.
#
# Note: the 'apple' Provider checks for the package name
# in /L/Receipts. Since we install multiple pkg's from a single
# source, we treat the source .pkg.dmg file as the package name.
# As a result, we store installed .pkg.dmg file names
# in /var/db/.puppet_pkgdmg_installed_<name>
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/plist'
require_relative '../../../puppet/util/http_proxy'
Puppet::Type.type(:package).provide :pkgdmg, :parent => Puppet::Provider::Package do
desc "Package management based on Apple's Installer.app and DiskUtility.app.
This provider works by checking the contents of a DMG image for Apple pkg or
mpkg files. Any number of pkg or mpkg files may exist in the root directory
of the DMG file system, and Puppet will install all of them. Subdirectories
are not checked for packages.
This provider can also accept plain .pkg (but not .mpkg) files in addition
to .dmg files.
Notes:
* The `source` attribute is mandatory. It must be either a local disk path
or an HTTP, HTTPS, or FTP URL to the package.
* The `name` of the resource must be the filename (without path) of the DMG file.
* When installing the packages from a DMG, this provider writes a file to
disk at `/var/db/.puppet_pkgdmg_installed_NAME`. If that file is present,
Puppet assumes all packages from that DMG are already installed.
* This provider is not versionable and uses DMG filenames to determine
whether a package has been installed. Thus, to install new a version of a
package, you must create a new DMG with a different filename."
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
defaultfor 'os.name' => :darwin
commands :installer => "/usr/sbin/installer"
commands :hdiutil => "/usr/bin/hdiutil"
commands :curl => "/usr/bin/curl"
# JJM We store a cookie for each installed .pkg.dmg in /var/db
def self.instance_by_name
Dir.entries("/var/db").find_all { |f|
f =~ /^\.puppet_pkgdmg_installed_/
}.collect do |f|
name = f.sub(/^\.puppet_pkgdmg_installed_/, '')
yield name if block_given?
name
end
end
def self.instances
instance_by_name.collect do |name|
new(:name => name, :provider => :pkgdmg, :ensure => :installed)
end
end
def self.installpkg(source, name, orig_source)
installer "-pkg", source, "-target", "/"
# Non-zero exit status will throw an exception.
Puppet::FileSystem.open("/var/db/.puppet_pkgdmg_installed_#{name}", nil, "w:UTF-8") do |t|
t.print "name: '#{name}'\n"
t.print "source: '#{orig_source}'\n"
end
end
def self.installpkgdmg(source, name)
unless Puppet::Util::HttpProxy.no_proxy?(source)
http_proxy_host = Puppet::Util::HttpProxy.http_proxy_host
http_proxy_port = Puppet::Util::HttpProxy.http_proxy_port
end
unless source =~ /\.dmg$/i || source =~ /\.pkg$/i
raise Puppet::Error, _("Mac OS X PKG DMGs must specify a source string ending in .dmg or flat .pkg file")
end
require 'open-uri' # Dead code; this is never used. The File.open call 20-ish lines south of here used to be Kernel.open but changed in '09. -NF
cached_source = source
tmpdir = Dir.mktmpdir
ext = /(\.dmg|\.pkg)$/i.match(source)[0]
begin
if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source
cached_source = File.join(tmpdir, "#{name}#{ext}")
args = ["-o", cached_source, "-C", "-", "-L", "-s", "--fail", "--url", source]
if http_proxy_host and http_proxy_port
args << "--proxy" << "#{http_proxy_host}:#{http_proxy_port}"
elsif http_proxy_host and !http_proxy_port
args << "--proxy" << http_proxy_host
end
begin
curl(*args)
Puppet.debug "Success: curl transferred [#{name}] (via: curl #{args.join(' ')})"
rescue Puppet::ExecutionFailure
Puppet.debug "curl #{args.join(' ')} did not transfer [#{name}]. Falling back to local file." # This used to fall back to open-uri. -NF
cached_source = source
end
end
if source =~ /\.dmg$/i
# If you fix this to use open-uri again, you must update the docs above. -NF
File.open(cached_source) do |dmg|
xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path
hdiutil_info = Puppet::Util::Plist.parse_plist(xml_str)
raise Puppet::Error, _("No disk entities returned by mount at %{path}") % { path: dmg.path } unless hdiutil_info.has_key?("system-entities")
mounts = hdiutil_info["system-entities"].filter_map { |entity|
entity["mount-point"]
}
begin
mounts.each do |mountpoint|
Dir.entries(mountpoint).select { |f|
f =~ /\.m{0,1}pkg$/i
}.each do |pkg|
installpkg("#{mountpoint}/#{pkg}", name, source)
end
end
ensure
mounts.each do |mountpoint|
hdiutil "eject", mountpoint
end
end
end
else
installpkg(cached_source, name, source)
end
ensure
FileUtils.remove_entry_secure(tmpdir, true)
end
end
def query
if Puppet::FileSystem.exist?("/var/db/.puppet_pkgdmg_installed_#{@resource[:name]}")
Puppet.debug "/var/db/.puppet_pkgdmg_installed_#{@resource[:name]} found"
{ :name => @resource[:name], :ensure => :present }
else
nil
end
end
def install
source = @resource[:source]
unless source
raise Puppet::Error, _("Mac OS X PKG DMGs must specify a package source.")
end
name = @resource[:name]
unless name
raise Puppet::Error, _("Mac OS X PKG DMGs must specify a package name.")
end
self.class.installpkgdmg(source, name)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/dpkg.rb | lib/puppet/provider/package/dpkg.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package do
desc "Package management via `dpkg`. Because this only uses `dpkg`
and not `apt`, you must specify the source of any packages you want
to manage."
has_feature :holdable, :virtual_packages
commands :dpkg => "/usr/bin/dpkg"
commands :dpkg_deb => "/usr/bin/dpkg-deb"
commands :dpkgquery => "/usr/bin/dpkg-query"
# Performs a dpkgquery call with a pipe so that output can be processed
# inline in a passed block.
# @param args [Array<String>] any command line arguments to be appended to the command
# @param block expected to be passed on to execpipe
# @return whatever the block returns
# @see Puppet::Util::Execution.execpipe
# @api private
def self.dpkgquery_piped(*args, &block)
cmd = args.unshift(command(:dpkgquery))
Puppet::Util::Execution.execpipe(cmd, &block)
end
def self.instances
packages = []
# list out all of the packages
dpkgquery_piped('-W', '--showformat', self::DPKG_QUERY_FORMAT_STRING) do |pipe|
# now turn each returned line into a package object
pipe.each_line do |line|
hash = parse_line(line)
if hash
packages << new(hash)
end
end
end
packages
end
private
# Note: self:: is required here to keep these constants in the context of what will
# eventually become this Puppet::Type::Package::ProviderDpkg class.
self::DPKG_QUERY_FORMAT_STRING = "'${Status} ${Package} ${Version}\\n'"
self::DPKG_QUERY_PROVIDES_FORMAT_STRING = "'${Status} ${Package} ${Version} [${Provides}]\\n'"
self::FIELDS_REGEX = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*)$/
self::FIELDS_REGEX_WITH_PROVIDES = /^'?(\S+) +(\S+) +(\S+) (\S+) (\S*) \[.*\]$/
self::FIELDS = [:desired, :error, :status, :name, :ensure]
def self.defaultto_allow_virtual
false
end
# @param line [String] one line of dpkg-query output
# @return [Hash,nil] a hash of FIELDS or nil if we failed to match
# @api private
def self.parse_line(line, regex = self::FIELDS_REGEX)
hash = nil
match = regex.match(line)
if match
hash = {}
self::FIELDS.zip(match.captures) do |field, value|
hash[field] = value
end
hash[:provider] = name
if hash[:status] == 'not-installed'
hash[:ensure] = :purged
elsif %w[config-files half-installed unpacked half-configured].include?(hash[:status])
hash[:ensure] = :absent
end
hash[:mark] = hash[:desired] == 'hold' ? :hold : :none
else
Puppet.debug("Failed to match dpkg-query line #{line.inspect}")
end
hash
end
public
def install
file = @resource[:source]
unless file
raise ArgumentError, _("You cannot install dpkg packages without a source")
end
args = []
if @resource[:configfiles] == :keep
args << '--force-confold'
else
args << '--force-confnew'
end
args << '-i' << file
unhold if properties[:mark] == :hold
begin
dpkg(*args)
ensure
hold if @resource[:mark] == :hold
end
end
def update
install
end
# Return the version from the package.
def latest
source = @resource[:source]
unless source
@resource.fail _("Could not update: You cannot install dpkg packages without a source")
end
output = dpkg_deb "--show", source
matches = /^(\S+)\t(\S+)$/.match(output).captures
warning _("source doesn't contain named package, but %{name}") % { name: matches[0] } unless matches[0].match(Regexp.escape(@resource[:name]))
matches[1]
end
def query
hash = nil
# list out our specific package
begin
if @resource.allow_virtual?
output = dpkgquery(
"-W",
"--showformat",
self.class::DPKG_QUERY_PROVIDES_FORMAT_STRING
# the regex searches for the resource[:name] in the dpkquery result in which the Provides field is also available
# it will search for the packages only in the brackets ex: [rubygems]
).lines.find { |package| package.match(/[\[ ](#{Regexp.escape(@resource[:name])})[\],]/) }
if output
hash = self.class.parse_line(output, self.class::FIELDS_REGEX_WITH_PROVIDES)
Puppet.info("Package #{@resource[:name]} is virtual, defaulting to #{hash[:name]}")
@resource[:name] = hash[:name]
end
end
output = dpkgquery(
"-W",
"--showformat",
self.class::DPKG_QUERY_FORMAT_STRING,
@resource[:name]
)
hash = self.class.parse_line(output)
rescue Puppet::ExecutionFailure
# dpkg-query exits 1 if the package is not found.
return { :ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok' }
end
hash ||= { :ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok' }
if hash[:error] != "ok"
raise Puppet::Error, "Package #{hash[:name]}, version #{hash[:ensure]} is in error state: #{hash[:error]}"
end
hash
end
def uninstall
dpkg "-r", @resource[:name]
end
def purge
dpkg "--purge", @resource[:name]
end
def hold
Tempfile.open('puppet_dpkg_set_selection') do |tmpfile|
tmpfile.write("#{@resource[:name]} hold\n")
tmpfile.flush
execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s)
end
end
def unhold
Tempfile.open('puppet_dpkg_set_selection') do |tmpfile|
tmpfile.write("#{@resource[:name]} install\n")
tmpfile.flush
execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/fink.rb | lib/puppet/provider/package/fink.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :fink, :parent => :dpkg, :source => :dpkg do
# Provide sorting functionality
include Puppet::Util::Package
desc "Package management via `fink`."
commands :fink => "/sw/bin/fink"
commands :aptget => "/sw/bin/apt-get"
commands :aptcache => "/sw/bin/apt-cache"
commands :dpkgquery => "/sw/bin/dpkg-query"
has_feature :versionable
# A derivative of DPKG; this is how most people actually manage
# Debian boxes, and the only thing that differs is that it can
# install packages from remote sites.
def finkcmd(*args)
fink(*args)
end
# Install a package using 'apt-get'. This function needs to support
# installing a specific version.
def install
run_preseed if @resource[:responsefile]
should = @resource.should(:ensure)
str = @resource[:name]
case should
when true, false, Symbol
# pass
else
# Add the package version
str += "=#{should}"
end
cmd = %w[-b -q -y]
cmd << :install << str
unhold if properties[:mark] == :hold
begin
finkcmd(cmd)
ensure
hold if @resource[:mark] == :hold
end
end
# What's the latest package version available?
def latest
output = aptcache :policy, @resource[:name]
if output =~ /Candidate:\s+(\S+)\s/
Regexp.last_match(1)
else
err _("Could not find latest version")
nil
end
end
#
# preseeds answers to dpkg-set-selection from the "responsefile"
#
def run_preseed
response = @resource[:responsefile]
if response && Puppet::FileSystem.exist?(response)
info(_("Preseeding %{response} to debconf-set-selections") % { response: response })
preseed response
else
info _("No responsefile specified or non existent, not preseeding anything")
end
end
def update
install
end
def uninstall
unhold if properties[:mark] == :hold
begin
finkcmd "-y", "-q", :remove, @model[:name]
rescue StandardError, LoadError => e
hold if properties[:mark] == :hold
raise e
end
end
def purge
unhold if properties[:mark] == :hold
begin
aptget '-y', '-q', 'remove', '--purge', @resource[:name]
rescue StandardError, LoadError => e
hold if properties[:mark] == :hold
raise e
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/rpm.rb | lib/puppet/provider/package/rpm.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/rpm_compare'
# RPM packaging. Should work anywhere that has rpm installed.
Puppet::Type.type(:package).provide :rpm, :source => :rpm, :parent => Puppet::Provider::Package do
# provides Rpm parsing and comparison
include Puppet::Util::RpmCompare
desc "RPM packaging support; should work anywhere with a working `rpm`
binary.
This provider supports the `install_options` and `uninstall_options`
attributes, which allow command-line flags to be passed to rpm.
These options should be specified as an array where each element is either a string or a hash."
has_feature :versionable
has_feature :install_options
has_feature :uninstall_options
has_feature :virtual_packages
has_feature :install_only
# Note: self:: is required here to keep these constants in the context of what will
# eventually become this Puppet::Type::Package::ProviderRpm class.
# The query format by which we identify installed packages
self::NEVRA_FORMAT = '%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n'
self::NEVRA_REGEX = /^'?(\S+) (\S+) (\S+) (\S+) (\S+)$/
self::NEVRA_FIELDS = [:name, :epoch, :version, :release, :arch]
self::MULTIVERSION_SEPARATOR = "; "
commands :rpm => "rpm"
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
def self.current_version
return @current_version unless @current_version.nil?
output = rpm "--version"
@current_version = output.gsub('RPM version ', '').strip
end
# rpm < 4.1 does not support --nosignature
def self.nosignature
'--nosignature' unless Puppet::Util::Package.versioncmp(current_version, '4.1') < 0
end
# rpm < 4.0.2 does not support --nodigest
def self.nodigest
'--nodigest' unless Puppet::Util::Package.versioncmp(current_version, '4.0.2') < 0
end
def self.instances
packages = []
# list out all of the packages
begin
execpipe("#{command(:rpm)} -qa #{nosignature} #{nodigest} --qf '#{self::NEVRA_FORMAT}' | sort") { |process|
# now turn each returned line into a package object
nevra_to_multiversion_hash(process).each { |hash| packages << new(hash) }
}
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, _("Failed to list packages"), e.backtrace
end
packages
end
# Find the fully versioned package name and the version alone. Returns
# a hash with entries :instance => fully versioned package name, and
# :ensure => version-release
def query
# NOTE: Prior to a fix for issue 1243, this method potentially returned a cached value
# IF YOU CALL THIS METHOD, IT WILL CALL RPM
# Use get(:property) to check if cached values are available
cmd = ["-q", @resource[:name], self.class.nosignature.to_s, self.class.nodigest.to_s, "--qf", self.class::NEVRA_FORMAT.to_s]
begin
output = rpm(*cmd)
rescue Puppet::ExecutionFailure
return nil unless @resource.allow_virtual?
# rpm -q exits 1 if package not found
# retry the query for virtual packages
cmd << '--whatprovides'
begin
output = rpm(*cmd)
rescue Puppet::ExecutionFailure
# couldn't find a virtual package either
return nil
end
end
@property_hash.update(self.class.nevra_to_multiversion_hash(output))
@property_hash.dup
end
# Here we just retrieve the version from the file specified in the source.
def latest
source = @resource[:source]
unless source
@resource.fail _("RPMs must specify a package source")
end
cmd = [command(:rpm), "-q", "--qf", self.class::NEVRA_FORMAT.to_s, "-p", source]
h = self.class.nevra_to_multiversion_hash(execute(cmd))
h[:ensure]
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, e.message, e.backtrace
end
def install
source = @resource[:source]
unless source
@resource.fail _("RPMs must specify a package source")
end
version = @property_hash[:ensure]
# RPM gets upset if you try to install an already installed package
return if @resource.should(:ensure) == version || (@resource.should(:ensure) == :latest && version == latest)
flag = ["-i"]
flag = ["-U", "--oldpackage"] if version && (version != :absent && version != :purged)
flag += install_options if resource[:install_options]
rpm flag, source
end
def uninstall
query
# If version and release (or only version) is specified in the resource,
# uninstall using them, otherwise uninstall using only the name of the package.
name = get(:name)
version = get(:version)
release = get(:release)
nav = "#{name}-#{version}"
nvr = "#{nav}-#{release}"
if @resource[:name].start_with? nvr
identifier = nvr
elsif @resource[:name].start_with? nav
identifier = nav
elsif @resource[:install_only]
identifier = get(:ensure).split(self.class::MULTIVERSION_SEPARATOR).map { |ver| "#{name}-#{ver}" }
else
identifier = name
end
# If an arch is specified in the resource, uninstall that arch,
# otherwise uninstall the arch returned by query.
# If multiple arches are installed and arch is not specified,
# this will uninstall all of them after successive runs.
#
# rpm prior to 4.2.1 cannot accept architecture as part of the package name.
unless Puppet::Util::Package.versioncmp(self.class.current_version, '4.2.1') < 0
arch = ".#{get(:arch)}"
if @resource[:name].end_with? arch
identifier += arch
end
end
flag = ['-e']
flag += uninstall_options if resource[:uninstall_options]
rpm flag, identifier
end
def update
install
end
def install_options
join_options(resource[:install_options])
end
def uninstall_options
join_options(resource[:uninstall_options])
end
def insync?(is)
return false if [:purged, :absent].include?(is)
return false if is.include?(self.class::MULTIVERSION_SEPARATOR) && !@resource[:install_only]
should = resource[:ensure]
is.split(self.class::MULTIVERSION_SEPARATOR).any? do |version|
0 == rpm_compare_evr(should, version)
end
end
private
# @param line [String] one line of rpm package query information
# @return [Hash] of NEVRA_FIELDS strings parsed from package info
# or an empty hash if we failed to parse
# @api private
def self.nevra_to_hash(line)
line.strip!
hash = {}
match = self::NEVRA_REGEX.match(line)
if match
self::NEVRA_FIELDS.zip(match.captures) { |f, v| hash[f] = v }
hash[:provider] = name
hash[:ensure] = "#{hash[:version]}-#{hash[:release]}"
hash[:ensure].prepend("#{hash[:epoch]}:") if hash[:epoch] != '0'
else
Puppet.debug("Failed to match rpm line #{line}")
end
hash
end
# @param line [String] multiple lines of rpm package query information
# @return list of [Hash] of NEVRA_FIELDS strings parsed from package info
# or an empty list if we failed to parse
# @api private
def self.nevra_to_multiversion_hash(multiline)
list = []
multiversion_hash = {}
multiline.each_line do |line|
hash = nevra_to_hash(line)
next if hash.empty?
if multiversion_hash.empty?
multiversion_hash = hash.dup
next
end
if multiversion_hash[:name] != hash[:name]
list << multiversion_hash
multiversion_hash = hash.dup
next
end
unless multiversion_hash[:ensure].include?(hash[:ensure])
multiversion_hash[:ensure].concat("#{self::MULTIVERSION_SEPARATOR}#{hash[:ensure]}")
end
end
list << multiversion_hash if multiversion_hash
if list.size == 1
return list[0]
end
list
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/windows/package.rb | lib/puppet/provider/package/windows/package.rb | # frozen_string_literal: true
require_relative '../../../../puppet/provider/package'
require_relative '../../../../puppet/util/windows'
class Puppet::Provider::Package::Windows
class Package
extend Enumerable
extend Puppet::Util::Errors
include Puppet::Util::Windows::Registry
extend Puppet::Util::Windows::Registry
attr_reader :name, :version
REG_DISPLAY_VALUE_NAMES = %w[DisplayName QuietDisplayName]
def self.reg_value_names_to_load
REG_DISPLAY_VALUE_NAMES |
MsiPackage::REG_VALUE_NAMES |
ExePackage::REG_VALUE_NAMES
end
# Enumerate each package. The appropriate package subclass
# will be yielded.
def self.each(&block)
with_key do |key, values|
name = key.name.match(/^.+\\([^\\]+)$/).captures[0]
[MsiPackage, ExePackage].find do |klass|
pkg = klass.from_registry(name, values)
if pkg
yield pkg
end
end
end
end
# Yield each registry key and its values associated with an
# installed package. This searches both per-machine and current
# user contexts, as well as packages associated with 64 and
# 32-bit installers.
def self.with_key(&block)
%w[HKEY_LOCAL_MACHINE HKEY_CURRENT_USER].each do |hive|
[KEY64, KEY32].each do |mode|
mode |= KEY_READ
begin
self.open(hive, 'Software\Microsoft\Windows\CurrentVersion\Uninstall', mode) do |uninstall|
each_key(uninstall) do |name, _wtime|
self.open(hive, "#{uninstall.keyname}\\#{name}", mode) do |key|
yield key, values_by_name(key, reg_value_names_to_load)
end
end
end
rescue Puppet::Util::Windows::Error => e
raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND
end
end
end
end
# Get the class that knows how to install this resource
def self.installer_class(resource)
fail(_("The source parameter is required when using the Windows provider.")) unless resource[:source]
case resource[:source]
when /\.msi"?\Z/i
# REMIND: can we install from URL?
# REMIND: what about msp, etc
MsiPackage
when /\.exe"?\Z/i
fail(_("The source does not exist: '%{source}'") % { source: resource[:source] }) unless
Puppet::FileSystem.exist?(resource[:source]) || resource[:source].start_with?('http://', 'https://')
ExePackage
else
fail(_("Don't know how to install '%{source}'") % { source: resource[:source] })
end
end
def self.munge(value)
quote(replace_forward_slashes(value))
end
def self.replace_forward_slashes(value)
if value.include?('/')
value = value.tr('/', "\\")
Puppet.debug('Package source parameter contained /s - replaced with \\s')
end
value
end
def self.quote(value)
value.include?(' ') ? %Q("#{value.gsub(/"/, '\"')}") : value
end
def self.get_display_name(values)
return if values.nil?
return values['DisplayName'] if values['DisplayName'] && values['DisplayName'].length > 0
return values['QuietDisplayName'] if values['QuietDisplayName'] && values['QuietDisplayName'].length > 0
''
end
def initialize(name, version)
@name = name
@version = version
end
end
end
require_relative '../../../../puppet/provider/package/windows/msi_package'
require_relative '../../../../puppet/provider/package/windows/exe_package'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/windows/exe_package.rb | lib/puppet/provider/package/windows/exe_package.rb | # frozen_string_literal: true
require_relative '../../../../puppet/provider/package/windows/package'
class Puppet::Provider::Package::Windows
class ExePackage < Puppet::Provider::Package::Windows::Package
attr_reader :uninstall_string
# registry values to load under each product entry in
# HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
# for this provider
REG_VALUE_NAMES = [
'DisplayVersion',
'UninstallString',
'ParentKeyName',
'Security Update',
'Update Rollup',
'Hotfix',
'WindowsInstaller'
]
def self.register(path)
Puppet::Type::Package::ProviderWindows.paths ||= []
Puppet::Type::Package::ProviderWindows.paths << path
end
# Return an instance of the package from the registry, or nil
def self.from_registry(name, values)
if valid?(name, values)
ExePackage.new(
get_display_name(values),
values['DisplayVersion'],
values['UninstallString']
)
end
end
# Is this a valid executable package we should manage?
def self.valid?(name, values)
# See http://community.spiceworks.com/how_to/show/2238
displayName = get_display_name(values)
!!(displayName && displayName.length > 0 &&
values['UninstallString'] &&
values['UninstallString'].length > 0 &&
values['WindowsInstaller'] != 1 && # DWORD
name !~ /^KB[0-9]{6}/ &&
values['ParentKeyName'].nil? &&
values['Security Update'].nil? &&
values['Update Rollup'].nil? &&
values['Hotfix'].nil?)
end
def initialize(name, version, uninstall_string)
super(name, version)
@uninstall_string = uninstall_string
end
# Does this package match the resource?
def match?(resource)
resource[:name] == name
end
def self.install_command(resource)
file_location = resource[:source]
if file_location.start_with?('http://', 'https://')
tempfile = Tempfile.new(['', '.exe'])
begin
uri = URI(Puppet::Util.uri_encode(file_location))
client = Puppet.runtime[:http]
client.get(uri, options: { include_system_store: true }) do |response|
raise Puppet::HTTP::ResponseError, response unless response.success?
File.open(tempfile.path, 'wb') do |file|
response.read_body do |data|
file.write(data)
end
end
end
rescue => detail
raise Puppet::Error.new(_("Error when installing %{package}: %{detail}") % { package: resource[:name], detail: detail.message }, detail)
ensure
register(tempfile.path)
tempfile.close()
file_location = tempfile.path
end
end
munge(file_location)
end
def uninstall_command
# Only quote bare uninstall strings, e.g.
# C:\Program Files (x86)\Notepad++\uninstall.exe
# Don't quote uninstall strings that are already quoted, e.g.
# "c:\ruby187\unins000.exe"
# Don't quote uninstall strings that contain arguments:
# "C:\Program Files (x86)\Git\unins000.exe" /SILENT
if uninstall_string =~ /\A[^"]*.exe\Z/i
command = "\"#{uninstall_string}\""
else
command = uninstall_string
end
command
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/package/windows/msi_package.rb | lib/puppet/provider/package/windows/msi_package.rb | # frozen_string_literal: true
require_relative '../../../../puppet/provider/package/windows/package'
class Puppet::Provider::Package::Windows
class MsiPackage < Puppet::Provider::Package::Windows::Package
attr_reader :productcode, :packagecode
# From msi.h
INSTALLSTATE_DEFAULT = 5 # product is installed for the current user
INSTALLUILEVEL_NONE = 2 # completely silent installation
# registry values to load under each product entry in
# HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
# for this provider
REG_VALUE_NAMES = %w[
DisplayVersion
WindowsInstaller
]
# Get the COM installer object, it's in a separate method for testing
def self.installer
# REMIND: when does the COM release happen?
WIN32OLE.new("WindowsInstaller.Installer")
end
# Return an instance of the package from the registry, or nil
def self.from_registry(name, values)
if valid?(name, values)
inst = installer
if inst.ProductState(name) == INSTALLSTATE_DEFAULT
MsiPackage.new(get_display_name(values),
values['DisplayVersion'],
name, # productcode
inst.ProductInfo(name, 'PackageCode'))
end
end
end
# Is this a valid MSI package we should manage?
def self.valid?(name, values)
# See http://community.spiceworks.com/how_to/show/2238
displayName = get_display_name(values)
!!(displayName && displayName.length > 0 &&
values['WindowsInstaller'] == 1 && # DWORD
name =~ /\A\{[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}\Z/i)
end
def initialize(name, version, productcode, packagecode)
super(name, version)
@productcode = productcode
@packagecode = packagecode
end
# Does this package match the resource?
def match?(resource)
resource[:name].casecmp(packagecode) == 0 ||
resource[:name].casecmp(productcode) == 0 ||
resource[:name] == name
end
def self.install_command(resource)
['msiexec.exe', '/qn', '/norestart', '/i', munge(resource[:source])]
end
def uninstall_command
['msiexec.exe', '/qn', '/norestart', '/x', productcode]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_bucket/file.rb | lib/puppet/file_bucket/file.rb | # frozen_string_literal: true
require_relative '../../puppet/file_bucket'
require_relative '../../puppet/indirector'
require_relative '../../puppet/util/checksums'
require 'digest/md5'
require 'stringio'
class Puppet::FileBucket::File
# This class handles the abstract notion of a file in a filebucket.
# There are mechanisms to save and load this file locally and remotely in puppet/indirector/filebucketfile/*
# There is a compatibility class that emulates pre-indirector filebuckets in Puppet::FileBucket::Dipper
extend Puppet::Indirector
indirects :file_bucket_file, :terminus_class => :selector
attr_reader :bucket_path
def self.supported_formats
[:binary]
end
def initialize(contents, options = {})
case contents
when String
@contents = StringContents.new(contents)
when Pathname
@contents = FileContents.new(contents)
else
raise ArgumentError, _("contents must be a String or Pathname, got a %{contents_class}") % { contents_class: contents.class }
end
@bucket_path = options.delete(:bucket_path)
@checksum_type = Puppet[:digest_algorithm].to_sym
raise ArgumentError, _("Unknown option(s): %{opts}") % { opts: options.keys.join(', ') } unless options.empty?
end
# @return [Num] The size of the contents
def size
@contents.size()
end
# @return [IO] A stream that reads the contents
def stream(&block)
@contents.stream(&block)
end
def checksum_type
@checksum_type.to_s
end
def checksum
"{#{checksum_type}}#{checksum_data}"
end
def checksum_data
@checksum_data ||= @contents.checksum_data(@checksum_type)
end
def to_s
to_binary
end
def to_binary
@contents.to_binary
end
def contents
to_binary
end
def name
"#{checksum_type}/#{checksum_data}"
end
def self.from_binary(contents)
new(contents)
end
class StringContents
def initialize(content)
@contents = content;
end
def stream(&block)
s = StringIO.new(@contents)
begin
block.call(s)
ensure
s.close
end
end
def size
@contents.size
end
def checksum_data(base_method)
Puppet.info(_("Computing checksum on string"))
Puppet::Util::Checksums.method(base_method).call(@contents)
end
def to_binary
# This is not so horrible as for FileContent, but still possible to mutate the content that the
# checksum is based on... so semi horrible...
@contents;
end
end
class FileContents
def initialize(path)
@path = path
end
def stream(&block)
Puppet::FileSystem.open(@path, nil, 'rb', &block)
end
def size
Puppet::FileSystem.size(@path)
end
def checksum_data(base_method)
Puppet.info(_("Computing checksum on file %{path}") % { path: @path })
Puppet::Util::Checksums.method(:"#{base_method}_file").call(@path)
end
def to_binary
Puppet::FileSystem.binread(@path)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_bucket/dipper.rb | lib/puppet/file_bucket/dipper.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../puppet/file_bucket'
require_relative '../../puppet/file_bucket/file'
require_relative '../../puppet/indirector/request'
require_relative '../../puppet/util/diff'
require 'tempfile'
class Puppet::FileBucket::Dipper
include Puppet::Util::Checksums
# This is a transitional implementation that uses REST
# to access remote filebucket files.
attr_accessor :name
# Creates a bucket client
def initialize(hash = {})
# Emulate the XMLRPC client
server = hash[:Server]
port = hash[:Port] || Puppet[:serverport]
if hash.include?(:Path)
@local_path = hash[:Path]
@rest_path = nil
else
@local_path = nil
@rest_path = "filebucket://#{server}:#{port}/"
end
@checksum_type = Puppet[:digest_algorithm].to_sym
@digest = method(@checksum_type)
end
def local?
!!@local_path
end
# Backs up a file to the file bucket
def backup(file)
file_handle = Puppet::FileSystem.pathname(file)
raise(ArgumentError, _("File %{file} does not exist") % { file: file }) unless Puppet::FileSystem.exist?(file_handle)
begin
file_bucket_file = Puppet::FileBucket::File.new(file_handle, :bucket_path => @local_path)
files_original_path = absolutize_path(file)
dest_path = "#{@rest_path}#{file_bucket_file.name}/#{files_original_path}"
file_bucket_path = "#{@rest_path}#{file_bucket_file.checksum_type}/#{file_bucket_file.checksum_data}/#{files_original_path}"
# Make a HEAD request for the file so that we don't waste time
# uploading it if it already exists in the bucket.
unless Puppet::FileBucket::File.indirection.head(file_bucket_path, :bucket_path => file_bucket_file.bucket_path)
Puppet::FileBucket::File.indirection.save(file_bucket_file, dest_path)
end
file_bucket_file.checksum_data
rescue => detail
message = _("Could not back up %{file}: %{detail}") % { file: file, detail: detail }
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
end
# Diffs two filebucket files identified by their sums
def diff(checksum_a, checksum_b, file_a, file_b)
raise RuntimeError, _("Diff is not supported on this platform") if Puppet[:diff] == ""
if checksum_a
source_path = "#{@rest_path}#{@checksum_type}/#{checksum_a}"
if checksum_b
file_diff = Puppet::FileBucket::File.indirection.find(
source_path,
:bucket_path => @local_path,
:diff_with => checksum_b
)
elsif file_b
tmp_file = ::Tempfile.new('diff')
begin
restore(tmp_file.path, checksum_a)
file_diff = Puppet::Util::Diff.diff(tmp_file.path, file_b)
ensure
tmp_file.close
tmp_file.unlink
end
else
raise Puppet::Error, _("Please provide a file or checksum to diff with")
end
elsif file_a
if checksum_b
tmp_file = ::Tempfile.new('diff')
begin
restore(tmp_file.path, checksum_b)
file_diff = Puppet::Util::Diff.diff(file_a, tmp_file.path)
ensure
tmp_file.close
tmp_file.unlink
end
elsif file_b
file_diff = Puppet::Util::Diff.diff(file_a, file_b)
end
end
raise Puppet::Error, _("Failed to diff files") unless file_diff
file_diff.to_s
end
# Retrieves a file by sum.
def getfile(sum)
get_bucket_file(sum).to_s
end
# Retrieves a FileBucket::File by sum.
def get_bucket_file(sum)
source_path = "#{@rest_path}#{@checksum_type}/#{sum}"
file_bucket_file = Puppet::FileBucket::File.indirection.find(source_path, :bucket_path => @local_path)
raise Puppet::Error, _("File not found") unless file_bucket_file
file_bucket_file
end
# Restores the file
def restore(file, sum)
restore = true
file_handle = Puppet::FileSystem.pathname(file)
if Puppet::FileSystem.exist?(file_handle)
cursum = Puppet::FileBucket::File.new(file_handle).checksum_data()
# if the checksum has changed...
# this might be extra effort
if cursum == sum
restore = false
end
end
if restore
newcontents = get_bucket_file(sum)
if newcontents
newsum = newcontents.checksum_data
changed = nil
if Puppet::FileSystem.exist?(file_handle) and !Puppet::FileSystem.writable?(file_handle)
changed = Puppet::FileSystem.stat(file_handle).mode
::File.chmod(changed | 0o200, file)
end
::File.open(file, ::File::WRONLY | ::File::TRUNC | ::File::CREAT) { |of|
of.binmode
newcontents.stream do |source_stream|
FileUtils.copy_stream(source_stream, of)
end
}
::File.chmod(changed, file) if changed
else
Puppet.err _("Could not find file with checksum %{sum}") % { sum: sum }
return nil
end
newsum
else
nil
end
end
# List Filebucket content.
def list(fromdate, todate)
raise Puppet::Error, _("Listing remote file buckets is not allowed") unless local?
source_path = "#{@rest_path}#{@checksum_type}/"
file_bucket_list = Puppet::FileBucket::File.indirection.find(
source_path,
:bucket_path => @local_path,
:list_all => true,
:fromdate => fromdate,
:todate => todate
)
raise Puppet::Error, _("File not found") unless file_bucket_list
file_bucket_list.to_s
end
private
def absolutize_path(path)
Pathname.new(path).realpath
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/state_machine.rb | lib/puppet/ssl/state_machine.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
require_relative '../../puppet/util/pidlock'
# This class implements a state machine for bootstrapping a host's CA and CRL
# bundles, private key and signed client certificate. Each state has a frozen
# SSLContext that it uses to make network connections. If a state makes progress
# bootstrapping the host, then the state will generate a new frozen SSLContext
# and pass that to the next state. For example, the NeedCACerts state will load
# or download a CA bundle, and generate a new SSLContext containing those CA
# certs. This way we're sure about which SSLContext is being used during any
# phase of the bootstrapping process.
#
# @api private
class Puppet::SSL::StateMachine
class SSLState
attr_reader :ssl_context
def initialize(machine, ssl_context)
@machine = machine
@ssl_context = ssl_context
@cert_provider = machine.cert_provider
@ssl_provider = machine.ssl_provider
end
def to_error(message, cause)
detail = Puppet::Error.new(message)
detail.set_backtrace(cause.backtrace)
Error.new(@machine, message, detail)
end
def log_error(message)
# When running daemonized we set stdout to /dev/null, so write to the log instead
if Puppet[:daemonize]
Puppet.err(message)
else
$stdout.puts(message)
end
end
end
# Load existing CA certs or download them. Transition to NeedCRLs.
#
class NeedCACerts < SSLState
def initialize(machine)
super(machine, nil)
@ssl_context = @ssl_provider.create_insecure_context
end
def next_state
Puppet.debug("Loading CA certs")
force_crl_refresh = false
cacerts = @cert_provider.load_cacerts
if cacerts
next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false)
now = Time.now
last_update = @cert_provider.ca_last_update
if needs_refresh?(now, last_update)
# If we refresh the CA, then we need to force the CRL to be refreshed too,
# since if there is a new CA in the chain, then we need its CRL to check
# the full chain for revocation status.
next_ctx, force_crl_refresh = refresh_ca(next_ctx, last_update)
end
else
route = @machine.session.route_to(:ca, ssl_context: @ssl_context)
_, pem = route.get_certificate(Puppet::SSL::CA_NAME, ssl_context: @ssl_context)
if @machine.ca_fingerprint
actual_digest = @machine.digest_as_hex(pem)
expected_digest = @machine.ca_fingerprint.scan(/../).join(':').upcase
if actual_digest == expected_digest
Puppet.info(_("Verified CA bundle with digest (%{digest_type}) %{actual_digest}") %
{ digest_type: @machine.digest, actual_digest: actual_digest })
else
e = Puppet::Error.new(_("CA bundle with digest (%{digest_type}) %{actual_digest} did not match expected digest %{expected_digest}") % { digest_type: @machine.digest, actual_digest: actual_digest, expected_digest: expected_digest })
return Error.new(@machine, e.message, e)
end
end
cacerts = @cert_provider.load_cacerts_from_pem(pem)
# verify cacerts before saving
next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false)
@cert_provider.save_cacerts(cacerts)
end
NeedCRLs.new(@machine, next_ctx, force_crl_refresh)
rescue OpenSSL::X509::CertificateError => e
Error.new(@machine, e.message, e)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
to_error(_('CA certificate is missing from the server'), e)
else
to_error(_('Could not download CA certificate: %{message}') % { message: e.message }, e)
end
end
private
def needs_refresh?(now, last_update)
return true if last_update.nil?
ca_ttl = Puppet[:ca_refresh_interval]
return false unless ca_ttl
now.to_i > last_update.to_i + ca_ttl
end
def refresh_ca(ssl_ctx, last_update)
Puppet.info(_("Refreshing CA certificate"))
# return the next_ctx containing the updated ca
next_ctx = [download_ca(ssl_ctx, last_update), true]
# After a successful refresh, update ca_last_update
@cert_provider.ca_last_update = Time.now
next_ctx
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 304
Puppet.info(_("CA certificate is unmodified, using existing CA certificate"))
else
Puppet.info(_("Failed to refresh CA certificate, using existing CA certificate: %{message}") % { message: e.message })
end
# return the original ssl_ctx
[ssl_ctx, false]
rescue Puppet::HTTP::HTTPError => e
Puppet.warning(_("Failed to refresh CA certificate, using existing CA certificate: %{message}") % { message: e.message })
# return the original ssl_ctx
[ssl_ctx, false]
end
def download_ca(ssl_ctx, last_update)
route = @machine.session.route_to(:ca, ssl_context: ssl_ctx)
_, pem = route.get_certificate(Puppet::SSL::CA_NAME, if_modified_since: last_update, ssl_context: ssl_ctx)
cacerts = @cert_provider.load_cacerts_from_pem(pem)
# verify cacerts before saving
next_ctx = @ssl_provider.create_root_context(cacerts: cacerts, revocation: false)
@cert_provider.save_cacerts(cacerts)
Puppet.info("Refreshed CA certificate: #{@machine.digest_as_hex(pem)}")
next_ctx
end
end
# If revocation is enabled, load CRLs or download them, using the CA bundle
# from the previous state. Transition to NeedKey. Even if Puppet[:certificate_revocation]
# is leaf or chain, disable revocation when downloading the CRL, since 1) we may
# not have one yet or 2) the connection will fail if NeedCACerts downloaded a new CA
# for which we don't have a CRL
#
class NeedCRLs < SSLState
attr_reader :force_crl_refresh
def initialize(machine, ssl_context, force_crl_refresh = false)
super(machine, ssl_context)
@force_crl_refresh = force_crl_refresh
end
def next_state
Puppet.debug("Loading CRLs")
case Puppet[:certificate_revocation]
when :chain, :leaf
crls = @cert_provider.load_crls
if crls
next_ctx = @ssl_provider.create_root_context(cacerts: ssl_context[:cacerts], crls: crls)
now = Time.now
last_update = @cert_provider.crl_last_update
if needs_refresh?(now, last_update)
next_ctx = refresh_crl(next_ctx, last_update)
end
else
next_ctx = download_crl(@ssl_context, nil)
end
else
Puppet.info("Certificate revocation is disabled, skipping CRL download")
next_ctx = @ssl_provider.create_root_context(cacerts: ssl_context[:cacerts], crls: [])
end
NeedKey.new(@machine, next_ctx)
rescue OpenSSL::X509::CRLError => e
Error.new(@machine, e.message, e)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
to_error(_('CRL is missing from the server'), e)
else
to_error(_('Could not download CRLs: %{message}') % { message: e.message }, e)
end
end
private
def needs_refresh?(now, last_update)
return true if @force_crl_refresh || last_update.nil?
crl_ttl = Puppet[:crl_refresh_interval]
return false unless crl_ttl
now.to_i > last_update.to_i + crl_ttl
end
def refresh_crl(ssl_ctx, last_update)
Puppet.info(_("Refreshing CRL"))
# return the next_ctx containing the updated crl
next_ctx = download_crl(ssl_ctx, last_update)
# After a successful refresh, update crl_last_update
@cert_provider.crl_last_update = Time.now
next_ctx
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 304
Puppet.info(_("CRL is unmodified, using existing CRL"))
else
Puppet.info(_("Failed to refresh CRL, using existing CRL: %{message}") % { message: e.message })
end
# return the original ssl_ctx
ssl_ctx
rescue Puppet::HTTP::HTTPError => e
Puppet.warning(_("Failed to refresh CRL, using existing CRL: %{message}") % { message: e.message })
# return the original ssl_ctx
ssl_ctx
end
def download_crl(ssl_ctx, last_update)
route = @machine.session.route_to(:ca, ssl_context: ssl_ctx)
_, pem = route.get_certificate_revocation_list(if_modified_since: last_update, ssl_context: ssl_ctx)
crls = @cert_provider.load_crls_from_pem(pem)
# verify crls before saving
next_ctx = @ssl_provider.create_root_context(cacerts: ssl_ctx[:cacerts], crls: crls)
@cert_provider.save_crls(crls)
Puppet.info("Refreshed CRL: #{@machine.digest_as_hex(pem)}")
next_ctx
end
end
# Load or generate a private key. If the key exists, try to load the client cert
# and transition to Done. If the cert is mismatched or otherwise fails valiation,
# raise an error. If the key doesn't exist yet, generate one, and save it. If the
# cert doesn't exist yet, transition to NeedSubmitCSR.
#
class NeedKey < SSLState
def next_state
Puppet.debug(_("Loading/generating private key"))
password = @cert_provider.load_private_key_password
key = @cert_provider.load_private_key(Puppet[:certname], password: password)
if key
cert = @cert_provider.load_client_cert(Puppet[:certname])
if cert
next_ctx = @ssl_provider.create_context(
cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: key, client_cert: cert
)
if needs_refresh?(cert)
return NeedRenewedCert.new(@machine, next_ctx, key)
else
return Done.new(@machine, next_ctx)
end
end
else
if Puppet[:key_type] == 'ec'
Puppet.info _("Creating a new EC SSL key for %{name} using curve %{curve}") % { name: Puppet[:certname], curve: Puppet[:named_curve] }
key = OpenSSL::PKey::EC.generate(Puppet[:named_curve])
else
Puppet.info _("Creating a new RSA SSL key for %{name}") % { name: Puppet[:certname] }
key = OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i)
end
@cert_provider.save_private_key(Puppet[:certname], key, password: password)
end
NeedSubmitCSR.new(@machine, @ssl_context, key)
end
private
def needs_refresh?(cert)
cert_ttl = Puppet[:hostcert_renewal_interval]
return false unless cert_ttl
Time.now.to_i >= (cert.not_after.to_i - cert_ttl)
end
end
# Base class for states with a private key.
#
class KeySSLState < SSLState
attr_reader :private_key
def initialize(machine, ssl_context, private_key)
super(machine, ssl_context)
@private_key = private_key
end
end
# Generate and submit a CSR using the CA cert bundle and optional CRL bundle
# from earlier states. If the request is submitted, proceed to NeedCert,
# otherwise Wait. This could be due to the server already having a CSR
# for this host (either the same or different CSR content), having a
# signed certificate, or a revoked certificate.
#
class NeedSubmitCSR < KeySSLState
def next_state
Puppet.debug(_("Generating and submitting a CSR"))
csr = @cert_provider.create_request(Puppet[:certname], @private_key)
route = @machine.session.route_to(:ca, ssl_context: @ssl_context)
route.put_certificate_request(Puppet[:certname], csr, ssl_context: @ssl_context)
@cert_provider.save_request(Puppet[:certname], csr)
NeedCert.new(@machine, @ssl_context, @private_key)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 400
NeedCert.new(@machine, @ssl_context, @private_key)
else
to_error(_("Failed to submit the CSR, HTTP response was %{code}") % { code: e.response.code }, e)
end
end
end
# Attempt to load or retrieve our signed cert.
#
class NeedCert < KeySSLState
def next_state
Puppet.debug(_("Downloading client certificate"))
route = @machine.session.route_to(:ca, ssl_context: @ssl_context)
cert = OpenSSL::X509::Certificate.new(
route.get_certificate(Puppet[:certname], ssl_context: @ssl_context)[1]
)
Puppet.info _("Downloaded certificate for %{name} from %{url}") % { name: Puppet[:certname], url: route.url }
# verify client cert before saving
next_ctx = @ssl_provider.create_context(
cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: @private_key, client_cert: cert
)
@cert_provider.save_client_cert(Puppet[:certname], cert)
@cert_provider.delete_request(Puppet[:certname])
Done.new(@machine, next_ctx)
rescue Puppet::SSL::SSLError => e
Error.new(@machine, e.message, e)
rescue OpenSSL::X509::CertificateError => e
Error.new(@machine, _("Failed to parse certificate: %{message}") % { message: e.message }, e)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
Puppet.info(_("Certificate for %{certname} has not been signed yet") % { certname: Puppet[:certname] })
$stdout.puts _("Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate (%{name}).") % { name: Puppet[:certname] }
Wait.new(@machine)
else
to_error(_("Failed to retrieve certificate for %{certname}: %{message}") %
{ certname: Puppet[:certname], message: e.message }, e)
end
end
end
# Class to renew a client/host certificate automatically.
#
class NeedRenewedCert < KeySSLState
def next_state
Puppet.debug(_("Renewing client certificate"))
route = @machine.session.route_to(:ca, ssl_context: @ssl_context)
cert = OpenSSL::X509::Certificate.new(
route.post_certificate_renewal(@ssl_context)[1]
)
# verify client cert before saving
next_ctx = @ssl_provider.create_context(
cacerts: @ssl_context.cacerts, crls: @ssl_context.crls, private_key: @private_key, client_cert: cert
)
@cert_provider.save_client_cert(Puppet[:certname], cert)
Puppet.info(_("Renewed client certificate: %{cert_digest}, not before '%{not_before}', not after '%{not_after}'") % { cert_digest: @machine.digest_as_hex(cert.to_pem), not_before: cert.not_before, not_after: cert.not_after })
Done.new(@machine, next_ctx)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404
Puppet.info(_("Certificate autorenewal has not been enabled on the server."))
else
Puppet.warning(_("Failed to automatically renew certificate: %{code} %{reason}") % { code: e.response.code, reason: e.response.reason })
end
Done.new(@machine, @ssl_context)
rescue => e
Puppet.warning(_("Unable to automatically renew certificate: %{message}") % { message: e.message })
Done.new(@machine, @ssl_context)
end
end
# We cannot make progress, so wait if allowed to do so, or exit.
#
class Wait < SSLState
def initialize(machine)
super(machine, nil)
end
def next_state
time = @machine.waitforcert
if time < 1
log_error(_("Exiting now because the waitforcert setting is set to 0."))
exit(1)
elsif Time.now.to_i > @machine.wait_deadline
log_error(_("Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate (%{name}). Exiting now because the maxwaitforcert timeout has been exceeded.") % { name: Puppet[:certname] })
exit(1)
else
Puppet.info(_("Will try again in %{time} seconds.") % { time: time })
# close http/tls and session state before sleeping
Puppet.runtime[:http].close
@machine.session = Puppet.runtime[:http].create_session
@machine.unlock
Kernel.sleep(time)
NeedLock.new(@machine)
end
end
end
# Acquire the ssl lock or return LockFailure causing us to exit.
#
class NeedLock < SSLState
def initialize(machine)
super(machine, nil)
end
def next_state
if @machine.lock
# our ssl directory may have been cleaned while we were
# sleeping, start over from the top
NeedCACerts.new(@machine)
elsif @machine.waitforlock < 1
LockFailure.new(@machine, _("Another puppet instance is already running and the waitforlock setting is set to 0; exiting"))
elsif Time.now.to_i >= @machine.waitlock_deadline
LockFailure.new(@machine, _("Another puppet instance is already running and the maxwaitforlock timeout has been exceeded; exiting"))
else
Puppet.info _("Another puppet instance is already running; waiting for it to finish")
Puppet.info _("Will try again in %{time} seconds.") % { time: @machine.waitforlock }
Kernel.sleep @machine.waitforlock
# try again
self
end
end
end
# We failed to acquire the lock, so exit
#
class LockFailure < SSLState
attr_reader :message
def initialize(machine, message)
super(machine, nil)
@message = message
end
end
# We cannot make progress due to an error.
#
class Error < SSLState
attr_reader :message, :error
def initialize(machine, message, error)
super(machine, nil)
@message = message
@error = error
end
def next_state
Puppet.log_exception(@error, @message)
Wait.new(@machine)
end
end
# We have a CA bundle, optional CRL bundle, a private key and matching cert
# that chains to one of the root certs in our bundle.
#
class Done < SSLState; end
attr_reader :waitforcert, :wait_deadline, :waitforlock, :waitlock_deadline, :cert_provider, :ssl_provider, :ca_fingerprint, :digest
attr_accessor :session
# Construct a state machine to manage the SSL initialization process. By
# default, if the state machine encounters an exception, it will log the
# exception and wait for `waitforcert` seconds and retry, restarting from the
# beginning of the state machine.
#
# However, if `onetime` is true, then the state machine will raise the first
# error it encounters, instead of waiting. Otherwise, if `waitforcert` is 0,
# then then state machine will exit instead of wait.
#
# @param waitforcert [Integer] how many seconds to wait between attempts
# @param maxwaitforcert [Integer] maximum amount of seconds to wait for the
# server to sign the certificate request
# @param waitforlock [Integer] how many seconds to wait between attempts for
# acquiring the ssl lock
# @param maxwaitforlock [Integer] maximum amount of seconds to wait for an
# already running process to release the ssl lock
# @param onetime [Boolean] whether to run onetime
# @param lockfile [Puppet::Util::Pidlock] lockfile to protect against
# concurrent modification by multiple processes
# @param cert_provider [Puppet::X509::CertProvider] cert provider to use
# to load and save X509 objects.
# @param ssl_provider [Puppet::SSL::SSLProvider] ssl provider to use
# to construct ssl contexts.
# @param digest [String] digest algorithm to use for certificate fingerprinting
# @param ca_fingerprint [String] optional fingerprint to verify the
# downloaded CA bundle
def initialize(waitforcert: Puppet[:waitforcert],
maxwaitforcert: Puppet[:maxwaitforcert],
waitforlock: Puppet[:waitforlock],
maxwaitforlock: Puppet[:maxwaitforlock],
onetime: Puppet[:onetime],
cert_provider: Puppet::X509::CertProvider.new,
ssl_provider: Puppet::SSL::SSLProvider.new,
lockfile: Puppet::Util::Pidlock.new(Puppet[:ssl_lockfile]),
digest: 'SHA256',
ca_fingerprint: Puppet[:ca_fingerprint])
@waitforcert = waitforcert
@wait_deadline = Time.now.to_i + maxwaitforcert
@waitforlock = waitforlock
@waitlock_deadline = Time.now.to_i + maxwaitforlock
@onetime = onetime
@cert_provider = cert_provider
@ssl_provider = ssl_provider
@lockfile = lockfile
@digest = digest
@ca_fingerprint = ca_fingerprint
@session = Puppet.runtime[:http].create_session
end
# Run the state machine for CA certs and CRLs.
#
# @return [Puppet::SSL::SSLContext] initialized SSLContext
# @raise [Puppet::Error] If we fail to generate an SSLContext
# @api private
def ensure_ca_certificates
final_state = run_machine(NeedLock.new(self), NeedKey)
final_state.ssl_context
end
# Run the state machine for client certs.
#
# @return [Puppet::SSL::SSLContext] initialized SSLContext
# @raise [Puppet::Error] If we fail to generate an SSLContext
# @api private
def ensure_client_certificate
final_state = run_machine(NeedLock.new(self), Done)
ssl_context = final_state.ssl_context
@ssl_provider.print(ssl_context, @digest)
ssl_context
end
def lock
@lockfile.lock
end
def unlock
@lockfile.unlock
end
def digest_as_hex(str)
Puppet::SSL::Digest.new(digest, str).to_hex
end
private
def run_machine(state, stop)
loop do
state = run_step(state)
case state
when stop
break
when LockFailure
raise Puppet::Error, state.message
when Error
if @onetime
Puppet.log_exception(state.error)
raise state.error
end
else
# fall through
end
end
state
ensure
@lockfile.unlock if @lockfile.locked?
end
def run_step(state)
state.next_state
rescue => e
state.to_error(e.message, e)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/ssl_context.rb | lib/puppet/ssl/ssl_context.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
module Puppet::SSL
# The `keyword_init: true` option is no longer needed in Ruby >= 3.2
SSLContext = Struct.new(
:store,
:cacerts,
:crls,
:private_key,
:client_cert,
:client_chain,
:revocation,
:verify_peer,
keyword_init: true
) do
def initialize(*)
super
self[:cacerts] ||= []
self[:crls] ||= []
self[:client_chain] ||= []
self[:revocation] = true if self[:revocation].nil?
self[:verify_peer] = true if self[:verify_peer].nil?
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/verifier.rb | lib/puppet/ssl/verifier.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
# Verify an SSL connection.
#
# @api private
class Puppet::SSL::Verifier
FIVE_MINUTES_AS_SECONDS = 5 * 60
attr_reader :ssl_context
# Create a verifier using an `ssl_context`.
#
# @param hostname [String] FQDN of the server we're attempting to connect to
# @param ssl_context [Puppet::SSL::SSLContext] ssl_context containing CA certs,
# CRLs, etc needed to verify the server's certificate chain
# @api private
def initialize(hostname, ssl_context)
@hostname = hostname
@ssl_context = ssl_context
end
# Return true if `self` is reusable with `verifier` meaning they
# are using the same `ssl_context`, so there's no loss of security
# when using a cached connection.
#
# @param verifier [Puppet::SSL::Verifier] the verifier to compare against
# @return [Boolean] return true if a cached connection can be used, false otherwise
# @api private
def reusable?(verifier)
verifier.instance_of?(self.class) &&
verifier.ssl_context.equal?(@ssl_context) # same object?
end
# Configure the `http` connection based on the current `ssl_context`.
#
# @param http [Net::HTTP] connection
# @api private
def setup_connection(http)
http.cert_store = @ssl_context[:store]
http.cert = @ssl_context[:client_cert]
http.key = @ssl_context[:private_key]
# default to VERIFY_PEER
http.verify_mode = if !@ssl_context[:verify_peer]
OpenSSL::SSL::VERIFY_NONE
else
OpenSSL::SSL::VERIFY_PEER
end
http.verify_callback = self
end
# This method is called if `Net::HTTP#start` raises an exception, which
# could be a result of an openssl error during cert verification, due
# to ruby's `Socket#post_connection_check`, or general SSL connection
# error.
#
# @param http [Net::HTTP] connection
# @param error [OpenSSL::SSL::SSLError] connection error
# @raise [Puppet::SSL::CertVerifyError] SSL connection failed due to a
# verification error with the server's certificate or chain
# @raise [Puppet::Error] server hostname does not match certificate
# @raise [OpenSSL::SSL::SSLError] low-level SSL connection failure
# @api private
def handle_connection_error(http, error)
raise @last_error if @last_error
# ruby can pass SSL validation but fail post_connection_check
peer_cert = http.peer_cert
if peer_cert && !OpenSSL::SSL.verify_certificate_identity(peer_cert, @hostname)
raise Puppet::SSL::CertMismatchError.new(peer_cert, @hostname)
else
raise error
end
end
# OpenSSL will call this method with the verification result for each cert in
# the server's chain, working from the root CA to the server's cert. If
# preverify_ok is `true`, then that cert passed verification. If it's `false`
# then the current verification error is contained in `store_context.error`.
# and the current cert is in `store_context.current_cert`.
#
# If this method returns `false`, then verification stops and ruby will raise
# an `OpenSSL::SSL::Error` with "certificate verification failed". If this
# method returns `true`, then verification continues.
#
# If this method ignores a verification error, such as the cert's CRL will be
# valid within the next 5 minutes, then this method may be called with a
# different verification error for the same cert.
#
# WARNING: If `store_context.error` returns `OpenSSL::X509::V_OK`, don't
# assume verification passed. Ruby 2.4+ implements certificate hostname
# checking by default, and if the cert doesn't match the hostname, then the
# error will be V_OK. Always use `preverify_ok` to determine if verification
# succeeded or not.
#
# @param preverify_ok [Boolean] if `true` the current certificate in `store_context`
# was verified. Otherwise, check for the current error in `store_context.error`
# @param store_context [OpenSSL::X509::StoreContext] The context holding the
# verification result for one certificate
# @return [Boolean] If `true`, continue verifying the chain, even if that means
# ignoring the current verification error. If `false`, abort the connection.
#
# @api private
def call(preverify_ok, store_context)
return true if preverify_ok
peer_cert = store_context.current_cert
case store_context.error
when OpenSSL::X509::V_OK
# chain is from leaf to root, opposite of the order that `call` is invoked
chain_cert = store_context.chain.first
# ruby 2.4 doesn't compare certs based on value, so force to DER byte array
if peer_cert && chain_cert && peer_cert.to_der == chain_cert.to_der && !OpenSSL::SSL.verify_certificate_identity(peer_cert, @hostname)
@last_error = Puppet::SSL::CertMismatchError.new(peer_cert, @hostname)
return false
end
# ruby-openssl#74ef8c0cc56b840b772240f2ee2b0fc0aafa2743 now sets the
# store_context error when the cert is mismatched
when OpenSSL::X509::V_ERR_HOSTNAME_MISMATCH
@last_error = Puppet::SSL::CertMismatchError.new(peer_cert, @hostname)
return false
when OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID
crl = store_context.current_crl
if crl && crl.last_update && crl.last_update < Time.now + FIVE_MINUTES_AS_SECONDS
Puppet.debug("Ignoring CRL not yet valid, current time #{Time.now.utc}, CRL last updated #{crl.last_update.utc}")
return true
end
end
# TRANSLATORS: `error` is an untranslated message from openssl describing why a certificate in the server's chain is invalid, and `subject` is the identity/name of the failed certificate
@last_error = Puppet::SSL::CertVerifyError.new(
_("certificate verify failed [%{error} for %{subject}]") %
{ error: store_context.error_string, subject: peer_cert.subject.to_utf8 },
store_context.error, peer_cert
)
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/digest.rb | lib/puppet/ssl/digest.rb | # frozen_string_literal: true
class Puppet::SSL::Digest
attr_reader :digest
def initialize(algorithm, content)
algorithm ||= 'SHA256'
@digest = OpenSSL::Digest.new(algorithm, content)
end
def to_s
"(#{name}) #{to_hex}"
end
def to_hex
@digest.hexdigest.scan(/../).join(':').upcase
end
def name
@digest.name.upcase
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/certificate_request.rb | lib/puppet/ssl/certificate_request.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl/base'
require_relative '../../puppet/ssl/certificate_signer'
# This class creates and manages X509 certificate signing requests.
#
# ## CSR attributes
#
# CSRs may contain a set of attributes that includes supplementary information
# about the CSR or information for the signed certificate.
#
# PKCS#9/RFC 2985 section 5.4 formally defines the "Challenge password",
# "Extension request", and "Extended-certificate attributes", but this
# implementation only handles the "Extension request" attribute. Other
# attributes may be defined on a CSR, but the RFC doesn't define behavior for
# any other attributes so we treat them as only informational.
#
# ## CSR Extension request attribute
#
# CSRs may contain an optional set of extension requests, which allow CSRs to
# include additional information that may be included in the signed
# certificate. Any additional information that should be copied from the CSR
# to the signed certificate MUST be included in this attribute.
#
# This behavior is dictated by PKCS#9/RFC 2985 section 5.4.2.
#
# @see https://tools.ietf.org/html/rfc2985 "RFC 2985 Section 5.4.2 Extension request"
#
class Puppet::SSL::CertificateRequest < Puppet::SSL::Base
wraps OpenSSL::X509::Request
# Because of how the format handler class is included, this
# can't be in the base class.
def self.supported_formats
[:s]
end
def extension_factory
# rubocop:disable Naming/MemoizedInstanceVariableName
@ef ||= OpenSSL::X509::ExtensionFactory.new
# rubocop:enable Naming/MemoizedInstanceVariableName
end
# Create a certificate request with our system settings.
#
# @param key [OpenSSL::X509::Key] The private key associated with this CSR.
# @param options [Hash]
# @option options [String] :dns_alt_names A comma separated list of
# Subject Alternative Names to include in the CSR extension request.
# @option options [Hash<String, String, Array<String>>] :csr_attributes A hash
# of OIDs and values that are either a string or array of strings.
# @option options [Array<String, String>] :extension_requests A hash of
# certificate extensions to add to the CSR extReq attribute, excluding
# the Subject Alternative Names extension.
#
# @raise [Puppet::Error] If the generated CSR signature couldn't be verified
#
# @return [OpenSSL::X509::Request] The generated CSR
def generate(key, options = {})
Puppet.info _("Creating a new SSL certificate request for %{name}") % { name: name }
# If we're a CSR for the CA, then use the real ca_name, rather than the
# fake 'ca' name. This is mostly for backward compatibility with 0.24.x,
# but it's also just a good idea.
common_name = name == Puppet::SSL::CA_NAME ? Puppet.settings[:ca_name] : name
csr = OpenSSL::X509::Request.new
csr.version = 0
csr.subject = OpenSSL::X509::Name.new([["CN", common_name]])
csr.public_key = if key.is_a?(OpenSSL::PKey::EC)
# EC#public_key doesn't follow the PKey API,
# see https://github.com/ruby/openssl/issues/29
key
else
key.public_key
end
if options[:csr_attributes]
add_csr_attributes(csr, options[:csr_attributes])
end
if (ext_req_attribute = extension_request_attribute(options))
csr.add_attribute(ext_req_attribute)
end
signer = Puppet::SSL::CertificateSigner.new
signer.sign(csr, key)
raise Puppet::Error, _("CSR sign verification failed; you need to clean the certificate request for %{name} on the server") % { name: name } unless csr.verify(csr.public_key)
@content = csr
# we won't be able to get the digest on jruby
if @content.signature_algorithm
Puppet.info _("Certificate Request fingerprint (%{digest}): %{hex_digest}") % { digest: digest.name, hex_digest: digest.to_hex }
end
@content
end
def ext_value_to_ruby_value(asn1_arr)
# A list of ASN1 types than can't be directly converted to a Ruby type
@non_convertible ||= [OpenSSL::ASN1::EndOfContent,
OpenSSL::ASN1::BitString,
OpenSSL::ASN1::Null,
OpenSSL::ASN1::Enumerated,
OpenSSL::ASN1::UTCTime,
OpenSSL::ASN1::GeneralizedTime,
OpenSSL::ASN1::Sequence,
OpenSSL::ASN1::Set]
begin
# Attempt to decode the extension's DER data located in the original OctetString
asn1_val = OpenSSL::ASN1.decode(asn1_arr.last.value)
rescue OpenSSL::ASN1::ASN1Error
# This is to allow supporting the old-style of not DER encoding trusted facts
return asn1_arr.last.value
end
# If the extension value can not be directly converted to an atomic Ruby
# type, use the original ASN1 value. This is needed to work around a bug
# in Ruby's OpenSSL library which doesn't convert the value of unknown
# extension OIDs properly. See PUP-3560
if @non_convertible.include?(asn1_val.class) then
# Allows OpenSSL to take the ASN1 value and turn it into something Ruby understands
OpenSSL::X509::Extension.new(asn1_arr.first.value, asn1_val.to_der).value
else
asn1_val.value
end
end
# Return the set of extensions requested on this CSR, in a form designed to
# be useful to Ruby: an array of hashes. Which, not coincidentally, you can pass
# successfully to the OpenSSL constructor later, if you want.
#
# @return [Array<Hash{String => String}>] An array of two or three element
# hashes, with key/value pairs for the extension's oid, its value, and
# optionally its critical state.
def request_extensions
raise Puppet::Error, _("CSR needs content to extract fields") unless @content
# Prefer the standard extReq, but accept the Microsoft specific version as
# a fallback, if the standard version isn't found.
attribute = @content.attributes.find { |x| x.oid == "extReq" }
attribute ||= @content.attributes.find { |x| x.oid == "msExtReq" }
return [] unless attribute
extensions = unpack_extension_request(attribute)
index = -1
extensions.map do |ext_values|
index += 1
value = ext_value_to_ruby_value(ext_values)
# OK, turn that into an extension, to unpack the content. Lovely that
# we have to swap the order of arguments to the underlying method, or
# perhaps that the ASN.1 representation chose to pack them in a
# strange order where the optional component comes *earlier* than the
# fixed component in the sequence.
case ext_values.length
when 2
{ "oid" => ext_values[0].value, "value" => value }
when 3
{ "oid" => ext_values[0].value, "value" => value, "critical" => ext_values[1].value }
else
raise Puppet::Error, _("In %{attr}, expected extension record %{index} to have two or three items, but found %{count}") % { attr: attribute.oid, index: index, count: ext_values.length }
end
end
end
def subject_alt_names
@subject_alt_names ||= request_extensions
.select { |x| x["oid"] == "subjectAltName" }
.map { |x| x["value"].split(/\s*,\s*/) }
.flatten
.sort
.uniq
end
# Return all user specified attributes attached to this CSR as a hash. IF an
# OID has a single value it is returned as a string, otherwise all values are
# returned as an array.
#
# The format of CSR attributes is specified in PKCS#10/RFC 2986
#
# @see https://tools.ietf.org/html/rfc2986 "RFC 2986 Certification Request Syntax Specification"
#
# @api public
#
# @return [Hash<String, String>]
def custom_attributes
x509_attributes = @content.attributes.reject do |attr|
PRIVATE_CSR_ATTRIBUTES.include? attr.oid
end
x509_attributes.map do |attr|
{ "oid" => attr.oid, "value" => attr.value.value.first.value }
end
end
private
# Exclude OIDs that may conflict with how Puppet creates CSRs.
#
# We only have nominal support for Microsoft extension requests, but since we
# ultimately respect that field when looking for extension requests in a CSR
# we need to prevent that field from being written to directly.
PRIVATE_CSR_ATTRIBUTES = [
'extReq', '1.2.840.113549.1.9.14',
'msExtReq', '1.3.6.1.4.1.311.2.1.14'
]
def add_csr_attributes(csr, csr_attributes)
csr_attributes.each do |oid, value|
if PRIVATE_CSR_ATTRIBUTES.include? oid
raise ArgumentError, _("Cannot specify CSR attribute %{oid}: conflicts with internally used CSR attribute") % { oid: oid }
end
encoded = OpenSSL::ASN1::PrintableString.new(value.to_s)
attr_set = OpenSSL::ASN1::Set.new([encoded])
csr.add_attribute(OpenSSL::X509::Attribute.new(oid, attr_set))
Puppet.debug("Added csr attribute: #{oid} => #{attr_set.inspect}")
rescue OpenSSL::X509::AttributeError => e
raise Puppet::Error, _("Cannot create CSR with attribute %{oid}: %{message}") % { oid: oid, message: e.message }, e.backtrace
end
end
PRIVATE_EXTENSIONS = [
'subjectAltName', '2.5.29.17'
]
# @api private
def extension_request_attribute(options)
extensions = []
if options[:extension_requests]
options[:extension_requests].each_pair do |oid, value|
if PRIVATE_EXTENSIONS.include? oid
raise Puppet::Error, _("Cannot specify CSR extension request %{oid}: conflicts with internally used extension request") % { oid: oid }
end
ext = OpenSSL::X509::Extension.new(oid, OpenSSL::ASN1::UTF8String.new(value.to_s).to_der, false)
extensions << ext
rescue OpenSSL::X509::ExtensionError => e
raise Puppet::Error, _("Cannot create CSR with extension request %{oid}: %{message}") % { oid: oid, message: e.message }, e.backtrace
end
end
if options[:dns_alt_names]
raw_names = options[:dns_alt_names].split(/\s*,\s*/).map(&:strip) + [name]
parsed_names = raw_names.map do |name|
if !name.start_with?("IP:") && !name.start_with?("DNS:")
"DNS:#{name}"
else
name
end
end.sort.uniq.join(", ")
alt_names_ext = extension_factory.create_extension("subjectAltName", parsed_names, false)
extensions << alt_names_ext
end
unless extensions.empty?
seq = OpenSSL::ASN1::Sequence(extensions)
ext_req = OpenSSL::ASN1::Set([seq])
OpenSSL::X509::Attribute.new("extReq", ext_req)
end
end
# Unpack the extReq attribute into an array of Extensions.
#
# The extension request attribute is structured like
# `Set[Sequence[Extensions]]` where the outer Set only contains a single
# sequence.
#
# In addition the Ruby implementation of ASN1 requires that all ASN1 values
# contain a single value, so Sets and Sequence have to contain an array
# that in turn holds the elements. This is why we have to unpack an array
# every time we unpack a Set/Seq.
#
# @see https://tools.ietf.org/html/rfc2985#ref-10 5.4.2 CSR Extension Request structure
# @see https://tools.ietf.org/html/rfc5280 4.1 Certificate Extension structure
#
# @api private
#
# @param attribute [OpenSSL::X509::Attribute] The X509 extension request
#
# @return [Array<Array<Object>>] A array of arrays containing the extension
# OID the critical state if present, and the extension value.
def unpack_extension_request(attribute)
unless attribute.value.is_a? OpenSSL::ASN1::Set
raise Puppet::Error, _("In %{attr}, expected Set but found %{klass}") % { attr: attribute.oid, klass: attribute.value.class }
end
unless attribute.value.value.is_a? Array
raise Puppet::Error, _("In %{attr}, expected Set[Array] but found %{klass}") % { attr: attribute.oid, klass: attribute.value.value.class }
end
unless attribute.value.value.size == 1
raise Puppet::Error, _("In %{attr}, expected Set[Array] with one value but found %{count} elements") % { attr: attribute.oid, count: attribute.value.value.size }
end
unless attribute.value.value.first.is_a? OpenSSL::ASN1::Sequence
raise Puppet::Error, _("In %{attr}, expected Set[Array[Sequence[...]]], but found %{klass}") % { attr: attribute.oid, klass: extension.class }
end
unless attribute.value.value.first.value.is_a? Array
raise Puppet::Error, _("In %{attr}, expected Set[Array[Sequence[Array[...]]]], but found %{klass}") % { attr: attribute.oid, klass: extension.value.class }
end
extensions = attribute.value.value.first.value
extensions.map(&:value)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/base.rb | lib/puppet/ssl/base.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl/openssl_loader'
require_relative '../../puppet/ssl'
require_relative '../../puppet/ssl/digest'
# The base class for wrapping SSL instances.
class Puppet::SSL::Base
# For now, use the YAML separator.
SEPARATOR = "\n---\n"
# Only allow printing ascii characters, excluding /
VALID_CERTNAME = /\A[ -.0-~]+\Z/
def self.from_multiple_s(text)
text.split(SEPARATOR).collect { |inst| from_s(inst) }
end
def self.to_multiple_s(instances)
instances.collect(&:to_s).join(SEPARATOR)
end
def self.wraps(klass)
@wrapped_class = klass
end
def self.wrapped_class
raise(Puppet::DevError, _("%{name} has not declared what class it wraps") % { name: self }) unless defined?(@wrapped_class)
@wrapped_class
end
def self.validate_certname(name)
raise _("Certname %{name} must not contain unprintable or non-ASCII characters") % { name: name.inspect } unless name =~ VALID_CERTNAME
end
attr_accessor :name, :content
def generate
raise Puppet::DevError, _("%{class_name} did not override 'generate'") % { class_name: self.class }
end
def initialize(name)
@name = name.to_s.downcase
self.class.validate_certname(@name)
end
##
# name_from_subject extracts the common name attribute from the subject of an
# x.509 certificate certificate
#
# @api private
#
# @param [OpenSSL::X509::Name] subject The full subject (distinguished name) of the x.509
# certificate.
#
# @return [String] the name (CN) extracted from the subject.
def self.name_from_subject(subject)
if subject.respond_to? :to_a
(subject.to_a.assoc('CN') || [])[1]
end
end
# Create an instance of our Puppet::SSL::* class using a given instance of the wrapped class
def self.from_instance(instance, name = nil)
unless instance.is_a?(wrapped_class)
raise ArgumentError, _("Object must be an instance of %{class_name}, %{actual_class} given") %
{ class_name: wrapped_class, actual_class: instance.class }
end
if name.nil? and !instance.respond_to?(:subject)
raise ArgumentError, _("Name must be supplied if it cannot be determined from the instance")
end
name ||= name_from_subject(instance.subject)
result = new(name)
result.content = instance
result
end
# Convert a string into an instance
def self.from_s(string, name = nil)
instance = wrapped_class.new(string)
from_instance(instance, name)
end
# Read content from disk appropriately.
def read(path)
# applies to Puppet::SSL::Certificate, Puppet::SSL::CertificateRequest
# nothing derives from Puppet::SSL::Certificate, but it is called by a number of other SSL Indirectors:
# Puppet::Indirector::CertificateStatus::File (.indirection.find)
# Puppet::Network::HTTP::WEBrick (.indirection.find)
# Puppet::Network::HTTP::RackREST (.from_instance)
# Puppet::Network::HTTP::WEBrickREST (.from_instance)
# Puppet::SSL::Inventory (.indirection.search, implements its own add / rebuild / serials with encoding UTF8)
@content = wrapped_class.new(Puppet::FileSystem.read(path, :encoding => Encoding::ASCII))
end
# Convert our thing to pem.
def to_s
return "" unless content
content.to_pem
end
def to_data_hash
to_s
end
# Provide the full text of the thing we're dealing with.
def to_text
return "" unless content
content.to_text
end
def fingerprint(md = :SHA256)
mds = md.to_s.upcase
digest(mds).to_hex
end
def digest(algorithm = nil)
algorithm ||= digest_algorithm
Puppet::SSL::Digest.new(algorithm, content.to_der)
end
def digest_algorithm
# The signature_algorithm on the X509 cert is a combination of the digest
# algorithm and the encryption algorithm
# e.g. md5WithRSAEncryption, sha256WithRSAEncryption
# Unfortunately there isn't a consistent pattern
# See RFCs 3279, 5758
digest_re = Regexp.union(
/ripemd160/i,
/md[245]/i,
/sha\d*/i
)
ln = content.signature_algorithm
match = digest_re.match(ln)
if match
match[0].downcase
else
raise Puppet::Error, _("Unknown signature algorithm '%{ln}'") % { ln: ln }
end
end
private
def wrapped_class
self.class.wrapped_class
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/ssl_provider.rb | lib/puppet/ssl/ssl_provider.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
# SSL Provider creates `SSLContext` objects that can be used to create
# secure connections.
#
# @example To load an SSLContext from an existing private key and related certs/crls:
# ssl_context = provider.load_context
#
# @example To load an SSLContext from an existing password-protected private key and related certs/crls:
# ssl_context = provider.load_context(password: 'opensesame')
#
# @example To create an SSLContext from in-memory certs and keys:
# cacerts = [<OpenSSL::X509::Certificate>]
# crls = [<OpenSSL::X509::CRL>]
# key = <OpenSSL::X509::PKey>
# cert = <OpenSSL::X509::Certificate>
# ssl_context = provider.create_context(cacerts: cacerts, crls: crls, private_key: key, client_cert: cert)
#
# @example To create an SSLContext to connect to non-puppet HTTPS servers:
# cacerts = [<OpenSSL::X509::Certificate>]
# ssl_context = provider.create_root_context(cacerts: cacerts)
#
# @api private
class Puppet::SSL::SSLProvider
# Create an insecure `SSLContext`. Connections made from the returned context
# will not authenticate the server, i.e. `VERIFY_NONE`, and are vulnerable to
# MITM. Do not call this method.
#
# @return [Puppet::SSL::SSLContext] A context to use to create connections
# @api private
def create_insecure_context
store = create_x509_store([], [], false)
Puppet::SSL::SSLContext.new(store: store, verify_peer: false).freeze
end
# Create an `SSLContext` using the trusted `cacerts` and optional `crls`.
# Connections made from the returned context will authenticate the server,
# i.e. `VERIFY_PEER`, but will not use a client certificate.
#
# The `crls` parameter must contain CRLs corresponding to each CA in `cacerts`
# depending on the `revocation` mode. See {#create_context}.
#
# @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs
# @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs
# @param revocation [:chain, :leaf, false] revocation mode
# @return [Puppet::SSL::SSLContext] A context to use to create connections
# @raise (see #create_context)
# @api private
def create_root_context(cacerts:, crls: [], revocation: Puppet[:certificate_revocation])
store = create_x509_store(cacerts, crls, revocation)
Puppet::SSL::SSLContext.new(store: store, cacerts: cacerts, crls: crls, revocation: revocation).freeze
end
# Create an `SSLContext` using the trusted `cacerts` and any certs in OpenSSL's
# default verify path locations. When running puppet as a gem, the location is
# system dependent. When running puppet from puppet-agent packages, the location
# refers to the cacerts bundle in the puppet-agent package.
#
# Connections made from the returned context will authenticate the server,
# i.e. `VERIFY_PEER`, but will not use a client certificate (unless requested)
# and will not perform revocation checking.
#
# @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs
# @param path [String, nil] A file containing additional trusted CA certs.
# @param include_client_cert [true, false] If true, the client cert will be added to the context
# allowing mutual TLS authentication. The default is false. If the client cert doesn't exist
# then the option will be ignored.
# @return [Puppet::SSL::SSLContext] A context to use to create connections
# @raise (see #create_context)
# @api private
def create_system_context(cacerts:, path: Puppet[:ssl_trust_store], include_client_cert: false)
store = create_x509_store(cacerts, [], false, include_system_store: true)
if path
stat = Puppet::FileSystem.stat(path)
if stat
if stat.ftype == 'file'
# don't add empty files as ruby/openssl will raise
if stat.size > 0
begin
store.add_file(path)
rescue => e
Puppet.err(_("Failed to add '%{path}' as a trusted CA file: %{detail}" % { path: path, detail: e.message }, e))
end
end
else
Puppet.warning(_("The 'ssl_trust_store' setting does not refer to a file and will be ignored: '%{path}'" % { path: path }))
end
end
end
if include_client_cert
cert_provider = Puppet::X509::CertProvider.new
private_key = cert_provider.load_private_key(Puppet[:certname], required: false)
unless private_key
msg = "Private key for '#{Puppet[:certname]}' does not exist"
Puppet.run_mode.name == :user ? Puppet.info(msg) : Puppet.warning(msg)
end
client_cert = cert_provider.load_client_cert(Puppet[:certname], required: false)
unless client_cert
msg = "Client certificate for '#{Puppet[:certname]}' does not exist"
Puppet.run_mode.name == :user ? Puppet.info(msg) : Puppet.warning(msg)
end
if private_key && client_cert
client_chain = resolve_client_chain(store, client_cert, private_key)
return Puppet::SSL::SSLContext.new(
store: store, cacerts: cacerts, crls: [],
private_key: private_key, client_cert: client_cert, client_chain: client_chain,
revocation: false
).freeze
end
end
Puppet::SSL::SSLContext.new(store: store, cacerts: cacerts, crls: [], revocation: false).freeze
end
# Create an `SSLContext` using the trusted `cacerts`, `crls`, `private_key`,
# `client_cert`, and `revocation` mode. Connections made from the returned
# context will be mutually authenticated.
#
# The `crls` parameter must contain CRLs corresponding to each CA in `cacerts`
# depending on the `revocation` mode:
#
# * `:chain` - `crls` must contain a CRL for every CA in `cacerts`
# * `:leaf` - `crls` must contain (at least) the CRL for the leaf CA in `cacerts`
# * `false` - `crls` can be empty
#
# The `private_key` and public key from the `client_cert` must match.
#
# @param cacerts [Array<OpenSSL::X509::Certificate>] Array of trusted CA certs
# @param crls [Array<OpenSSL::X509::CRL>] Array of CRLs
# @param private_key [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] client's private key
# @param client_cert [OpenSSL::X509::Certificate] client's cert whose public
# key matches the `private_key`
# @param revocation [:chain, :leaf, false] revocation mode
# @param include_system_store [true, false] Also trust system CA
# @return [Puppet::SSL::SSLContext] A context to use to create connections
# @raise [Puppet::SSL::CertVerifyError] There was an issue with
# one of the certs or CRLs.
# @raise [Puppet::SSL::SSLError] There was an issue with the
# `private_key`.
# @api private
def create_context(cacerts:, crls:, private_key:, client_cert:, revocation: Puppet[:certificate_revocation], include_system_store: false)
raise ArgumentError, _("CA certs are missing") unless cacerts
raise ArgumentError, _("CRLs are missing") unless crls
raise ArgumentError, _("Private key is missing") unless private_key
raise ArgumentError, _("Client cert is missing") unless client_cert
store = create_x509_store(cacerts, crls, revocation, include_system_store: include_system_store)
client_chain = resolve_client_chain(store, client_cert, private_key)
Puppet::SSL::SSLContext.new(
store: store, cacerts: cacerts, crls: crls,
private_key: private_key, client_cert: client_cert, client_chain: client_chain,
revocation: revocation
).freeze
end
# Load an `SSLContext` using available certs and keys. An exception is raised
# if any component is missing or is invalid, such as a mismatched client cert
# and private key. Connections made from the returned context will be mutually
# authenticated.
#
# @param certname [String] Which cert & key to load
# @param revocation [:chain, :leaf, false] revocation mode
# @param password [String, nil] If the private key is encrypted, decrypt
# it using the password. If the key is encrypted, but a password is
# not specified, then the key cannot be loaded.
# @param include_system_store [true, false] Also trust system CA
# @return [Puppet::SSL::SSLContext] A context to use to create connections
# @raise [Puppet::SSL::CertVerifyError] There was an issue with
# one of the certs or CRLs.
# @raise [Puppet::Error] There was an issue with one of the required components.
# @api private
def load_context(certname: Puppet[:certname], revocation: Puppet[:certificate_revocation], password: nil, include_system_store: false)
cert = Puppet::X509::CertProvider.new
cacerts = cert.load_cacerts(required: true)
crls = case revocation
when :chain, :leaf
cert.load_crls(required: true)
else
[]
end
private_key = cert.load_private_key(certname, required: true, password: password)
client_cert = cert.load_client_cert(certname, required: true)
create_context(cacerts: cacerts, crls: crls, private_key: private_key, client_cert: client_cert, revocation: revocation, include_system_store: include_system_store)
rescue OpenSSL::PKey::PKeyError => e
raise Puppet::SSL::SSLError.new(_("Failed to load private key for host '%{name}': %{message}") % { name: certname, message: e.message }, e)
end
# Verify the `csr` was signed with a private key corresponding to the
# `public_key`. This ensures the CSR was signed by someone in possession
# of the private key, and that it hasn't been tampered with since.
#
# @param csr [OpenSSL::X509::Request] certificate signing request
# @param public_key [OpenSSL::PKey::RSA, OpenSSL::PKey::EC] public key
# @raise [Puppet::SSL:SSLError] The private_key for the given `public_key` was
# not used to sign the CSR.
# @api private
def verify_request(csr, public_key)
unless csr.verify(public_key)
raise Puppet::SSL::SSLError, _("The CSR for host '%{name}' does not match the public key") % { name: subject(csr) }
end
csr
end
def print(ssl_context, alg = 'SHA256')
if Puppet::Util::Log.sendlevel?(:debug)
chain = ssl_context.client_chain
# print from root to client
chain.reverse.each_with_index do |cert, i|
digest = Puppet::SSL::Digest.new(alg, cert.to_der)
if i == chain.length - 1
Puppet.debug(_("Verified client certificate '%{subject}' fingerprint %{digest}") % { subject: cert.subject.to_utf8, digest: digest })
else
Puppet.debug(_("Verified CA certificate '%{subject}' fingerprint %{digest}") % { subject: cert.subject.to_utf8, digest: digest })
end
end
ssl_context.crls.each do |crl|
oid_values = crl.extensions.to_h { |ext| [ext.oid, ext.value] }
crlNumber = oid_values['crlNumber'] || 'unknown'
authKeyId = (oid_values['authorityKeyIdentifier'] || 'unknown').chomp
Puppet.debug("Using CRL '#{crl.issuer.to_utf8}' authorityKeyIdentifier '#{authKeyId}' crlNumber '#{crlNumber}'")
end
end
end
private
def default_flags
# checking the signature of the self-signed cert doesn't add any security,
# but it's a sanity check to make sure the cert isn't corrupt. This option
# is not available in JRuby's OpenSSL library.
if defined?(OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE)
OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE
else
0
end
end
def create_x509_store(roots, crls, revocation, include_system_store: false)
store = OpenSSL::X509::Store.new
store.purpose = OpenSSL::X509::PURPOSE_ANY
store.flags = default_flags | revocation_mode(revocation)
roots.each { |cert| store.add_cert(cert) }
crls.each { |crl| store.add_crl(crl) }
store.set_default_paths if include_system_store
store
end
def subject(x509)
x509.subject.to_utf8
end
def issuer(x509)
x509.issuer.to_utf8
end
def revocation_mode(mode)
case mode
when false
0
when :leaf
OpenSSL::X509::V_FLAG_CRL_CHECK
else
# :chain is the default
OpenSSL::X509::V_FLAG_CRL_CHECK | OpenSSL::X509::V_FLAG_CRL_CHECK_ALL
end
end
def resolve_client_chain(store, client_cert, private_key)
client_chain = verify_cert_with_store(store, client_cert)
if !private_key.is_a?(OpenSSL::PKey::RSA) && !private_key.is_a?(OpenSSL::PKey::EC)
raise Puppet::SSL::SSLError, _("Unsupported key '%{type}'") % { type: private_key.class.name }
end
unless client_cert.check_private_key(private_key)
raise Puppet::SSL::SSLError, _("The certificate for '%{name}' does not match its private key") % { name: subject(client_cert) }
end
client_chain
end
def verify_cert_with_store(store, cert)
# StoreContext#initialize accepts a chain argument, but it's set to [] because
# puppet requires any intermediate CA certs needed to complete the client's
# chain to be in the CA bundle that we downloaded from the server, and
# they've already been added to the store. See PUP-9500.
store_context = OpenSSL::X509::StoreContext.new(store, cert, [])
unless store_context.verify
current_cert = store_context.current_cert
# If the client cert's intermediate CA is not in the CA bundle, then warn,
# but don't error, because SSL allows the client to send an incomplete
# chain, and have the server resolve it.
if store_context.error == OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
Puppet.warning _("The issuer '%{issuer}' of certificate '%{subject}' cannot be found locally") % {
issuer: issuer(current_cert), subject: subject(current_cert)
}
else
raise_cert_verify_error(store_context, current_cert)
end
end
# resolved chain from leaf to root
store_context.chain
end
def raise_cert_verify_error(store_context, current_cert)
message =
case store_context.error
when OpenSSL::X509::V_ERR_CERT_NOT_YET_VALID
_("The certificate '%{subject}' is not yet valid, verify time is synchronized") % { subject: subject(current_cert) }
when OpenSSL::X509::V_ERR_CERT_HAS_EXPIRED
_("The certificate '%{subject}' has expired, verify time is synchronized") % { subject: subject(current_cert) }
when OpenSSL::X509::V_ERR_CRL_NOT_YET_VALID
_("The CRL issued by '%{issuer}' is not yet valid, verify time is synchronized") % { issuer: issuer(current_cert) }
when OpenSSL::X509::V_ERR_CRL_HAS_EXPIRED
_("The CRL issued by '%{issuer}' has expired, verify time is synchronized") % { issuer: issuer(current_cert) }
when OpenSSL::X509::V_ERR_CERT_SIGNATURE_FAILURE
_("Invalid signature for certificate '%{subject}'") % { subject: subject(current_cert) }
when OpenSSL::X509::V_ERR_CRL_SIGNATURE_FAILURE
_("Invalid signature for CRL issued by '%{issuer}'") % { issuer: issuer(current_cert) }
when OpenSSL::X509::V_ERR_UNABLE_TO_GET_ISSUER_CERT
_("The issuer '%{issuer}' of certificate '%{subject}' is missing") % {
issuer: issuer(current_cert), subject: subject(current_cert)
}
when OpenSSL::X509::V_ERR_UNABLE_TO_GET_CRL
_("The CRL issued by '%{issuer}' is missing") % { issuer: issuer(current_cert) }
when OpenSSL::X509::V_ERR_CERT_REVOKED
_("Certificate '%{subject}' is revoked") % { subject: subject(current_cert) }
else
# error_string is labeled ASCII-8BIT, but is encoded based on Encoding.default_external
err_utf8 = Puppet::Util::CharacterEncoding.convert_to_utf_8(store_context.error_string)
_("Certificate '%{subject}' failed verification (%{err}): %{err_utf8}") % {
subject: subject(current_cert), err: store_context.error, err_utf8: err_utf8
}
end
raise Puppet::SSL::CertVerifyError.new(message, store_context.error, current_cert)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/openssl_loader.rb | lib/puppet/ssl/openssl_loader.rb | # frozen_string_literal: true
require_relative '../../puppet/util/platform'
# This file should be required instead of writing `require 'openssl'`
# or any library that loads openssl like `net/https`. This allows the
# core Puppet code to load correctly in JRuby environments that do not
# have a functioning openssl (eg a FIPS enabled one).
if Puppet::Util::Platform.jruby_fips?
# Even in JRuby we need to define the constants that are wrapped in
# Indirections: Puppet::SSL::{Key, Certificate, CertificateRequest}
module OpenSSL
module PKey
class RSA; end
end
module X509
class Request; end
class Certificate; end
end
end
else
require 'openssl'
require 'net/https'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/certificate_request_attributes.rb | lib/puppet/ssl/certificate_request_attributes.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
require_relative '../../puppet/util/yaml'
# This class transforms simple key/value pairs into the equivalent ASN1
# structures. Values may be strings or arrays of strings.
#
# @api private
class Puppet::SSL::CertificateRequestAttributes
attr_reader :path, :custom_attributes, :extension_requests
def initialize(path)
@path = path
@custom_attributes = {}
@extension_requests = {}
end
# Attempt to load a yaml file at the given @path.
# @return true if we are able to load the file, false otherwise
# @raise [Puppet::Error] if there are unexpected attribute keys
def load
Puppet.info(_("csr_attributes file loading from %{path}") % { path: path })
if Puppet::FileSystem.exist?(path)
hash = Puppet::Util::Yaml.safe_load_file(path, [Symbol]) || {}
unless hash.is_a?(Hash)
raise Puppet::Error, _("invalid CSR attributes, expected instance of Hash, received instance of %{klass}") % { klass: hash.class }
end
@custom_attributes = hash.delete('custom_attributes') || {}
@extension_requests = hash.delete('extension_requests') || {}
unless hash.keys.empty?
raise Puppet::Error, _("unexpected attributes %{keys} in %{path}") % { keys: hash.keys.inspect, path: @path.inspect }
end
return true
end
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/certificate_signer.rb | lib/puppet/ssl/certificate_signer.rb | # frozen_string_literal: true
# Take care of signing a certificate in a FIPS 140-2 compliant manner.
#
# @see https://projects.puppetlabs.com/issues/17295
#
# @api private
class Puppet::SSL::CertificateSigner
# @!attribute [r] digest
# @return [OpenSSL::Digest]
attr_reader :digest
def initialize
if OpenSSL::Digest.const_defined?('SHA256')
@digest = OpenSSL::Digest::SHA256
elsif OpenSSL::Digest.const_defined?('SHA1')
@digest = OpenSSL::Digest::SHA1
elsif OpenSSL::Digest.const_defined?('SHA512')
@digest = OpenSSL::Digest::SHA512
elsif OpenSSL::Digest.const_defined?('SHA384')
@digest = OpenSSL::Digest::SHA384
elsif OpenSSL::Digest.const_defined?('SHA224')
@digest = OpenSSL::Digest::SHA224
else
raise Puppet::Error,
"No FIPS 140-2 compliant digest algorithm in OpenSSL::Digest"
end
end
# Sign a certificate signing request (CSR) with a private key.
#
# @param [OpenSSL::X509::Request] content The CSR to sign
# @param [OpenSSL::X509::PKey] key The private key to sign with
#
# @api private
def sign(content, key)
content.sign(key, @digest.new)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/error.rb | lib/puppet/ssl/error.rb | # frozen_string_literal: true
module Puppet::SSL
class SSLError < Puppet::Error; end
class CertVerifyError < Puppet::SSL::SSLError
attr_reader :code, :cert
def initialize(message, code, cert)
super(message)
@code = code
@cert = cert
end
end
class CertMismatchError < Puppet::SSL::SSLError
def initialize(peer_cert, host)
valid_certnames = [peer_cert.subject.to_utf8.sub(/.*=/, ''),
*Puppet::SSL::Certificate.subject_alt_names_for(peer_cert)].uniq
if valid_certnames.size > 1
expected_certnames = _("expected one of %{certnames}") % { certnames: valid_certnames.join(', ') }
else
expected_certnames = _("expected %{certname}") % { certname: valid_certnames.first }
end
super(_("Server hostname '%{host}' did not match server certificate; %{expected_certnames}") % { host: host, expected_certnames: expected_certnames })
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/certificate.rb | lib/puppet/ssl/certificate.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl/base'
# Manage certificates themselves. This class has no
# 'generate' method because the CA is responsible
# for turning CSRs into certificates; we can only
# retrieve them from the CA (or not, as is often
# the case).
#
# @deprecated Use {Puppet::SSL::SSLProvider} instead.
class Puppet::SSL::Certificate < Puppet::SSL::Base
# This is defined from the base class
wraps OpenSSL::X509::Certificate
# Because of how the format handler class is included, this
# can't be in the base class.
def self.supported_formats
[:s]
end
def self.subject_alt_names_for(cert)
alts = cert.extensions.find { |ext| ext.oid == "subjectAltName" }
return [] unless alts
alts.value.split(/\s*,\s*/)
end
def subject_alt_names
self.class.subject_alt_names_for(content)
end
def expiration
return nil unless content
content.not_after
end
# This name is what gets extracted from the subject before being passed
# to the constructor, so it's not downcased
def unmunged_name
self.class.name_from_subject(content.subject.to_utf8)
end
# Any extensions registered with custom OIDs as defined in module
# Puppet::SSL::Oids may be looked up here.
#
# A cert with a 'pp_uuid' extension having the value 'abcd' would return:
#
# [{ 'oid' => 'pp_uuid', 'value' => 'abcd'}]
#
# @return [Array<Hash{String => String}>] An array of two element hashes,
# with key/value pairs for the extension's oid, and its value.
def custom_extensions
custom_exts = content.extensions.select do |ext|
Puppet::SSL::Oids.subtree_of?('ppRegCertExt', ext.oid) or
Puppet::SSL::Oids.subtree_of?('ppPrivCertExt', ext.oid) or
Puppet::SSL::Oids.subtree_of?('ppAuthCertExt', ext.oid)
end
custom_exts.map do |ext|
{ 'oid' => ext.oid, 'value' => get_ext_val(ext.oid) }
end
end
private
# Extract the extensions sequence from the wrapped certificate's raw ASN.1 form
def exts_seq
# See RFC-2459 section 4.1 (https://tools.ietf.org/html/rfc2459#section-4.1)
# to see where this is defined. Essentially this is saying "in the first
# sequence in the certificate, find the item that's tagged with 3. This
# is where the extensions are stored."
@extensions_tag ||= 3
@exts_seq ||= OpenSSL::ASN1.decode(content.to_der).value[0].value.find do |data|
(data.tag == @extensions_tag) && (data.tag_class == :CONTEXT_SPECIFIC)
end.value[0]
end
# Get the DER parsed value of an X.509 extension by it's OID, or short name
# if one has been registered with OpenSSL.
def get_ext_val(oid)
ext_obj = exts_seq.value.find do |ext_seq|
ext_seq.value[0].value == oid
end
raw_val = ext_obj.value.last.value
begin
OpenSSL::ASN1.decode(raw_val).value
rescue OpenSSL::ASN1::ASN1Error
# This is required to maintain backward compatibility with the previous
# way trusted facts were signed. See PUP-3560
raw_val
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ssl/oids.rb | lib/puppet/ssl/oids.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl'
# This module defines OIDs for use within Puppet.
#
# # ASN.1 Definition
#
# The following is the formal definition of OIDs specified in this file.
#
# ```
# puppetCertExtensions OBJECT IDENTIFIER ::= {iso(1) identified-organization(3)
# dod(6) internet(1) private(4) enterprise(1) 34380 1}
#
# -- the tree under registeredExtensions 'belongs' to puppetlabs
# -- privateExtensions can be extended by enterprises to suit their own needs
# registeredExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 1 }
# privateExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 2 }
# authorizationExtensions OBJECT IDENTIFIER ::= { puppetCertExtensions 3 }
#
# -- subtree of common registered extensions
# -- The short names for these OIDs are intentionally lowercased and formatted
# -- since they may be exposed inside the Puppet DSL as variables.
# pp_uuid OBJECT IDENTIFIER ::= { registeredExtensions 1 }
# pp_instance_id OBJECT IDENTIFIER ::= { registeredExtensions 2 }
# pp_image_name OBJECT IDENTIFIER ::= { registeredExtensions 3 }
# pp_preshared_key OBJECT IDENTIFIER ::= { registeredExtensions 4 }
# ```
#
# @api private
module Puppet::SSL::Oids
# Note: When updating the following OIDs make sure to also update the OID
# definitions here:
# https://github.com/puppetlabs/puppetserver/blob/master/src/clj/puppetlabs/puppetserver/certificate_authority.clj#L122-L159
PUPPET_OIDS = [
["1.3.6.1.4.1.34380", 'puppetlabs', 'Puppet Labs'],
["1.3.6.1.4.1.34380.1", 'ppCertExt', 'Puppet Certificate Extension'],
["1.3.6.1.4.1.34380.1.1", 'ppRegCertExt', 'Puppet Registered Certificate Extension'],
["1.3.6.1.4.1.34380.1.1.1", 'pp_uuid', 'Puppet Node UUID'],
["1.3.6.1.4.1.34380.1.1.2", 'pp_instance_id', 'Puppet Node Instance ID'],
["1.3.6.1.4.1.34380.1.1.3", 'pp_image_name', 'Puppet Node Image Name'],
["1.3.6.1.4.1.34380.1.1.4", 'pp_preshared_key', 'Puppet Node Preshared Key'],
["1.3.6.1.4.1.34380.1.1.5", 'pp_cost_center', 'Puppet Node Cost Center Name'],
["1.3.6.1.4.1.34380.1.1.6", 'pp_product', 'Puppet Node Product Name'],
["1.3.6.1.4.1.34380.1.1.7", 'pp_project', 'Puppet Node Project Name'],
["1.3.6.1.4.1.34380.1.1.8", 'pp_application', 'Puppet Node Application Name'],
["1.3.6.1.4.1.34380.1.1.9", 'pp_service', 'Puppet Node Service Name'],
["1.3.6.1.4.1.34380.1.1.10", 'pp_employee', 'Puppet Node Employee Name'],
["1.3.6.1.4.1.34380.1.1.11", 'pp_created_by', 'Puppet Node created_by Tag'],
["1.3.6.1.4.1.34380.1.1.12", 'pp_environment', 'Puppet Node Environment Name'],
["1.3.6.1.4.1.34380.1.1.13", 'pp_role', 'Puppet Node Role Name'],
["1.3.6.1.4.1.34380.1.1.14", 'pp_software_version', 'Puppet Node Software Version'],
["1.3.6.1.4.1.34380.1.1.15", 'pp_department', 'Puppet Node Department Name'],
["1.3.6.1.4.1.34380.1.1.16", 'pp_cluster', 'Puppet Node Cluster Name'],
["1.3.6.1.4.1.34380.1.1.17", 'pp_provisioner', 'Puppet Node Provisioner Name'],
["1.3.6.1.4.1.34380.1.1.18", 'pp_region', 'Puppet Node Region Name'],
["1.3.6.1.4.1.34380.1.1.19", 'pp_datacenter', 'Puppet Node Datacenter Name'],
["1.3.6.1.4.1.34380.1.1.20", 'pp_zone', 'Puppet Node Zone Name'],
["1.3.6.1.4.1.34380.1.1.21", 'pp_network', 'Puppet Node Network Name'],
["1.3.6.1.4.1.34380.1.1.22", 'pp_securitypolicy', 'Puppet Node Security Policy Name'],
["1.3.6.1.4.1.34380.1.1.23", 'pp_cloudplatform', 'Puppet Node Cloud Platform Name'],
["1.3.6.1.4.1.34380.1.1.24", 'pp_apptier', 'Puppet Node Application Tier'],
["1.3.6.1.4.1.34380.1.1.25", 'pp_hostname', 'Puppet Node Hostname'],
["1.3.6.1.4.1.34380.1.1.26", 'pp_owner', 'Puppet Node Owner'],
["1.3.6.1.4.1.34380.1.2", 'ppPrivCertExt', 'Puppet Private Certificate Extension'],
["1.3.6.1.4.1.34380.1.3", 'ppAuthCertExt', 'Puppet Certificate Authorization Extension'],
["1.3.6.1.4.1.34380.1.3.1", 'pp_authorization', 'Certificate Extension Authorization'],
["1.3.6.1.4.1.34380.1.3.2", 'pp_auth_auto_renew', 'Auto-Renew Certificate Attribute'],
["1.3.6.1.4.1.34380.1.3.13", 'pp_auth_role', 'Puppet Node Role Name for Authorization'],
["1.3.6.1.4.1.34380.1.3.39", 'pp_cli_auth', 'Puppetserver CA CLI Authorization']
]
@did_register_puppet_oids = false
# Register our custom Puppet OIDs with OpenSSL so they can be used as CSR
# extensions. Without registering these OIDs, OpenSSL will fail when it
# encounters such an extension in a CSR.
def self.register_puppet_oids
unless @did_register_puppet_oids
PUPPET_OIDS.each do |oid_defn|
OpenSSL::ASN1::ObjectId.register(*oid_defn)
end
@did_register_puppet_oids = true
end
end
# Parse custom OID mapping file that enables custom OIDs to be resolved
# into user-friendly names.
#
# @param custom_oid_file [String] File to obtain custom OIDs mapping from
# @param map_key [String] Hash key in which custom OIDs mapping is stored
#
# @example Custom OID mapping file
# ---
# oid_mapping:
# '1.3.6.1.4.1.34380.1.2.1.1':
# shortname : 'myshortname'
# longname : 'Long name'
# '1.3.6.1.4.1.34380.1.2.1.2':
# shortname: 'myothershortname'
# longname: 'Other Long name'
def self.parse_custom_oid_file(custom_oid_file, map_key = 'oid_mapping')
if File.exist?(custom_oid_file) && File.readable?(custom_oid_file)
mapping = nil
begin
mapping = Puppet::Util::Yaml.safe_load_file(custom_oid_file, [Symbol])
rescue => err
raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': %{err}") % { custom_oid_file: custom_oid_file, err: err }, err.backtrace
end
unless mapping.has_key?(map_key)
raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': no such index '%{map_key}'") % { custom_oid_file: custom_oid_file, map_key: map_key }
end
unless mapping[map_key].is_a?(Hash)
raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': data under index '%{map_key}' must be a Hash") % { custom_oid_file: custom_oid_file, map_key: map_key }
end
oid_defns = []
mapping[map_key].keys.each do |oid|
shortname, longname = mapping[map_key][oid].values_at("shortname", "longname")
if shortname.nil? || longname.nil?
raise Puppet::Error, _("Error loading ssl custom OIDs mapping file from '%{custom_oid_file}': incomplete definition of oid '%{oid}'") % { custom_oid_file: custom_oid_file, oid: oid }
end
oid_defns << [oid, shortname, longname]
end
oid_defns
end
end
# Load custom OID mapping file that enables custom OIDs to be resolved
# into user-friendly names.
#
# @param custom_oid_file [String] File to obtain custom OIDs mapping from
# @param map_key [String] Hash key in which custom OIDs mapping is stored
#
# @example Custom OID mapping file
# ---
# oid_mapping:
# '1.3.6.1.4.1.34380.1.2.1.1':
# shortname : 'myshortname'
# longname : 'Long name'
# '1.3.6.1.4.1.34380.1.2.1.2':
# shortname: 'myothershortname'
# longname: 'Other Long name'
def self.load_custom_oid_file(custom_oid_file, map_key = 'oid_mapping')
oid_defns = parse_custom_oid_file(custom_oid_file, map_key)
unless oid_defns.nil?
begin
oid_defns.each do |oid_defn|
OpenSSL::ASN1::ObjectId.register(*oid_defn)
end
rescue => err
raise ArgumentError, _("Error registering ssl custom OIDs mapping from file '%{custom_oid_file}': %{err}") % { custom_oid_file: custom_oid_file, err: err }, err.backtrace
end
end
end
# Determine if the first OID contains the second OID
#
# @param first [String] The containing OID, in dotted form or as the short name
# @param second [String] The contained OID, in dotted form or as the short name
# @param exclusive [true, false] If an OID should not be considered as a subtree of itself
#
# @example Comparing two dotted OIDs
# Puppet::SSL::Oids.subtree_of?('1.3.6.1', '1.3.6.1.4.1') #=> true
# Puppet::SSL::Oids.subtree_of?('1.3.6.1', '1.3.6') #=> false
#
# @example Comparing an OID short name with a dotted OID
# Puppet::SSL::Oids.subtree_of?('IANA', '1.3.6.1.4.1') #=> true
# Puppet::SSL::Oids.subtree_of?('1.3.6.1', 'enterprises') #=> true
#
# @example Comparing an OID against itself
# Puppet::SSL::Oids.subtree_of?('IANA', 'IANA') #=> true
# Puppet::SSL::Oids.subtree_of?('IANA', 'IANA', true) #=> false
#
# @return [true, false]
def self.subtree_of?(first, second, exclusive = false)
first_oid = OpenSSL::ASN1::ObjectId.new(first).oid
second_oid = OpenSSL::ASN1::ObjectId.new(second).oid
if exclusive and first_oid == second_oid
false
else
second_oid.index(first_oid) == 0
end
rescue OpenSSL::ASN1::ASN1Error, TypeError
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/posix.rb | lib/puppet/ffi/posix.rb | # frozen_string_literal: true
require 'ffi'
module Puppet
module FFI
module POSIX
require_relative 'posix/functions'
require_relative 'posix/constants'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/windows.rb | lib/puppet/ffi/windows.rb | # frozen_string_literal: true
require 'ffi'
module Puppet
module FFI
module Windows
require_relative 'windows/api_types'
require_relative 'windows/constants'
require_relative 'windows/structs'
require_relative 'windows/functions'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/posix/constants.rb | lib/puppet/ffi/posix/constants.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/posix'
module Puppet::FFI::POSIX
module Constants
extend FFI::Library
# Maximum number of supplementary groups (groups
# that a user can be in plus its primary group)
# (64 + 1 primary group)
# Chosen a reasonable middle number from the list
# https://www.j3e.de/ngroups.html
MAXIMUM_NUMBER_OF_GROUPS = 65
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/posix/functions.rb | lib/puppet/ffi/posix/functions.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/posix'
module Puppet::FFI::POSIX
module Functions
extend FFI::Library
ffi_convention :stdcall
# https://man7.org/linux/man-pages/man3/getgrouplist.3.html
# int getgrouplist (
# const char *user,
# gid_t group,
# gid_t *groups,
# int *ngroups
# );
begin
ffi_lib FFI::Library::LIBC
attach_function :getgrouplist, [:string, :uint, :pointer, :pointer], :int
rescue FFI::NotFoundError
# Do nothing
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/windows/api_types.rb | lib/puppet/ffi/windows/api_types.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
require_relative '../../../puppet/util/windows/string'
module Puppet::FFI::Windows
module APITypes
module ::FFI
WIN32_FALSE = 0
# standard Win32 error codes
ERROR_SUCCESS = 0
end
module ::FFI::Library
# Wrapper method for attach_function + private
def attach_function_private(*args)
attach_function(*args)
private args[0]
end
end
class ::FFI::Pointer
NULL_HANDLE = 0
WCHAR_NULL = String.new("\0\0").force_encoding('UTF-16LE').freeze
def self.from_string_to_wide_string(str, &block)
str = Puppet::Util::Windows::String.wide_string(str)
FFI::MemoryPointer.from_wide_string(str, &block)
# ptr has already had free called, so nothing to return
nil
end
def read_win32_bool
# BOOL is always a 32-bit integer in Win32
# some Win32 APIs return 1 for true, while others are non-0
read_int32 != FFI::WIN32_FALSE
end
alias_method :read_dword, :read_uint32
alias_method :read_win32_ulong, :read_uint32
alias_method :read_qword, :read_uint64
alias_method :read_hresult, :read_int32
def read_handle
type_size == 4 ? read_uint32 : read_uint64
end
alias_method :read_wchar, :read_uint16
alias_method :read_word, :read_uint16
alias_method :read_array_of_wchar, :read_array_of_uint16
def read_wide_string(char_length, dst_encoding = Encoding::UTF_8, strip = false, encode_options = {})
# char_length is number of wide chars (typically excluding NULLs), *not* bytes
str = get_bytes(0, char_length * 2).force_encoding('UTF-16LE')
if strip
i = str.index(WCHAR_NULL)
str = str[0, i] if i
end
str.encode(dst_encoding, str.encoding, **encode_options)
rescue EncodingError => e
Puppet.debug { "Unable to convert value #{str.nil? ? 'nil' : str.dump} to encoding #{dst_encoding} due to #{e.inspect}" }
raise
end
# @param max_char_length [Integer] Maximum number of wide chars to return (typically excluding NULLs), *not* bytes
# @param null_terminator [Symbol] Number of number of null wchar characters, *not* bytes, that determine the end of the string
# null_terminator = :single_null, then the terminating sequence is two bytes of zero. This is UNIT16 = 0
# null_terminator = :double_null, then the terminating sequence is four bytes of zero. This is UNIT32 = 0
# @param encode_options [Hash] Accepts the same option hash that may be passed to String#encode in Ruby
def read_arbitrary_wide_string_up_to(max_char_length = 512, null_terminator = :single_null, encode_options = {})
idx = case null_terminator
when :single_null
# find index of wide null between 0 and max (exclusive)
(0...max_char_length).find do |i|
get_uint16(i * 2) == 0
end
when :double_null
# find index of double-wide null between 0 and max - 1 (exclusive)
(0...max_char_length - 1).find do |i|
get_uint32(i * 2) == 0
end
else
raise _("Unable to read wide strings with %{null_terminator} terminal nulls") % { null_terminator: null_terminator }
end
read_wide_string(idx || max_char_length, Encoding::UTF_8, false, encode_options)
end
def read_win32_local_pointer(&block)
ptr = read_pointer
begin
yield ptr
ensure
if !ptr.null? && FFI::WIN32::LocalFree(ptr.address) != FFI::Pointer::NULL_HANDLE
Puppet.debug "LocalFree memory leak"
end
end
# ptr has already had LocalFree called, so nothing to return
nil
end
def read_com_memory_pointer(&block)
ptr = read_pointer
begin
yield ptr
ensure
FFI::WIN32::CoTaskMemFree(ptr) unless ptr.null?
end
# ptr has already had CoTaskMemFree called, so nothing to return
nil
end
alias_method :write_dword, :write_uint32
alias_method :write_word, :write_uint16
end
class FFI::MemoryPointer
# Return a MemoryPointer that points to wide string. This is analogous to the
# FFI::MemoryPointer.from_string method.
def self.from_wide_string(wstr)
ptr = FFI::MemoryPointer.new(:uchar, wstr.bytesize + 2)
ptr.put_array_of_uchar(0, wstr.bytes.to_a)
ptr.put_uint16(wstr.bytesize, 0)
yield ptr if block_given?
ptr
end
end
# FFI Types
# https://github.com/ffi/ffi/wiki/Types
# Windows - Common Data Types
# https://msdn.microsoft.com/en-us/library/cc230309.aspx
# Windows Data Types
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751(v=vs.85).aspx
FFI.typedef :uint16, :word
FFI.typedef :uint32, :dword
# uintptr_t is defined in an FFI conf as platform specific, either
# ulong_long on x64 or just ulong on x86
FFI.typedef :uintptr_t, :handle
FFI.typedef :uintptr_t, :hwnd
# buffer_inout is similar to pointer (platform specific), but optimized for buffers
FFI.typedef :buffer_inout, :lpwstr
# buffer_in is similar to pointer (platform specific), but optimized for CONST read only buffers
FFI.typedef :buffer_in, :lpcwstr
FFI.typedef :buffer_in, :lpcolestr
# string is also similar to pointer, but should be used for const char *
# NOTE that this is not wide, useful only for A suffixed functions
FFI.typedef :string, :lpcstr
# pointer in FFI is platform specific
# NOTE: for API calls with reserved lpvoid parameters, pass a FFI::Pointer::NULL
FFI.typedef :pointer, :lpcvoid
FFI.typedef :pointer, :lpvoid
FFI.typedef :pointer, :lpword
FFI.typedef :pointer, :lpbyte
FFI.typedef :pointer, :lpdword
FFI.typedef :pointer, :pdword
FFI.typedef :pointer, :phandle
FFI.typedef :pointer, :ulong_ptr
FFI.typedef :pointer, :pbool
FFI.typedef :pointer, :lpunknown
# any time LONG / ULONG is in a win32 API definition DO NOT USE platform specific width
# which is what FFI uses by default
# instead create new aliases for these very special cases
# NOTE: not a good idea to redefine FFI :ulong since other typedefs may rely on it
FFI.typedef :uint32, :win32_ulong
FFI.typedef :int32, :win32_long
# FFI bool can be only 1 byte at times,
# Win32 BOOL is a signed int, and is always 4 bytes, even on x64
# https://blogs.msdn.com/b/oldnewthing/archive/2011/03/28/10146459.aspx
FFI.typedef :int32, :win32_bool
# BOOLEAN (unlike BOOL) is a BYTE - typedef unsigned char BYTE;
FFI.typedef :uchar, :boolean
# Same as a LONG, a 32-bit signed integer
FFI.typedef :int32, :hresult
# NOTE: FFI already defines (u)short as a 16-bit (un)signed like this:
# FFI.typedef :uint16, :ushort
# FFI.typedef :int16, :short
# 8 bits per byte
FFI.typedef :uchar, :byte
FFI.typedef :uint16, :wchar
# Definitions for data types used in LSA structures and functions
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/
# https://docs.microsoft.com/sr-latn-rs/windows/win32/secmgmt/management-data-types
FFI.typedef :pointer, :pwstr
FFI.typedef :pointer, :pulong
FFI.typedef :pointer, :lsa_handle
FFI.typedef :pointer, :plsa_handle
FFI.typedef :pointer, :psid
FFI.typedef :pointer, :pvoid
FFI.typedef :pointer, :plsa_unicode_string
FFI.typedef :pointer, :plsa_object_attributes
FFI.typedef :uint32, :ntstatus
FFI.typedef :dword, :access_mask
module ::FFI::WIN32
extend ::FFI::Library
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa373931(v=vs.85).aspx
# typedef struct _GUID {
# DWORD Data1;
# WORD Data2;
# WORD Data3;
# BYTE Data4[8];
# } GUID;
class GUID < FFI::Struct
layout :Data1, :dword,
:Data2, :word,
:Data3, :word,
:Data4, [:byte, 8]
def self.[](s)
raise _('Bad GUID format.') unless s =~ /^[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/i
new.tap do |guid|
guid[:Data1] = s[0, 8].to_i(16)
guid[:Data2] = s[9, 4].to_i(16)
guid[:Data3] = s[14, 4].to_i(16)
guid[:Data4][0] = s[19, 2].to_i(16)
guid[:Data4][1] = s[21, 2].to_i(16)
s[24, 12].split('').each_slice(2).with_index do |a, i|
guid[:Data4][i + 2] = a.join('').to_i(16)
end
end
end
def ==(other) Windows.memcmp(other, self, size) == 0 end
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
# typedef struct _SYSTEMTIME {
# WORD wYear;
# WORD wMonth;
# WORD wDayOfWeek;
# WORD wDay;
# WORD wHour;
# WORD wMinute;
# WORD wSecond;
# WORD wMilliseconds;
# } SYSTEMTIME, *PSYSTEMTIME;
class SYSTEMTIME < FFI::Struct
layout :wYear, :word,
:wMonth, :word,
:wDayOfWeek, :word,
:wDay, :word,
:wHour, :word,
:wMinute, :word,
:wSecond, :word,
:wMilliseconds, :word
def to_local_time
Time.local(self[:wYear], self[:wMonth], self[:wDay],
self[:wHour], self[:wMinute], self[:wSecond], self[:wMilliseconds] * 1000)
end
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284(v=vs.85).aspx
# Contains a 64-bit value representing the number of 100-nanosecond
# intervals since January 1, 1601 (UTC).
# typedef struct _FILETIME {
# DWORD dwLowDateTime;
# DWORD dwHighDateTime;
# } FILETIME, *PFILETIME;
class FILETIME < FFI::Struct
layout :dwLowDateTime, :dword,
:dwHighDateTime, :dword
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa366730(v=vs.85).aspx
# HLOCAL WINAPI LocalFree(
# _In_ HLOCAL hMem
# );
ffi_lib :kernel32
attach_function :LocalFree, [:handle], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx
# BOOL WINAPI CloseHandle(
# _In_ HANDLE hObject
# );
ffi_lib :kernel32
attach_function_private :CloseHandle, [:handle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms680722(v=vs.85).aspx
# void CoTaskMemFree(
# _In_opt_ LPVOID pv
# );
ffi_lib :ole32
attach_function :CoTaskMemFree, [:lpvoid], :void
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/windows/constants.rb | lib/puppet/ffi/windows/constants.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::FFI::Windows
module Constants
extend FFI::Library
FILE_ATTRIBUTE_READONLY = 0x00000001
FILE_ATTRIBUTE_DIRECTORY = 0x00000010
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379607(v=vs.85).aspx
# The right to use the object for synchronization. This enables a thread to
# wait until the object is in the signaled state. Some object types do not
# support this access right.
SYNCHRONIZE = 0x100000
# The right to delete the object.
DELETE = 0x00010000
# The right to read the information in the object's security descriptor, not including the information in the system access control list (SACL).
# READ_CONTROL = 0x00020000
# The right to modify the discretionary access control list (DACL) in the object's security descriptor.
WRITE_DAC = 0x00040000
# The right to change the owner in the object's security descriptor.
WRITE_OWNER = 0x00080000
# Combines DELETE, READ_CONTROL, WRITE_DAC, and WRITE_OWNER access.
STANDARD_RIGHTS_REQUIRED = 0xf0000
# Currently defined to equal READ_CONTROL.
STANDARD_RIGHTS_READ = 0x20000
# Currently defined to equal READ_CONTROL.
STANDARD_RIGHTS_WRITE = 0x20000
# Currently defined to equal READ_CONTROL.
STANDARD_RIGHTS_EXECUTE = 0x20000
# Combines DELETE, READ_CONTROL, WRITE_DAC, WRITE_OWNER, and SYNCHRONIZE access.
STANDARD_RIGHTS_ALL = 0x1F0000
SPECIFIC_RIGHTS_ALL = 0xFFFF
FILE_READ_DATA = 1
FILE_WRITE_DATA = 2
FILE_APPEND_DATA = 4
FILE_READ_EA = 8
FILE_WRITE_EA = 16
FILE_EXECUTE = 32
FILE_DELETE_CHILD = 64
FILE_READ_ATTRIBUTES = 128
FILE_WRITE_ATTRIBUTES = 256
FILE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1FF
FILE_GENERIC_READ =
STANDARD_RIGHTS_READ |
FILE_READ_DATA |
FILE_READ_ATTRIBUTES |
FILE_READ_EA |
SYNCHRONIZE
FILE_GENERIC_WRITE =
STANDARD_RIGHTS_WRITE |
FILE_WRITE_DATA |
FILE_WRITE_ATTRIBUTES |
FILE_WRITE_EA |
FILE_APPEND_DATA |
SYNCHRONIZE
FILE_GENERIC_EXECUTE =
STANDARD_RIGHTS_EXECUTE |
FILE_READ_ATTRIBUTES |
FILE_EXECUTE |
SYNCHRONIZE
REPLACEFILE_WRITE_THROUGH = 0x1
REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2
REPLACEFILE_IGNORE_ACL_ERRORS = 0x3
INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF # define INVALID_FILE_ATTRIBUTES (DWORD (-1))
IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
IO_REPARSE_TAG_HSM = 0xC0000004
IO_REPARSE_TAG_HSM2 = 0x80000006
IO_REPARSE_TAG_SIS = 0x80000007
IO_REPARSE_TAG_WIM = 0x80000008
IO_REPARSE_TAG_CSV = 0x80000009
IO_REPARSE_TAG_DFS = 0x8000000A
IO_REPARSE_TAG_SYMLINK = 0xA000000C
IO_REPARSE_TAG_DFSR = 0x80000012
IO_REPARSE_TAG_DEDUP = 0x80000013
IO_REPARSE_TAG_NFS = 0x80000014
FILE_ATTRIBUTE_REPARSE_POINT = 0x400
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
GENERIC_EXECUTE = 0x20000000
GENERIC_ALL = 0x10000000
METHOD_BUFFERED = 0
FILE_SHARE_READ = 1
FILE_SHARE_WRITE = 2
OPEN_EXISTING = 3
FILE_DEVICE_FILE_SYSTEM = 0x00000009
FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
SHGFI_DISPLAYNAME = 0x000000200
SHGFI_PIDL = 0x000000008
ERROR_FILE_NOT_FOUND = 2
ERROR_PATH_NOT_FOUND = 3
ERROR_ALREADY_EXISTS = 183
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa364571(v=vs.85).aspx
FSCTL_GET_REPARSE_POINT = 0x900a8
MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16_384
# Priority constants
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setpriorityclass
ABOVE_NORMAL_PRIORITY_CLASS = 0x0008000
BELOW_NORMAL_PRIORITY_CLASS = 0x0004000
HIGH_PRIORITY_CLASS = 0x0000080
IDLE_PRIORITY_CLASS = 0x0000040
NORMAL_PRIORITY_CLASS = 0x0000020
REALTIME_PRIORITY_CLASS = 0x0000010
# Process Access Rights
# https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights
PROCESS_TERMINATE = 0x00000001
PROCESS_SET_INFORMATION = 0x00000200
PROCESS_QUERY_INFORMATION = 0x00000400
PROCESS_ALL_ACCESS = 0x001F0FFF
PROCESS_VM_READ = 0x00000010
# Process creation flags
# https://docs.microsoft.com/en-us/windows/win32/procthread/process-creation-flags
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NEW_CONSOLE = 0x00000010
CREATE_NEW_PROCESS_GROUP = 0x00000200
CREATE_NO_WINDOW = 0x08000000
CREATE_PROTECTED_PROCESS = 0x00040000
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000
CREATE_SEPARATE_WOW_VDM = 0x00000800
CREATE_SHARED_WOW_VDM = 0x00001000
CREATE_SUSPENDED = 0x00000004
CREATE_UNICODE_ENVIRONMENT = 0x00000400
DEBUG_ONLY_THIS_PROCESS = 0x00000002
DEBUG_PROCESS = 0x00000001
DETACHED_PROCESS = 0x00000008
INHERIT_PARENT_AFFINITY = 0x00010000
# Logon options
LOGON_WITH_PROFILE = 0x00000001
# STARTUPINFOA constants
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa
STARTF_USESTDHANDLES = 0x00000100
# Miscellaneous
HANDLE_FLAG_INHERIT = 0x00000001
SEM_FAILCRITICALERRORS = 0x00000001
SEM_NOGPFAULTERRORBOX = 0x00000002
# Error constants
INVALID_HANDLE_VALUE = FFI::Pointer.new(-1).address
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379626(v=vs.85).aspx
TOKEN_INFORMATION_CLASS = enum(
:TokenUser, 1,
:TokenGroups,
:TokenPrivileges,
:TokenOwner,
:TokenPrimaryGroup,
:TokenDefaultDacl,
:TokenSource,
:TokenType,
:TokenImpersonationLevel,
:TokenStatistics,
:TokenRestrictedSids,
:TokenSessionId,
:TokenGroupsAndPrivileges,
:TokenSessionReference,
:TokenSandBoxInert,
:TokenAuditPolicy,
:TokenOrigin,
:TokenElevationType,
:TokenLinkedToken,
:TokenElevation,
:TokenHasRestrictions,
:TokenAccessInformation,
:TokenVirtualizationAllowed,
:TokenVirtualizationEnabled,
:TokenIntegrityLevel,
:TokenUIAccess,
:TokenMandatoryPolicy,
:TokenLogonSid,
:TokenIsAppContainer,
:TokenCapabilities,
:TokenAppContainerSid,
:TokenAppContainerNumber,
:TokenUserClaimAttributes,
:TokenDeviceClaimAttributes,
:TokenRestrictedUserClaimAttributes,
:TokenRestrictedDeviceClaimAttributes,
:TokenDeviceGroups,
:TokenRestrictedDeviceGroups,
:TokenSecurityAttributes,
:TokenIsRestricted,
:MaxTokenInfoClass
)
# Service error codes
# https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes--1000-1299-
ERROR_SERVICE_DOES_NOT_EXIST = 0x00000424
# Service control codes
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-controlserviceexw
SERVICE_CONTROL_STOP = 0x00000001
SERVICE_CONTROL_PAUSE = 0x00000002
SERVICE_CONTROL_CONTINUE = 0x00000003
SERVICE_CONTROL_INTERROGATE = 0x00000004
SERVICE_CONTROL_SHUTDOWN = 0x00000005
SERVICE_CONTROL_PARAMCHANGE = 0x00000006
SERVICE_CONTROL_NETBINDADD = 0x00000007
SERVICE_CONTROL_NETBINDREMOVE = 0x00000008
SERVICE_CONTROL_NETBINDENABLE = 0x00000009
SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A
SERVICE_CONTROL_DEVICEEVENT = 0x0000000B
SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C
SERVICE_CONTROL_POWEREVENT = 0x0000000D
SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E
SERVICE_CONTROL_PRESHUTDOWN = 0x0000000F
SERVICE_CONTROL_TIMECHANGE = 0x00000010
SERVICE_CONTROL_TRIGGEREVENT = 0x00000020
SERVICE_CONTROL_SIGNALS = {
SERVICE_CONTROL_STOP => :SERVICE_CONTROL_STOP,
SERVICE_CONTROL_PAUSE => :SERVICE_CONTROL_PAUSE,
SERVICE_CONTROL_CONTINUE => :SERVICE_CONTROL_CONTINUE,
SERVICE_CONTROL_INTERROGATE => :SERVICE_CONTROL_INTERROGATE,
SERVICE_CONTROL_SHUTDOWN => :SERVICE_CONTROL_SHUTDOWN,
SERVICE_CONTROL_PARAMCHANGE => :SERVICE_CONTROL_PARAMCHANGE,
SERVICE_CONTROL_NETBINDADD => :SERVICE_CONTROL_NETBINDADD,
SERVICE_CONTROL_NETBINDREMOVE => :SERVICE_CONTROL_NETBINDREMOVE,
SERVICE_CONTROL_NETBINDENABLE => :SERVICE_CONTROL_NETBINDENABLE,
SERVICE_CONTROL_NETBINDDISABLE => :SERVICE_CONTROL_NETBINDDISABLE,
SERVICE_CONTROL_DEVICEEVENT => :SERVICE_CONTROL_DEVICEEVENT,
SERVICE_CONTROL_HARDWAREPROFILECHANGE => :SERVICE_CONTROL_HARDWAREPROFILECHANGE,
SERVICE_CONTROL_POWEREVENT => :SERVICE_CONTROL_POWEREVENT,
SERVICE_CONTROL_SESSIONCHANGE => :SERVICE_CONTROL_SESSIONCHANGE,
SERVICE_CONTROL_PRESHUTDOWN => :SERVICE_CONTROL_PRESHUTDOWN,
SERVICE_CONTROL_TIMECHANGE => :SERVICE_CONTROL_TIMECHANGE,
SERVICE_CONTROL_TRIGGEREVENT => :SERVICE_CONTROL_TRIGGEREVENT
}
# Service start type codes
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-changeserviceconfigw
SERVICE_AUTO_START = 0x00000002
SERVICE_BOOT_START = 0x00000000
SERVICE_DEMAND_START = 0x00000003
SERVICE_DISABLED = 0x00000004
SERVICE_SYSTEM_START = 0x00000001
SERVICE_START_TYPES = {
SERVICE_AUTO_START => :SERVICE_AUTO_START,
SERVICE_BOOT_START => :SERVICE_BOOT_START,
SERVICE_DEMAND_START => :SERVICE_DEMAND_START,
SERVICE_DISABLED => :SERVICE_DISABLED,
SERVICE_SYSTEM_START => :SERVICE_SYSTEM_START,
}
# Service type codes
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-changeserviceconfigw
SERVICE_FILE_SYSTEM_DRIVER = 0x00000002
SERVICE_KERNEL_DRIVER = 0x00000001
SERVICE_WIN32_OWN_PROCESS = 0x00000010
SERVICE_WIN32_SHARE_PROCESS = 0x00000020
SERVICE_USER_OWN_PROCESS = 0x00000050
SERVICE_USER_SHARE_PROCESS = 0x00000060
# Available only if service is also SERVICE_WIN32_OWN_PROCESS or SERVICE_WIN32_SHARE_PROCESS
SERVICE_INTERACTIVE_PROCESS = 0x00000100
ALL_SERVICE_TYPES =
SERVICE_FILE_SYSTEM_DRIVER |
SERVICE_KERNEL_DRIVER |
SERVICE_WIN32_OWN_PROCESS |
SERVICE_WIN32_SHARE_PROCESS
# Current state codes
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process
SERVICE_CONTINUE_PENDING = 0x00000005
SERVICE_PAUSE_PENDING = 0x00000006
SERVICE_PAUSED = 0x00000007
SERVICE_RUNNING = 0x00000004
SERVICE_START_PENDING = 0x00000002
SERVICE_STOP_PENDING = 0x00000003
SERVICE_STOPPED = 0x00000001
UNSAFE_PENDING_STATES = [SERVICE_START_PENDING, SERVICE_STOP_PENDING]
FINAL_STATES = {
SERVICE_CONTINUE_PENDING => SERVICE_RUNNING,
SERVICE_PAUSE_PENDING => SERVICE_PAUSED,
SERVICE_START_PENDING => SERVICE_RUNNING,
SERVICE_STOP_PENDING => SERVICE_STOPPED
}
SERVICE_STATES = {
SERVICE_CONTINUE_PENDING => :SERVICE_CONTINUE_PENDING,
SERVICE_PAUSE_PENDING => :SERVICE_PAUSE_PENDING,
SERVICE_PAUSED => :SERVICE_PAUSED,
SERVICE_RUNNING => :SERVICE_RUNNING,
SERVICE_START_PENDING => :SERVICE_START_PENDING,
SERVICE_STOP_PENDING => :SERVICE_STOP_PENDING,
SERVICE_STOPPED => :SERVICE_STOPPED,
}
# Service accepts control codes
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process
SERVICE_ACCEPT_STOP = 0x00000001
SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002
SERVICE_ACCEPT_SHUTDOWN = 0x00000004
SERVICE_ACCEPT_PARAMCHANGE = 0x00000008
SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020
SERVICE_ACCEPT_POWEREVENT = 0x00000040
SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080
SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100
SERVICE_ACCEPT_TIMECHANGE = 0x00000200
SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400
SERVICE_ACCEPT_USER_LOGOFF = 0x00000800
# Service manager access codes
# https://docs.microsoft.com/en-us/windows/desktop/Services/service-security-and-access-rights
SC_MANAGER_CREATE_SERVICE = 0x00000002
SC_MANAGER_CONNECT = 0x00000001
SC_MANAGER_ENUMERATE_SERVICE = 0x00000004
SC_MANAGER_LOCK = 0x00000008
SC_MANAGER_MODIFY_BOOT_CONFIG = 0x00000020
SC_MANAGER_QUERY_LOCK_STATUS = 0x00000010
SC_MANAGER_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED |
SC_MANAGER_CREATE_SERVICE |
SC_MANAGER_CONNECT |
SC_MANAGER_ENUMERATE_SERVICE |
SC_MANAGER_LOCK |
SC_MANAGER_MODIFY_BOOT_CONFIG |
SC_MANAGER_QUERY_LOCK_STATUS
# Service access codes
# https://docs.microsoft.com/en-us/windows/desktop/Services/service-security-and-access-rights
SERVICE_CHANGE_CONFIG = 0x0002
SERVICE_ENUMERATE_DEPENDENTS = 0x0008
SERVICE_INTERROGATE = 0x0080
SERVICE_PAUSE_CONTINUE = 0x0040
SERVICE_QUERY_STATUS = 0x0004
SERVICE_QUERY_CONFIG = 0x0001
SERVICE_START = 0x0010
SERVICE_STOP = 0x0020
SERVICE_USER_DEFINED_CONTROL = 0x0100
SERVICE_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED |
SERVICE_CHANGE_CONFIG |
SERVICE_ENUMERATE_DEPENDENTS |
SERVICE_INTERROGATE |
SERVICE_PAUSE_CONTINUE |
SERVICE_QUERY_STATUS |
SERVICE_QUERY_CONFIG |
SERVICE_START |
SERVICE_STOP |
SERVICE_USER_DEFINED_CONTROL
# Service config codes
# From the windows 10 SDK:
# //
# // Value to indicate no change to an optional parameter
# //
# #define SERVICE_NO_CHANGE 0xffffffff
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-changeserviceconfig2w
SERVICE_CONFIG_DESCRIPTION = 0x00000001
SERVICE_CONFIG_FAILURE_ACTIONS = 0x00000002
SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x00000003
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG = 0x00000004
SERVICE_CONFIG_SERVICE_SID_INFO = 0x00000005
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO = 0x00000006
SERVICE_CONFIG_PRESHUTDOWN_INFO = 0x00000007
SERVICE_CONFIG_TRIGGER_INFO = 0x00000008
SERVICE_CONFIG_PREFERRED_NODE = 0x00000009
SERVICE_CONFIG_LAUNCH_PROTECTED = 0x0000000C
SERVICE_NO_CHANGE = 0xffffffff
SERVICE_CONFIG_TYPES = {
SERVICE_CONFIG_DESCRIPTION => :SERVICE_CONFIG_DESCRIPTION,
SERVICE_CONFIG_FAILURE_ACTIONS => :SERVICE_CONFIG_FAILURE_ACTIONS,
SERVICE_CONFIG_DELAYED_AUTO_START_INFO => :SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG => :SERVICE_CONFIG_FAILURE_ACTIONS_FLAG,
SERVICE_CONFIG_SERVICE_SID_INFO => :SERVICE_CONFIG_SERVICE_SID_INFO,
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO => :SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO,
SERVICE_CONFIG_PRESHUTDOWN_INFO => :SERVICE_CONFIG_PRESHUTDOWN_INFO,
SERVICE_CONFIG_TRIGGER_INFO => :SERVICE_CONFIG_TRIGGER_INFO,
SERVICE_CONFIG_PREFERRED_NODE => :SERVICE_CONFIG_PREFERRED_NODE,
SERVICE_CONFIG_LAUNCH_PROTECTED => :SERVICE_CONFIG_LAUNCH_PROTECTED,
}
# Service enum codes
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-enumservicesstatusexa
SERVICE_ACTIVE = 0x00000001
SERVICE_INACTIVE = 0x00000002
SERVICE_STATE_ALL =
SERVICE_ACTIVE |
SERVICE_INACTIVE
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_enum_service_status_processw
SERVICENAME_MAX = 256
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/windows/structs.rb | lib/puppet/ffi/windows/structs.rb | # coding: utf-8
# frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::FFI::Windows
module Structs
extend FFI::Library
extend Puppet::FFI::Windows::APITypes
# https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85)
# typedef struct _SECURITY_ATTRIBUTES {
# DWORD nLength;
# LPVOID lpSecurityDescriptor;
# BOOL bInheritHandle;
# } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
class SECURITY_ATTRIBUTES < FFI::Struct
layout(
:nLength, :dword,
:lpSecurityDescriptor, :lpvoid,
:bInheritHandle, :win32_bool
)
end
private_constant :SECURITY_ATTRIBUTES
# sizeof(STARTUPINFO) == 68
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa
# typedef struct _STARTUPINFOA {
# DWORD cb;
# LPSTR lpReserved;
# LPSTR lpDesktop;
# LPSTR lpTitle;
# DWORD dwX;
# DWORD dwY;
# DWORD dwXSize;
# DWORD dwYSize;
# DWORD dwXCountChars;
# DWORD dwYCountChars;
# DWORD dwFillAttribute;
# DWORD dwFlags;
# WORD wShowWindow;
# WORD cbReserved2;
# LPBYTE lpReserved2;
# HANDLE hStdInput;
# HANDLE hStdOutput;
# HANDLE hStdError;
# } STARTUPINFOA, *LPSTARTUPINFOA;
class STARTUPINFO < FFI::Struct
layout(
:cb, :dword,
:lpReserved, :lpcstr,
:lpDesktop, :lpcstr,
:lpTitle, :lpcstr,
:dwX, :dword,
:dwY, :dword,
:dwXSize, :dword,
:dwYSize, :dword,
:dwXCountChars, :dword,
:dwYCountChars, :dword,
:dwFillAttribute, :dword,
:dwFlags, :dword,
:wShowWindow, :word,
:cbReserved2, :word,
:lpReserved2, :pointer,
:hStdInput, :handle,
:hStdOutput, :handle,
:hStdError, :handle
)
end
private_constant :STARTUPINFO
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information
# typedef struct _PROCESS_INFORMATION {
# HANDLE hProcess;
# HANDLE hThread;
# DWORD dwProcessId;
# DWORD dwThreadId;
# } PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION;
class PROCESS_INFORMATION < FFI::Struct
layout(
:hProcess, :handle,
:hThread, :handle,
:dwProcessId, :dword,
:dwThreadId, :dword
)
end
private_constant :PROCESS_INFORMATION
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379261(v=vs.85).aspx
# typedef struct _LUID {
# DWORD LowPart;
# LONG HighPart;
# } LUID, *PLUID;
class LUID < FFI::Struct
layout :LowPart, :dword,
:HighPart, :win32_long
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379263(v=vs.85).aspx
# typedef struct _LUID_AND_ATTRIBUTES {
# LUID Luid;
# DWORD Attributes;
# } LUID_AND_ATTRIBUTES, *PLUID_AND_ATTRIBUTES;
class LUID_AND_ATTRIBUTES < FFI::Struct
layout :Luid, LUID,
:Attributes, :dword
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379630(v=vs.85).aspx
# typedef struct _TOKEN_PRIVILEGES {
# DWORD PrivilegeCount;
# LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY];
# } TOKEN_PRIVILEGES, *PTOKEN_PRIVILEGES;
class TOKEN_PRIVILEGES < FFI::Struct
layout :PrivilegeCount, :dword,
:Privileges, [LUID_AND_ATTRIBUTES, 1] # placeholder for offset
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb530717(v=vs.85).aspx
# typedef struct _TOKEN_ELEVATION {
# DWORD TokenIsElevated;
# } TOKEN_ELEVATION, *PTOKEN_ELEVATION;
class TOKEN_ELEVATION < FFI::Struct
layout :TokenIsElevated, :dword
end
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_service_status_process
# typedef struct _SERVICE_STATUS_PROCESS {
# DWORD dwServiceType;
# DWORD dwCurrentState;
# DWORD dwControlsAccepted;
# DWORD dwWin32ExitCode;
# DWORD dwServiceSpecificExitCode;
# DWORD dwCheckPoint;
# DWORD dwWaitHint;
# DWORD dwProcessId;
# DWORD dwServiceFlags;
# } SERVICE_STATUS_PROCESS, *LPSERVICE_STATUS_PROCESS;
class SERVICE_STATUS_PROCESS < FFI::Struct
layout(
:dwServiceType, :dword,
:dwCurrentState, :dword,
:dwControlsAccepted, :dword,
:dwWin32ExitCode, :dword,
:dwServiceSpecificExitCode, :dword,
:dwCheckPoint, :dword,
:dwWaitHint, :dword,
:dwProcessId, :dword,
:dwServiceFlags, :dword
)
end
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/ns-winsvc-service_delayed_auto_start_info
# typedef struct _SERVICE_DELAYED_AUTO_START_INFO {
# BOOL fDelayedAutostart;
# } SERVICE_DELAYED_AUTO_START_INFO, *LPSERVICE_DELAYED_AUTO_START_INFO;
class SERVICE_DELAYED_AUTO_START_INFO < FFI::Struct
layout(:fDelayedAutostart, :int)
alias aset []=
# Intercept the accessor so that we can handle either true/false or 1/0.
# Since there is only one member, there’s no need to check the key name.
def []=(key, value)
[0, false].include?(value) ? aset(key, 0) : aset(key, 1)
end
end
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/ns-winsvc-_enum_service_status_processw
# typedef struct _ENUM_SERVICE_STATUS_PROCESSW {
# LPWSTR lpServiceName;
# LPWSTR lpDisplayName;
# SERVICE_STATUS_PROCESS ServiceStatusProcess;
# } ENUM_SERVICE_STATUS_PROCESSW, *LPENUM_SERVICE_STATUS_PROCESSW;
class ENUM_SERVICE_STATUS_PROCESSW < FFI::Struct
layout(
:lpServiceName, :pointer,
:lpDisplayName, :pointer,
:ServiceStatusProcess, SERVICE_STATUS_PROCESS
)
end
# typedef struct _SERVICE_STATUS {
# DWORD dwServiceType;
# DWORD dwCurrentState;
# DWORD dwControlsAccepted;
# DWORD dwWin32ExitCode;
# DWORD dwServiceSpecificExitCode;
# DWORD dwCheckPoint;
# DWORD dwWaitHint;
# } SERVICE_STATUS, *LPSERVICE_STATUS;
class SERVICE_STATUS < FFI::Struct
layout(
:dwServiceType, :dword,
:dwCurrentState, :dword,
:dwControlsAccepted, :dword,
:dwWin32ExitCode, :dword,
:dwServiceSpecificExitCode, :dword,
:dwCheckPoint, :dword,
:dwWaitHint, :dword
)
end
# typedef struct _QUERY_SERVICE_CONFIGW {
# DWORD dwServiceType;
# DWORD dwStartType;
# DWORD dwErrorControl;
# LPWSTR lpBinaryPathName;
# LPWSTR lpLoadOrderGroup;
# DWORD dwTagId;
# LPWSTR lpDependencies;
# LPWSTR lpServiceStartName;
# LPWSTR lpDisplayName;
# } QUERY_SERVICE_CONFIGW, *LPQUERY_SERVICE_CONFIGW;
class QUERY_SERVICE_CONFIGW < FFI::Struct
layout(
:dwServiceType, :dword,
:dwStartType, :dword,
:dwErrorControl, :dword,
:lpBinaryPathName, :pointer,
:lpLoadOrderGroup, :pointer,
:dwTagId, :dword,
:lpDependencies, :pointer,
:lpServiceStartName, :pointer,
:lpDisplayName, :pointer
)
end
# typedef struct _SERVICE_TABLE_ENTRYW {
# LPWSTR lpServiceName;
# LPSERVICE_MAIN_FUNCTIONW lpServiceProc;
# } SERVICE_TABLE_ENTRYW, *LPSERVICE_TABLE_ENTRYW;
class SERVICE_TABLE_ENTRYW < FFI::Struct
layout(
:lpServiceName, :pointer,
:lpServiceProc, :pointer
)
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724834%28v=vs.85%29.aspx
# typedef struct _OSVERSIONINFO {
# DWORD dwOSVersionInfoSize;
# DWORD dwMajorVersion;
# DWORD dwMinorVersion;
# DWORD dwBuildNumber;
# DWORD dwPlatformId;
# TCHAR szCSDVersion[128];
# } OSVERSIONINFO;
class OSVERSIONINFO < FFI::Struct
layout(
:dwOSVersionInfoSize, :dword,
:dwMajorVersion, :dword,
:dwMinorVersion, :dword,
:dwBuildNumber, :dword,
:dwPlatformId, :dword,
:szCSDVersion, [:wchar, 128]
)
end
MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16_384
# SYMLINK_REPARSE_DATA_BUFFER
# https://msdn.microsoft.com/en-us/library/cc232006.aspx
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff552012(v=vs.85).aspx
# struct is always MAXIMUM_REPARSE_DATA_BUFFER_SIZE bytes
class SYMLINK_REPARSE_DATA_BUFFER < FFI::Struct
layout :ReparseTag, :win32_ulong,
:ReparseDataLength, :ushort,
:Reserved, :ushort,
:SubstituteNameOffset, :ushort,
:SubstituteNameLength, :ushort,
:PrintNameOffset, :ushort,
:PrintNameLength, :ushort,
:Flags, :win32_ulong,
# max less above fields dword / uint 4 bytes, ushort 2 bytes
# technically a WCHAR buffer, but we care about size in bytes here
:PathBuffer, [:byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 20]
end
# MOUNT_POINT_REPARSE_DATA_BUFFER
# https://msdn.microsoft.com/en-us/library/cc232007.aspx
# https://msdn.microsoft.com/en-us/library/windows/hardware/ff552012(v=vs.85).aspx
# struct is always MAXIMUM_REPARSE_DATA_BUFFER_SIZE bytes
class MOUNT_POINT_REPARSE_DATA_BUFFER < FFI::Struct
layout :ReparseTag, :win32_ulong,
:ReparseDataLength, :ushort,
:Reserved, :ushort,
:SubstituteNameOffset, :ushort,
:SubstituteNameLength, :ushort,
:PrintNameOffset, :ushort,
:PrintNameLength, :ushort,
# max less above fields dword / uint 4 bytes, ushort 2 bytes
# technically a WCHAR buffer, but we care about size in bytes here
:PathBuffer, [:byte, MAXIMUM_REPARSE_DATA_BUFFER_SIZE - 16]
end
# SHFILEINFO
# https://docs.microsoft.com/en-us/windows/win32/api/shellapi/ns-shellapi-shfileinfow
# typedef struct _SHFILEINFOW {
# HICON hIcon;
# int iIcon;
# DWORD dwAttributes;
# WCHAR szDisplayName[MAX_PATH];
# WCHAR szTypeName[80];
# } SHFILEINFOW;
class SHFILEINFO < FFI::Struct
layout(
:hIcon, :ulong,
:iIcon, :int,
:dwAttributes, :ulong,
:szDisplayName, [:char, 256],
:szTypeName, [:char, 80]
)
end
# REPARSE_JDATA_BUFFER
class REPARSE_JDATA_BUFFER < FFI::Struct
layout(
:ReparseTag, :ulong,
:ReparseDataLength, :ushort,
:Reserved, :ushort,
:SubstituteNameOffset, :ushort,
:SubstituteNameLength, :ushort,
:PrintNameOffset, :ushort,
:PrintNameLength, :ushort,
:PathBuffer, [:char, 1024]
)
# The REPARSE_DATA_BUFFER_HEADER_SIZE which is calculated as:
#
# sizeof(ReparseTag) + sizeof(ReparseDataLength) + sizeof(Reserved)
#
def header_size
FFI::Type::ULONG.size + FFI::Type::USHORT.size + FFI::Type::USHORT.size
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/ffi/windows/functions.rb | lib/puppet/ffi/windows/functions.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::FFI::Windows
module Functions
extend FFI::Library
include Puppet::FFI::Windows::Constants
ffi_convention :stdcall
# https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-sethandleinformation
# BOOL SetHandleInformation(
# HANDLE hObject,
# DWORD dwMask,
# DWORD dwFlags
# );
ffi_lib :kernel32
attach_function_private :SetHandleInformation, [:handle, :dword, :dword], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode
# UINT SetErrorMode(
# UINT uMode
# );
ffi_lib :kernel32
attach_function_private :SetErrorMode, [:uint], :uint
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
# BOOL CreateProcessW(
# LPCWSTR lpApplicationName,
# LPWSTR lpCommandLine,
# LPSECURITY_ATTRIBUTES lpProcessAttributes,
# LPSECURITY_ATTRIBUTES lpThreadAttributes,
# BOOL bInheritHandles,
# DWORD dwCreationFlags,
# LPVOID lpEnvironment,
# LPCWSTR lpCurrentDirectory,
# LPSTARTUPINFOW lpStartupInfo,
# LPPROCESS_INFORMATION lpProcessInformation
# );
ffi_lib :kernel32
attach_function_private :CreateProcessW,
[:lpcwstr, :lpwstr, :pointer, :pointer, :win32_bool,
:dword, :lpvoid, :lpcwstr, :pointer, :pointer], :bool
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess
# HANDLE OpenProcess(
# DWORD dwDesiredAccess,
# BOOL bInheritHandle,
# DWORD dwProcessId
# );
ffi_lib :kernel32
attach_function_private :OpenProcess, [:dword, :win32_bool, :dword], :handle
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setpriorityclass
# BOOL SetPriorityClass(
# HANDLE hProcess,
# DWORD dwPriorityClass
# );
ffi_lib :kernel32
attach_function_private :SetPriorityClass, [:handle, :dword], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprocesswithlogonw
# BOOL CreateProcessWithLogonW(
# LPCWSTR lpUsername,
# LPCWSTR lpDomain,
# LPCWSTR lpPassword,
# DWORD dwLogonFlags,
# LPCWSTR lpApplicationName,
# LPWSTR lpCommandLine,
# DWORD dwCreationFlags,
# LPVOID lpEnvironment,
# LPCWSTR lpCurrentDirectory,
# LPSTARTUPINFOW lpStartupInfo,
# LPPROCESS_INFORMATION lpProcessInformation
# );
ffi_lib :advapi32
attach_function_private :CreateProcessWithLogonW,
[:lpcwstr, :lpcwstr, :lpcwstr, :dword, :lpcwstr, :lpwstr,
:dword, :lpvoid, :lpcwstr, :pointer, :pointer], :bool
# https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-osfhandle?view=vs-2019
# intptr_t _get_osfhandle(
# int fd
# );
ffi_lib FFI::Library::LIBC
attach_function_private :get_osfhandle, :_get_osfhandle, [:int], :intptr_t
begin
# https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/get-errno?view=vs-2019
# errno_t _get_errno(
# int * pValue
# );
attach_function_private :get_errno, :_get_errno, [:pointer], :int
rescue FFI::NotFoundError
# Do nothing, Windows XP or earlier.
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx
# DWORD WINAPI WaitForSingleObject(
# _In_ HANDLE hHandle,
# _In_ DWORD dwMilliseconds
# );
ffi_lib :kernel32
attach_function_private :WaitForSingleObject,
[:handle, :dword], :dword, :blocking => true
# https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjects
# DWORD WaitForMultipleObjects(
# DWORD nCount,
# const HANDLE *lpHandles,
# BOOL bWaitAll,
# DWORD dwMilliseconds
# );
ffi_lib :kernel32
attach_function_private :WaitForMultipleObjects,
[:dword, :phandle, :win32_bool, :dword], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createeventw
# HANDLE CreateEventW(
# LPSECURITY_ATTRIBUTES lpEventAttributes,
# BOOL bManualReset,
# BOOL bInitialState,
# LPCWSTR lpName
# );
ffi_lib :kernel32
attach_function_private :CreateEventW,
[:pointer, :win32_bool, :win32_bool, :lpcwstr], :handle
# https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread
# HANDLE CreateThread(
# LPSECURITY_ATTRIBUTES lpThreadAttributes,
# SIZE_T dwStackSize,
# LPTHREAD_START_ROUTINE lpStartAddress,
# __drv_aliasesMem LPVOID lpParameter,
# DWORD dwCreationFlags,
# LPDWORD lpThreadId
# );
ffi_lib :kernel32
attach_function_private :CreateThread,
[:pointer, :size_t, :pointer, :lpvoid, :dword, :lpdword], :handle, :blocking => true
# https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setevent
# BOOL SetEvent(
# HANDLE hEvent
# );
ffi_lib :kernel32
attach_function_private :SetEvent,
[:handle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms683189(v=vs.85).aspx
# BOOL WINAPI GetExitCodeProcess(
# _In_ HANDLE hProcess,
# _Out_ LPDWORD lpExitCode
# );
ffi_lib :kernel32
attach_function_private :GetExitCodeProcess,
[:handle, :lpdword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms683179(v=vs.85).aspx
# HANDLE WINAPI GetCurrentProcess(void);
ffi_lib :kernel32
attach_function_private :GetCurrentProcess, [], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms683187(v=vs.85).aspx
# LPTCH GetEnvironmentStrings(void);
ffi_lib :kernel32
attach_function_private :GetEnvironmentStringsW, [], :pointer
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms683151(v=vs.85).aspx
# BOOL FreeEnvironmentStrings(
# _In_ LPTCH lpszEnvironmentBlock
# );
ffi_lib :kernel32
attach_function_private :FreeEnvironmentStringsW,
[:pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms686206(v=vs.85).aspx
# BOOL WINAPI SetEnvironmentVariableW(
# _In_ LPCTSTR lpName,
# _In_opt_ LPCTSTR lpValue
# );
ffi_lib :kernel32
attach_function_private :SetEnvironmentVariableW,
[:lpcwstr, :lpcwstr], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx
# HANDLE WINAPI OpenProcess(
# _In_ DWORD DesiredAccess,
# _In_ BOOL InheritHandle,
# _In_ DWORD ProcessId
# );
ffi_lib :kernel32
attach_function_private :OpenProcess,
[:dword, :win32_bool, :dword], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379295(v=vs.85).aspx
# BOOL WINAPI OpenProcessToken(
# _In_ HANDLE ProcessHandle,
# _In_ DWORD DesiredAccess,
# _Out_ PHANDLE TokenHandle
# );
ffi_lib :advapi32
attach_function_private :OpenProcessToken,
[:handle, :dword, :phandle], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-queryfullprocessimagenamew
# BOOL WINAPI QueryFullProcessImageName(
# _In_ HANDLE hProcess,
# _In_ DWORD dwFlags,
# _Out_ LPWSTR lpExeName,
# _In_ PDWORD lpdwSize,
# );
ffi_lib :kernel32
attach_function_private :QueryFullProcessImageNameW,
[:handle, :dword, :lpwstr, :pdword], :win32_bool
# https://msdn.microsoft.com/en-us/library/Windows/desktop/aa379180(v=vs.85).aspx
# BOOL WINAPI LookupPrivilegeValue(
# _In_opt_ LPCTSTR lpSystemName,
# _In_ LPCTSTR lpName,
# _Out_ PLUID lpLuid
# );
ffi_lib :advapi32
attach_function_private :LookupPrivilegeValueW,
[:lpcwstr, :lpcwstr, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa446671(v=vs.85).aspx
# BOOL WINAPI GetTokenInformation(
# _In_ HANDLE TokenHandle,
# _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
# _Out_opt_ LPVOID TokenInformation,
# _In_ DWORD TokenInformationLength,
# _Out_ PDWORD ReturnLength
# );
ffi_lib :advapi32
attach_function_private :GetTokenInformation,
[:handle, TOKEN_INFORMATION_CLASS, :lpvoid, :dword, :pdword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
# BOOL WINAPI GetVersionEx(
# _Inout_ LPOSVERSIONINFO lpVersionInfo
# );
ffi_lib :kernel32
attach_function_private :GetVersionExW,
[:pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd318123(v=vs.85).aspx
# LANGID GetSystemDefaultUILanguage(void);
ffi_lib :kernel32
attach_function_private :GetSystemDefaultUILanguage, [], :word
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-openscmanagerw
# SC_HANDLE OpenSCManagerW(
# LPCWSTR lpMachineName,
# LPCWSTR lpDatabaseName,
# DWORD dwDesiredAccess
# );
ffi_lib :advapi32
attach_function_private :OpenSCManagerW,
[:lpcwstr, :lpcwstr, :dword], :handle
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-openservicew
# SC_HANDLE OpenServiceW(
# SC_HANDLE hSCManager,
# LPCWSTR lpServiceName,
# DWORD dwDesiredAccess
# );
ffi_lib :advapi32
attach_function_private :OpenServiceW,
[:handle, :lpcwstr, :dword], :handle
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-closeservicehandle
# BOOL CloseServiceHandle(
# SC_HANDLE hSCObject
# );
ffi_lib :advapi32
attach_function_private :CloseServiceHandle,
[:handle], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-queryservicestatusex
# BOOL QueryServiceStatusEx(
# SC_HANDLE hService,
# SC_STATUS_TYPE InfoLevel,
# LPBYTE lpBuffer,
# DWORD cbBufSize,
# LPDWORD pcbBytesNeeded
# );
SC_STATUS_TYPE = enum(
:SC_STATUS_PROCESS_INFO, 0
)
ffi_lib :advapi32
attach_function_private :QueryServiceStatusEx,
[:handle, SC_STATUS_TYPE, :lpbyte, :dword, :lpdword], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-queryserviceconfigw
# BOOL QueryServiceConfigW(
# SC_HANDLE hService,
# LPQUERY_SERVICE_CONFIGW lpServiceConfig,
# DWORD cbBufSize,
# LPDWORD pcbBytesNeeded
# );
ffi_lib :advapi32
attach_function_private :QueryServiceConfigW,
[:handle, :lpbyte, :dword, :lpdword], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-queryserviceconfig2w
# BOOL QueryServiceConfig2W(
# SC_HANDLE hService,
# DWORD dwInfoLevel,
# LPBYTE lpBuffer,
# DWORD cbBufSize,
# LPDWORD pcbBytesNeeded
# );
ffi_lib :advapi32
attach_function_private :QueryServiceConfig2W,
[:handle, :dword, :lpbyte, :dword, :lpdword], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/Winsvc/nf-winsvc-startservicew
# BOOL StartServiceW(
# SC_HANDLE hService,
# DWORD dwNumServiceArgs,
# LPCWSTR *lpServiceArgVectors
# );
ffi_lib :advapi32
attach_function_private :StartServiceW,
[:handle, :dword, :pointer], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatcherw
# BOOL StartServiceCtrlDispatcherW(
# const SERVICE_TABLE_ENTRYW *lpServiceStartTable
# );
ffi_lib :advapi32
attach_function_private :StartServiceCtrlDispatcherW,
[:pointer], :win32_bool, :blocking => true
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-setservicestatus
# BOOL SetServiceStatus(
# SERVICE_STATUS_HANDLE hServiceStatus,
# LPSERVICE_STATUS lpServiceStatus
# );
ffi_lib :advapi32
attach_function_private :SetServiceStatus,
[:handle, :pointer], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-controlservice
# BOOL ControlService(
# SC_HANDLE hService,
# DWORD dwControl,
# LPSERVICE_STATUS lpServiceStatus
# );
ffi_lib :advapi32
attach_function_private :ControlService,
[:handle, :dword, :pointer], :win32_bool
# DWORD LphandlerFunctionEx(
# DWORD dwControl,
# DWORD dwEventType,
# LPVOID lpEventData,
# LPVOID lpContext
# )
callback :handler_ex, [:dword, :dword, :lpvoid, :lpvoid], :void
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-registerservicectrlhandlerexw
# SERVICE_STATUS_HANDLE RegisterServiceCtrlHandlerExW(
# LPCWSTR lpServiceName,
# LPHANDLER_FUNCTION_EX lpHandlerProc,
# LPVOID lpContext
# );
ffi_lib :advapi32
attach_function_private :RegisterServiceCtrlHandlerExW,
[:lpcwstr, :handler_ex, :lpvoid], :handle
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-changeserviceconfigw
# BOOL ChangeServiceConfigW(
# SC_HANDLE hService,
# DWORD dwServiceType,
# DWORD dwStartType,
# DWORD dwErrorControl,
# LPCWSTR lpBinaryPathName,
# LPCWSTR lpLoadOrderGroup,
# LPDWORD lpdwTagId,
# LPCWSTR lpDependencies,
# LPCWSTR lpServiceStartName,
# LPCWSTR lpPassword,
# LPCWSTR lpDisplayName
# );
ffi_lib :advapi32
attach_function_private :ChangeServiceConfigW,
[
:handle,
:dword,
:dword,
:dword,
:lpcwstr,
:lpcwstr,
:lpdword,
:lpcwstr,
:lpcwstr,
:lpcwstr,
:lpcwstr
], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-changeserviceconfig2w
# BOOL ChangeServiceConfig2W(
# SC_HANDLE hService,
# DWORD dwInfoLevel,
# LPVOID lpInfo
# );
ffi_lib :advapi32
attach_function_private :ChangeServiceConfig2W,
[:handle, :dword, :lpvoid], :win32_bool
# https://docs.microsoft.com/en-us/windows/desktop/api/winsvc/nf-winsvc-enumservicesstatusexw
# BOOL EnumServicesStatusExW(
# SC_HANDLE hSCManager,
# SC_ENUM_TYPE InfoLevel,
# DWORD dwServiceType,
# DWORD dwServiceState,
# LPBYTE lpServices,
# DWORD cbBufSize,
# LPDWORD pcbBytesNeeded,
# LPDWORD lpServicesReturned,
# LPDWORD lpResumeHandle,
# LPCWSTR pszGroupName
# );
SC_ENUM_TYPE = enum(
:SC_ENUM_PROCESS_INFO, 0
)
ffi_lib :advapi32
attach_function_private :EnumServicesStatusExW,
[
:handle,
SC_ENUM_TYPE,
:dword,
:dword,
:lpbyte,
:dword,
:lpdword,
:lpdword,
:lpdword,
:lpcwstr
], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa365512(v=vs.85).aspx
# BOOL WINAPI ReplaceFile(
# _In_ LPCTSTR lpReplacedFileName,
# _In_ LPCTSTR lpReplacementFileName,
# _In_opt_ LPCTSTR lpBackupFileName,
# _In_ DWORD dwReplaceFlags - 0x1 REPLACEFILE_WRITE_THROUGH,
# 0x2 REPLACEFILE_IGNORE_MERGE_ERRORS,
# 0x4 REPLACEFILE_IGNORE_ACL_ERRORS
# _Reserved_ LPVOID lpExclude,
# _Reserved_ LPVOID lpReserved
# );
ffi_lib :kernel32
attach_function_private :ReplaceFileW,
[:lpcwstr, :lpcwstr, :lpcwstr, :dword, :lpvoid, :lpvoid], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa365240(v=vs.85).aspx
# BOOL WINAPI MoveFileEx(
# _In_ LPCTSTR lpExistingFileName,
# _In_opt_ LPCTSTR lpNewFileName,
# _In_ DWORD dwFlags
# );
ffi_lib :kernel32
attach_function_private :MoveFileExW,
[:lpcwstr, :lpcwstr, :dword], :win32_bool
# BOOLEAN WINAPI CreateSymbolicLink(
# _In_ LPTSTR lpSymlinkFileName, - symbolic link to be created
# _In_ LPTSTR lpTargetFileName, - name of target for symbolic link
# _In_ DWORD dwFlags - 0x0 target is a file, 0x1 target is a directory
# );
# rescue on Windows < 6.0 so that code doesn't explode
begin
ffi_lib :kernel32
attach_function_private :CreateSymbolicLinkW,
[:lpwstr, :lpwstr, :dword], :boolean
rescue LoadError
end
# https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory
# DWORD GetCurrentDirectory(
# DWORD nBufferLength,
# LPTSTR lpBuffer
# );
ffi_lib :kernel32
attach_function_private :GetCurrentDirectoryW,
[:dword, :lpwstr], :dword
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa364944(v=vs.85).aspx
# DWORD WINAPI GetFileAttributes(
# _In_ LPCTSTR lpFileName
# );
ffi_lib :kernel32
attach_function_private :GetFileAttributesW,
[:lpcwstr], :dword
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa365535(v=vs.85).aspx
# BOOL WINAPI SetFileAttributes(
# _In_ LPCTSTR lpFileName,
# _In_ DWORD dwFileAttributes
# );
ffi_lib :kernel32
attach_function_private :SetFileAttributesW,
[:lpcwstr, :dword], :win32_bool
# HANDLE WINAPI CreateFile(
# _In_ LPCTSTR lpFileName,
# _In_ DWORD dwDesiredAccess,
# _In_ DWORD dwShareMode,
# _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
# _In_ DWORD dwCreationDisposition,
# _In_ DWORD dwFlagsAndAttributes,
# _In_opt_ HANDLE hTemplateFile
# );
ffi_lib :kernel32
attach_function_private :CreateFileW,
[:lpcwstr, :dword, :dword, :pointer, :dword, :dword, :handle], :handle
# https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createdirectoryw
# BOOL CreateDirectoryW(
# LPCWSTR lpPathName,
# LPSECURITY_ATTRIBUTES lpSecurityAttributes
# );
ffi_lib :kernel32
attach_function_private :CreateDirectoryW,
[:lpcwstr, :pointer], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-removedirectoryw
# BOOL RemoveDirectoryW(
# LPCWSTR lpPathName
# );
ffi_lib :kernel32
attach_function_private :RemoveDirectoryW,
[:lpcwstr], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216(v=vs.85).aspx
# BOOL WINAPI DeviceIoControl(
# _In_ HANDLE hDevice,
# _In_ DWORD dwIoControlCode,
# _In_opt_ LPVOID lpInBuffer,
# _In_ DWORD nInBufferSize,
# _Out_opt_ LPVOID lpOutBuffer,
# _In_ DWORD nOutBufferSize,
# _Out_opt_ LPDWORD lpBytesReturned,
# _Inout_opt_ LPOVERLAPPED lpOverlapped
# );
ffi_lib :kernel32
attach_function_private :DeviceIoControl,
[:handle, :dword, :lpvoid, :dword, :lpvoid, :dword, :lpdword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa364980(v=vs.85).aspx
# DWORD WINAPI GetLongPathName(
# _In_ LPCTSTR lpszShortPath,
# _Out_ LPTSTR lpszLongPath,
# _In_ DWORD cchBuffer
# );
ffi_lib :kernel32
attach_function_private :GetLongPathNameW,
[:lpcwstr, :lpwstr, :dword], :dword
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa364989(v=vs.85).aspx
# DWORD WINAPI GetShortPathName(
# _In_ LPCTSTR lpszLongPath,
# _Out_ LPTSTR lpszShortPath,
# _In_ DWORD cchBuffer
# );
ffi_lib :kernel32
attach_function_private :GetShortPathNameW,
[:lpcwstr, :lpwstr, :dword], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamew
# DWORD GetFullPathNameW(
# LPCWSTR lpFileName,
# DWORD nBufferLength,
# LPWSTR lpBuffer,
# LPWSTR *lpFilePart
# );
ffi_lib :kernel32
attach_function_private :GetFullPathNameW,
[:lpcwstr, :dword, :lpwstr, :pointer], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpathw
# SHFOLDERAPI SHGetFolderPathW(
# HWND hwnd,
# int csidl,
# HANDLE hToken,
# DWORD dwFlags,
# LPWSTR pszPath
# );
ffi_lib :shell32
attach_function_private :SHGetFolderPathW,
[:hwnd, :int, :handle, :dword, :lpwstr], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderlocation
# SHSTDAPI SHGetFolderLocation(
# HWND hwnd,
# int csidl,
# HANDLE hToken,
# DWORD dwFlags,
# PIDLIST_ABSOLUTE *ppidl
# );
ffi_lib :shell32
attach_function_private :SHGetFolderLocation,
[:hwnd, :int, :handle, :dword, :pointer], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shgetfileinfoa
# DWORD_PTR SHGetFileInfoA(
# LPCSTR pszPath,
# DWORD dwFileAttributes,
# SHFILEINFOA *psfi,
# UINT cbFileInfo,
# UINT uFlags
# );
ffi_lib :shell32
attach_function_private :SHGetFileInfo,
[:dword, :dword, :pointer, :uint, :uint], :dword
# https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/nf-shlwapi-pathisdirectoryemptyw
# BOOL PathIsDirectoryEmptyW(
# LPCWSTR pszPath
# );
ffi_lib :shlwapi
attach_function_private :PathIsDirectoryEmptyW,
[:lpcwstr], :win32_bool
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/gettext/stubs.rb | lib/puppet/gettext/stubs.rb | # frozen_string_literal: true
# These stub the translation methods normally brought in
# by FastGettext. Used when Gettext could not be properly
# initialized.
def _(msg)
msg
end
def n_(*args, &block)
plural = args[2] == 1 ? args[0] : args[1]
block ? block.call : plural
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/gettext/module_translations.rb | lib/puppet/gettext/module_translations.rb | # frozen_string_literal: true
require_relative '../../puppet/gettext/config'
module Puppet::ModuleTranslations
# @api private
# Loads translation files for each of the specified modules,
# if present. Requires the modules to have `forge_name` specified.
# @param [[Module]] modules a list of modules for which to
# load translations
def self.load_from_modulepath(modules)
modules.each do |mod|
next unless mod.forge_name && mod.has_translations?(Puppet::GettextConfig.current_locale)
module_name = mod.forge_name.tr('/', '-')
if Puppet::GettextConfig.load_translations(module_name, mod.locale_directory, :po)
Puppet.debug { "Loaded translations for #{module_name}." }
elsif Puppet::GettextConfig.gettext_loaded?
Puppet.debug { "Could not find translation files for #{module_name} at #{mod.locale_directory}. Skipping translation initialization." }
else
Puppet.warn_once("gettext_unavailable", "gettext_unavailable", "No gettext library found, skipping translation initialization.")
end
end
end
# @api private
# Loads translation files that have been pluginsync'd for modules
# from the $vardir.
# @param [String] vardir the path to Puppet's vardir
def self.load_from_vardir(vardir)
locale = Puppet::GettextConfig.current_locale
Dir.glob("#{vardir}/locales/#{locale}/*.po") do |f|
module_name = File.basename(f, ".po")
if Puppet::GettextConfig.load_translations(module_name, File.join(vardir, "locales"), :po)
Puppet.debug { "Loaded translations for #{module_name}." }
elsif Puppet::GettextConfig.gettext_loaded?
Puppet.debug { "Could not load translations for #{module_name}." }
else
Puppet.warn_once("gettext_unavailable", "gettext_unavailable", "No gettext library found, skipping translation initialization.")
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/gettext/config.rb | lib/puppet/gettext/config.rb | # frozen_string_literal: true
require_relative '../../puppet/util/platform'
require_relative '../../puppet/file_system'
module Puppet::GettextConfig
LOCAL_PATH = File.absolute_path('../../../locales', File.dirname(__FILE__))
POSIX_PATH = File.absolute_path('../../../../../share/locale', File.dirname(__FILE__))
WINDOWS_PATH = File.absolute_path('../../../../../../puppet/share/locale', File.dirname(__FILE__))
# This is the only domain name that won't be a symbol, making it unique from environments.
DEFAULT_TEXT_DOMAIN = 'default-text-domain'
# Load gettext helpers and track whether they're available.
# Used instead of features because we initialize gettext before features is available.
begin
require 'fast_gettext'
require 'locale'
# Make translation methods (e.g. `_()` and `n_()`) available everywhere.
class ::Object
include FastGettext::Translation
end
@gettext_loaded = true
rescue LoadError
# Stub out gettext's `_` and `n_()` methods, which attempt to load translations,
# with versions that do nothing
require_relative '../../puppet/gettext/stubs'
@gettext_loaded = false
end
# @api private
# Whether we were able to require fast_gettext and locale
# @return [Boolean] true if translation gems were successfully loaded
def self.gettext_loaded?
@gettext_loaded
end
# @api private
# Returns the currently selected locale from FastGettext,
# or 'en' of gettext has not been loaded
# @return [String] the active locale
def self.current_locale
if gettext_loaded?
FastGettext.default_locale
else
'en'
end
end
# @api private
# Returns a list of the names of the loaded text domains
# @return [[String]] the names of the loaded text domains
def self.loaded_text_domains
return [] if @gettext_disabled || !gettext_loaded?
FastGettext.translation_repositories.keys
end
# @api private
# Clears the translation repository for the given text domain,
# creating it if it doesn't exist, then adds default translations
# and switches to using this domain.
# @param [String, Symbol] domain_name the name of the domain to create
def self.reset_text_domain(domain_name)
return if @gettext_disabled || !gettext_loaded?
domain_name = domain_name.to_sym
Puppet.debug { "Reset text domain to #{domain_name.inspect}" }
FastGettext.add_text_domain(domain_name,
type: :chain,
chain: [],
report_warning: false)
copy_default_translations(domain_name)
FastGettext.text_domain = domain_name
end
# @api private
# Resets the thread's configured text_domain to the default text domain.
# In Puppet Server, thread A may process a compile request that configures
# a domain, while thread B may invalidate that environment and delete the
# domain. That leaves thread A with an invalid text_domain selected.
# To avoid that, clear_text_domain after any processing that needs the
# non-default text domain.
def self.clear_text_domain
return if @gettext_disabled || !gettext_loaded?
FastGettext.text_domain = nil
end
# @api private
# Creates a default text domain containing the translations for
# Puppet as the start of chain. When semantic_puppet gets initialized,
# its translations are added to this chain. This is used as a cache
# so that all non-module translations only need to be loaded once as
# we create and reset environment-specific text domains.
#
# @return true if Puppet translations were successfully loaded, false
# otherwise
def self.create_default_text_domain
return if @gettext_disabled || !gettext_loaded?
FastGettext.add_text_domain(DEFAULT_TEXT_DOMAIN,
type: :chain,
chain: [],
report_warning: false)
FastGettext.default_text_domain = DEFAULT_TEXT_DOMAIN
load_translations('puppet', puppet_locale_path, translation_mode(puppet_locale_path), DEFAULT_TEXT_DOMAIN)
end
# @api private
# Switches the active text domain, if the requested domain exists.
# @param [String, Symbol] domain_name the name of the domain to switch to
def self.use_text_domain(domain_name)
return if @gettext_disabled || !gettext_loaded?
domain_name = domain_name.to_sym
if FastGettext.translation_repositories.include?(domain_name)
Puppet.debug { "Use text domain #{domain_name.inspect}" }
FastGettext.text_domain = domain_name
else
Puppet.debug { "Requested unknown text domain #{domain_name.inspect}" }
end
end
# @api private
# Delete all text domains.
def self.delete_all_text_domains
FastGettext.translation_repositories.clear
FastGettext.default_text_domain = nil
FastGettext.text_domain = nil
end
# @api private
# Deletes the text domain with the given name
# @param [String, Symbol] domain_name the name of the domain to delete
def self.delete_text_domain(domain_name)
return if @gettext_disabled || !gettext_loaded?
domain_name = domain_name.to_sym
deleted = FastGettext.translation_repositories.delete(domain_name)
if FastGettext.text_domain == domain_name
Puppet.debug { "Deleted current text domain #{domain_name.inspect}: #{!deleted.nil?}" }
FastGettext.text_domain = nil
else
Puppet.debug { "Deleted text domain #{domain_name.inspect}: #{!deleted.nil?}" }
end
end
# @api private
# Deletes all text domains except the default one
def self.delete_environment_text_domains
return if @gettext_disabled || !gettext_loaded?
FastGettext.translation_repositories.keys.each do |key|
# do not clear default translations
next if key == DEFAULT_TEXT_DOMAIN
FastGettext.translation_repositories.delete(key)
end
FastGettext.text_domain = nil
end
# @api private
# Adds translations from the default text domain to the specified
# text domain. Creates the default text domain if one does not exist
# (this will load Puppet's translations).
#
# Since we are currently (Nov 2017) vendoring semantic_puppet, in normal
# flows these translations will be copied along with Puppet's.
#
# @param [Symbol] domain_name the name of the domain to add translations to
def self.copy_default_translations(domain_name)
return if @gettext_disabled || !gettext_loaded?
if FastGettext.default_text_domain.nil?
create_default_text_domain
end
puppet_translations = FastGettext.translation_repositories[FastGettext.default_text_domain].chain
FastGettext.translation_repositories[domain_name].chain.push(*puppet_translations)
end
# @api private
# Search for puppet gettext config files
# @return [String] path to the config, or nil if not found
def self.puppet_locale_path
if Puppet::FileSystem.exist?(LOCAL_PATH)
LOCAL_PATH
elsif Puppet::Util::Platform.windows? && Puppet::FileSystem.exist?(WINDOWS_PATH)
WINDOWS_PATH
elsif !Puppet::Util::Platform.windows? && Puppet::FileSystem.exist?(POSIX_PATH)
POSIX_PATH
else
nil
end
end
# @api private
# Determine which translation file format to use
# @param [String] conf_path the path to the gettext config file
# @return [Symbol] :mo if in a package structure, :po otherwise
def self.translation_mode(conf_path)
if WINDOWS_PATH == conf_path || POSIX_PATH == conf_path
:mo
else
:po
end
end
# @api private
# Prevent future gettext initializations
def self.disable_gettext
@gettext_disabled = true
end
# @api private
# Attempt to load translations for the given project.
# @param [String] project_name the project whose translations we want to load
# @param [String] locale_dir the path to the directory containing translations
# @param [Symbol] file_format translation file format to use, either :po or :mo
# @return true if initialization succeeded, false otherwise
def self.load_translations(project_name, locale_dir, file_format, text_domain = FastGettext.text_domain)
if project_name.nil? || project_name.empty?
raise Puppet::Error, "A project name must be specified in order to initialize translations."
end
return false if @gettext_disabled || !@gettext_loaded
return false unless locale_dir && Puppet::FileSystem.exist?(locale_dir)
unless file_format == :po || file_format == :mo
raise Puppet::Error, "Unsupported translation file format #{file_format}; please use :po or :mo"
end
add_repository_to_domain(project_name, locale_dir, file_format, text_domain)
true
end
# @api private
# Add the translations for this project to the domain's repository chain
# chain for the currently selected text domain, if needed.
# @param [String] project_name the name of the project for which to load translations
# @param [String] locale_dir the path to the directory containing translations
# @param [Symbol] file_format the format of the translations files, :po or :mo
def self.add_repository_to_domain(project_name, locale_dir, file_format, text_domain = FastGettext.text_domain)
return if @gettext_disabled || !gettext_loaded?
current_chain = FastGettext.translation_repositories[text_domain].chain
repository = FastGettext::TranslationRepository.build(project_name,
path: locale_dir,
type: file_format,
report_warning: false)
current_chain << repository
end
# @api private
# Sets FastGettext's locale to the current system locale
def self.setup_locale
return if @gettext_disabled || !gettext_loaded?
set_locale(Locale.current.language)
end
# @api private
# Sets the language in which to display strings.
# @param [String] locale the language portion of a locale string (e.g. "ja")
def self.set_locale(locale)
return if @gettext_disabled || !gettext_loaded?
# make sure we're not using the `available_locales` machinery
FastGettext.default_available_locales = nil
FastGettext.default_locale = locale
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/module_directory.rb | lib/puppet/functions/module_directory.rb | # frozen_string_literal: true
# Finds an existing module and returns the path to its root directory.
#
# The argument to this function should be a module name String
# For example, the reference `mysql` will search for the
# directory `<MODULES DIRECTORY>/mysql` and return the first
# found on the modulepath.
#
# This function can also accept:
#
# * Multiple String arguments, which will return the path of the **first** module
# found, skipping non existing modules.
# * An array of module names, which will return the path of the **first** module
# found from the given names in the array, skipping non existing modules.
#
# The function returns `undef` if none of the given modules were found
#
# @since 5.4.0
#
Puppet::Functions.create_function(:module_directory, Puppet::Functions::InternalFunction) do
dispatch :module_directory do
scope_param
repeated_param 'String', :names
end
dispatch :module_directory_array do
scope_param
repeated_param 'Array[String]', :names
end
def module_directory_array(scope, names)
module_directory(scope, *names)
end
def module_directory(scope, *names)
names.each do |module_name|
found = scope.compiler.environment.module(module_name)
return found.path if found
end
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/ceiling.rb | lib/puppet/functions/ceiling.rb | # frozen_string_literal: true
# Returns the smallest `Integer` greater or equal to the argument.
# Takes a single numeric value as an argument.
#
# This function is backwards compatible with the same function in stdlib
# and accepts a `Numeric` value. A `String` that can be converted
# to a floating point number can also be used in this version - but this
# is deprecated.
#
# In general convert string input to `Numeric` before calling this function
# to have full control over how the conversion is done.
#
Puppet::Functions.create_function(:ceiling) do
dispatch :on_numeric do
param 'Numeric', :val
end
dispatch :on_string do
param 'String', :val
end
def on_numeric(x)
x.ceil
end
def on_string(x)
Puppet.warn_once('deprecations', 'ceiling_function_numeric_coerce_string',
_("The ceiling() function's auto conversion of String to Float is deprecated - change to convert input before calling"))
begin
Float(x).ceil
rescue TypeError, ArgumentError => _e
# TRANSLATORS: 'ceiling' is a name and should not be translated
raise(ArgumentError, _('ceiling(): cannot convert given value to a floating point value.'))
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/find_file.rb | lib/puppet/functions/find_file.rb | # frozen_string_literal: true
# Finds an existing file from a module and returns its path.
#
# This function accepts an argument that is a String as a `<MODULE NAME>/<FILE>`
# reference, which searches for `<FILE>` relative to a module's `files`
# directory. (For example, the reference `mysql/mysqltuner.pl` will search for the
# file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.)
#
# If this function is run via puppet agent, it checks for file existence on the
# Puppet Primary server. If run via puppet apply, it checks on the local host.
# In both cases, the check is performed before any resources are changed.
#
# This function can also accept:
#
# * An absolute String path, which checks for the existence of a file from anywhere on disk.
# * Multiple String arguments, which returns the path of the **first** file
# found, skipping nonexistent files.
# * An array of string paths, which returns the path of the **first** file
# found from the given paths in the array, skipping nonexistent files.
#
# The function returns `undef` if none of the given paths were found.
#
# @since 4.8.0
#
Puppet::Functions.create_function(:find_file, Puppet::Functions::InternalFunction) do
dispatch :find_file do
scope_param
repeated_param 'String', :paths
end
dispatch :find_file_array do
scope_param
repeated_param 'Array[String]', :paths_array
end
def find_file_array(scope, array)
find_file(scope, *array)
end
def find_file(scope, *args)
args.each do |file|
found = Puppet::Parser::Files.find_file(file, scope.compiler.environment)
if found && Puppet::FileSystem.exist?(found)
return found
end
end
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/hiera_array.rb | lib/puppet/functions/hiera_array.rb | # frozen_string_literal: true
require 'hiera/puppet_function'
# Finds all matches of a key throughout the hierarchy and returns them as a single flattened
# array of unique values. If any of the matched values are arrays, they're flattened and
# included in the results. This is called an
# [array merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#array-merge).
#
# This function is deprecated in favor of the `lookup` function. While this function
# continues to work, it does **not** support:
# * `lookup_options` stored in the data
# * lookup across global, environment, and module layers
#
# The `hiera_array` function takes up to three arguments, in this order:
#
# 1. A string key that Hiera searches for in the hierarchy. **Required**.
# 2. An optional default value to return if Hiera doesn't find anything matching the key.
# * If this argument isn't provided and this function results in a lookup failure, Puppet
# fails with a compilation error.
# 3. The optional name of an arbitrary
# [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
# top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
# * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
# searching the rest of the hierarchy.
#
# @example Using `hiera_array`
#
# ```yaml
# # Assuming hiera.yaml
# # :hierarchy:
# # - web01.example.com
# # - common
#
# # Assuming common.yaml:
# # users:
# # - 'cdouglas = regular'
# # - 'efranklin = regular'
#
# # Assuming web01.example.com.yaml:
# # users: 'abarry = admin'
# ```
#
# ```puppet
# $allusers = hiera_array('users', undef)
#
# # $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].
# ```
#
# You can optionally generate the default value with a
# [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
# takes one parameter.
#
# @example Using `hiera_array` with a lambda
#
# ```puppet
# # Assuming the same Hiera data as the previous example:
#
# $allusers = hiera_array('users') | $key | { "Key \'${key}\' not found" }
#
# # $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].
# # If hiera_array couldn't match its key, it would return the lambda result,
# # "Key 'users' not found".
# ```
#
# `hiera_array` expects that all values returned will be strings or arrays. If any matched
# value is a hash, Puppet raises a type mismatch error.
#
# See
# [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data.
# Also see
# [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html)
# for more information about the Hiera 3 functions.
#
# @since 4.0.0
#
Puppet::Functions.create_function(:hiera_array, Hiera::PuppetFunction) do
init_dispatch
def merge_type
:unique
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/binary_file.rb | lib/puppet/functions/binary_file.rb | # frozen_string_literal: true
# Loads a binary file from a module or file system and returns its contents as a `Binary`.
# The argument to this function should be a `<MODULE NAME>/<FILE>`
# reference, which will load `<FILE>` from a module's `files`
# directory. (For example, the reference `mysql/mysqltuner.pl` will load the
# file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.)
#
# This function also accepts an absolute file path that allows reading
# binary file content from anywhere on disk.
#
# An error is raised if the given file does not exists.
#
# To search for the existence of files, use the `find_file()` function.
#
# - since 4.8.0
#
# @since 4.8.0
#
Puppet::Functions.create_function(:binary_file, Puppet::Functions::InternalFunction) do
dispatch :binary_file do
scope_param
param 'String', :path
end
def binary_file(scope, unresolved_path)
path = Puppet::Parser::Files.find_file(unresolved_path, scope.compiler.environment)
unless path && Puppet::FileSystem.exist?(path)
# TRANSLATORS the string "binary_file()" should not be translated
raise Puppet::ParseError, _("binary_file(): The given file '%{unresolved_path}' does not exist") % { unresolved_path: unresolved_path }
end
Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(Puppet::FileSystem.binread(path))
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/reduce.rb | lib/puppet/functions/reduce.rb | # frozen_string_literal: true
# Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# to every value in a data structure from the first argument, carrying over the returned
# value of each iteration, and returns the result of the lambda's final iteration. This
# lets you create a new value or data structure by combining values from the first
# argument's data structure.
#
# This function takes two mandatory arguments, in this order:
#
# 1. An array, hash, or other iterable object that the function will iterate over.
# 2. A lambda, which the function calls for each element in the first argument. It takes
# two mandatory parameters:
# 1. A memo value that is overwritten after each iteration with the iteration's result.
# 2. A second value that is overwritten after each iteration with the next value in the
# function's first argument.
#
# @example Using the `reduce` function
#
# `$data.reduce |$memo, $value| { ... }`
#
# or
#
# `reduce($data) |$memo, $value| { ... }`
#
# You can also pass an optional "start memo" value as an argument, such as `start` below:
#
# `$data.reduce(start) |$memo, $value| { ... }`
#
# or
#
# `reduce($data, start) |$memo, $value| { ... }`
#
# When the first argument (`$data` in the above example) is an array, Puppet passes each
# of the data structure's values in turn to the lambda's parameters. When the first
# argument is a hash, Puppet converts each of the hash's values to an array in the form
# `[key, value]`.
#
# If you pass a start memo value, Puppet executes the lambda with the provided memo value
# and the data structure's first value. Otherwise, Puppet passes the structure's first two
# values to the lambda.
#
# Puppet calls the lambda for each of the data structure's remaining values. For each
# call, it passes the result of the previous call as the first parameter (`$memo` in the
# above examples) and the next value from the data structure as the second parameter
# (`$value`).
#
# @example Using the `reduce` function
#
# ```puppet
# # Reduce the array $data, returning the sum of all values in the array.
# $data = [1, 2, 3]
# $sum = $data.reduce |$memo, $value| { $memo + $value }
# # $sum contains 6
#
# # Reduce the array $data, returning the sum of a start memo value and all values in the
# # array.
# $data = [1, 2, 3]
# $sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# # $sum contains 10
#
# # Reduce the hash $data, returning the sum of all values and concatenated string of all
# # keys.
# $data = {a => 1, b => 2, c => 3}
# $combine = $data.reduce |$memo, $value| {
# $string = "${memo[0]}${value[0]}"
# $number = $memo[1] + $value[1]
# [$string, $number]
# }
# # $combine contains [abc, 6]
# ```
#
# @example Using the `reduce` function with a start memo and two-parameter lambda
#
# ```puppet
# # Reduce the array $data, returning the sum of all values in the array and starting
# # with $memo set to an arbitrary value instead of $data's first value.
# $data = [1, 2, 3]
# $sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# # At the start of the lambda's first iteration, $memo contains 4 and $value contains 1.
# # After all iterations, $sum contains 10.
#
# # Reduce the hash $data, returning the sum of all values and concatenated string of
# # all keys, and starting with $memo set to an arbitrary array instead of $data's first
# # key-value pair.
# $data = {a => 1, b => 2, c => 3}
# $combine = $data.reduce( [d, 4] ) |$memo, $value| {
# $string = "${memo[0]}${value[0]}"
# $number = $memo[1] + $value[1]
# [$string, $number]
# }
# # At the start of the lambda's first iteration, $memo contains [d, 4] and $value
# # contains [a, 1].
# # $combine contains [dabc, 10]
# ```
#
# @example Using the `reduce` function to reduce a hash of hashes
#
# ```puppet
# # Reduce a hash of hashes $data, merging defaults into the inner hashes.
# $data = {
# 'connection1' => {
# 'username' => 'user1',
# 'password' => 'pass1',
# },
# 'connection_name2' => {
# 'username' => 'user2',
# 'password' => 'pass2',
# },
# }
#
# $defaults = {
# 'maxActive' => '20',
# 'maxWait' => '10000',
# 'username' => 'defaultuser',
# 'password' => 'defaultpass',
# }
#
# $merged = $data.reduce( {} ) |$memo, $x| {
# $memo + { $x[0] => $defaults + $data[$x[0]] }
# }
# # At the start of the lambda's first iteration, $memo is set to {}, and $x is set to
# # the first [key, value] tuple. The key in $data is, therefore, given by $x[0]. In
# # subsequent rounds, $memo retains the value returned by the expression, i.e.
# # $memo + { $x[0] => $defaults + $data[$x[0]] }.
# ```
#
# @since 4.0.0
#
Puppet::Functions.create_function(:reduce) do
dispatch :reduce_without_memo do
param 'Iterable', :enumerable
block_param 'Callable[2,2]', :block
end
dispatch :reduce_with_memo do
param 'Iterable', :enumerable
param 'Any', :memo
block_param 'Callable[2,2]', :block
end
def reduce_without_memo(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
enum.reduce do |memo, x|
yield(memo, x)
rescue StopIteration
return memo
end
end
def reduce_with_memo(enumerable, given_memo)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
enum.reduce(given_memo) do |memo, x|
yield(memo, x)
rescue StopIteration
return memo
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/slice.rb | lib/puppet/functions/slice.rb | # frozen_string_literal: true
# Slices an array or hash into pieces of a given size.
#
# This function takes two mandatory arguments: the first should be an array or hash, and the second specifies
# the number of elements to include in each slice.
#
# When the first argument is a hash, each key value pair is counted as one. For example, a slice size of 2 will produce
# an array of two arrays with key, and value.
#
# @example Slicing a Hash
#
# ```puppet
# $a.slice(2) |$entry| { notice "first ${$entry[0]}, second ${$entry[1]}" }
# $a.slice(2) |$first, $second| { notice "first ${first}, second ${second}" }
# ```
# The function produces a concatenated result of the slices.
#
# @example Slicing an Array
#
# ```puppet
# slice([1,2,3,4,5,6], 2) # produces [[1,2], [3,4], [5,6]]
# slice(Integer[1,6], 2) # produces [[1,2], [3,4], [5,6]]
# slice(4,2) # produces [[0,1], [2,3]]
# slice('hello',2) # produces [[h, e], [l, l], [o]]
# ```
#
# @example Passing a lambda to a slice (optional)
#
# ```puppet
# $a.slice($n) |$x| { ... }
# slice($a) |$x| { ... }
# ```
#
# The lambda should have either one parameter (receiving an array with the slice), or the same number
# of parameters as specified by the slice size (each parameter receiving its part of the slice).
# If there are fewer remaining elements than the slice size for the last slice, it will contain the remaining
# elements. If the lambda has multiple parameters, excess parameters are set to undef for an array, or
# to empty arrays for a hash.
#
# @example Getting individual values of a slice
#
# ```puppet
# $a.slice(2) |$first, $second| { ... }
# ```
#
# @since 4.0.0
#
Puppet::Functions.create_function(:slice) do
dispatch :slice_Hash do
param 'Hash[Any, Any]', :hash
param 'Integer[1, default]', :slice_size
optional_block_param
end
dispatch :slice_Enumerable do
param 'Iterable', :enumerable
param 'Integer[1, default]', :slice_size
optional_block_param
end
def slice_Hash(hash, slice_size, &pblock)
result = slice_Common(hash, slice_size, [], block_given? ? pblock : nil)
block_given? ? hash : result
end
def slice_Enumerable(enumerable, slice_size, &pblock)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
result = slice_Common(enum, slice_size, nil, block_given? ? pblock : nil)
block_given? ? enumerable : result
end
def slice_Common(o, slice_size, filler, pblock)
serving_size = asserted_slice_serving_size(pblock, slice_size)
enumerator = o.each_slice(slice_size)
result = []
if serving_size == 1
begin
if pblock
loop do
pblock.call(enumerator.next)
end
else
loop do
result << enumerator.next
end
end
rescue StopIteration
end
else
begin
loop do
a = enumerator.next
if a.size < serving_size
a = a.dup.fill(filler, a.length...serving_size)
end
pblock.call(*a)
end
rescue StopIteration
end
end
if pblock
o
else
result
end
end
def asserted_slice_serving_size(pblock, slice_size)
if pblock
arity = pblock.arity
serving_size = arity < 0 ? slice_size : arity
else
serving_size = 1
end
if serving_size == 0
raise ArgumentError, _("slice(): block must define at least one parameter. Block has 0.")
end
unless serving_size == 1 || serving_size == slice_size
raise ArgumentError, _("slice(): block must define one parameter, or the same number of parameters as the given size of the slice (%{slice_size}). Block has %{serving_size}; %{parameter_names}") %
{ slice_size: slice_size, serving_size: serving_size, parameter_names: pblock.parameter_names.join(', ') }
end
serving_size
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/empty.rb | lib/puppet/functions/empty.rb | # frozen_string_literal: true
# Returns `true` if the given argument is an empty collection of values.
#
# This function can answer if one of the following is empty:
# * `Array`, `Hash` - having zero entries
# * `String`, `Binary` - having zero length
#
# For backwards compatibility with the stdlib function with the same name the
# following data types are also accepted by the function instead of raising an error.
# Using these is deprecated and will raise a warning:
#
# * `Numeric` - `false` is returned for all `Numeric` values.
# * `Undef` - `true` is returned for all `Undef` values.
#
# @example Using `empty`
#
# ```puppet
# notice([].empty)
# notice(empty([]))
# # would both notice 'true'
# ```
#
# @since Puppet 5.5.0 - support for Binary
#
Puppet::Functions.create_function(:empty) do
dispatch :collection_empty do
param 'Collection', :coll
end
dispatch :sensitive_string_empty do
param 'Sensitive[String]', :str
end
dispatch :string_empty do
param 'String', :str
end
dispatch :numeric_empty do
param 'Numeric', :num
end
dispatch :binary_empty do
param 'Binary', :bin
end
dispatch :undef_empty do
param 'Undef', :x
end
def collection_empty(coll)
coll.empty?
end
def sensitive_string_empty(str)
str.unwrap.empty?
end
def string_empty(str)
str.empty?
end
# For compatibility reasons - return false rather than error on floats and integers
# (Yes, it is strange)
#
def numeric_empty(num)
deprecation_warning_for('Numeric')
false
end
def binary_empty(bin)
bin.length == 0
end
# For compatibility reasons - return true rather than error on undef
# (Yes, it is strange, but undef was passed as empty string in 3.x API)
#
def undef_empty(x)
true
end
def deprecation_warning_for(arg_type)
file, line = Puppet::Pops::PuppetStack.top_of_stack
msg = _("Calling function empty() with %{arg_type} value is deprecated.") % { arg_type: arg_type }
Puppet.warn_once('deprecations', "empty-from-#{file}-#{line}", msg, file, line)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/include.rb | lib/puppet/functions/include.rb | # frozen_string_literal: true
# Declares one or more classes, causing the resources in them to be
# evaluated and added to the catalog. Accepts a class name, an array of class
# names, or a comma-separated list of class names.
#
# The `include` function can be used multiple times on the same class and will
# only declare a given class once. If a class declared with `include` has any
# parameters, Puppet will automatically look up values for them in Hiera, using
# `<class name>::<parameter name>` as the lookup key.
#
# Contrast this behavior with resource-like class declarations
# (`class {'name': parameter => 'value',}`), which must be used in only one place
# per class and can directly set parameters. You should avoid using both `include`
# and resource-like declarations with the same class.
#
# The `include` function does not cause classes to be contained in the class
# where they are declared. For that, see the `contain` function. It also
# does not create a dependency relationship between the declared class and the
# surrounding class; for that, see the `require` function.
#
# You must use the class's full name;
# relative names are not allowed. In addition to names in string form,
# you may also directly use `Class` and `Resource` `Type`-values that are produced by
# the resource and relationship expressions.
#
# - Since < 3.0.0
# - Since 4.0.0 support for class and resource type values, absolute names
# - Since 4.7.0 returns an `Array[Type[Class]]` of all included classes
#
Puppet::Functions.create_function(:include, Puppet::Functions::InternalFunction) do
dispatch :include do
scope_param
# The function supports what the type system sees as Ruby runtime objects, and
# they cannot be parameterized to find what is actually valid instances.
# The validation is instead done in the function body itself via a call to
# `transform_and_assert_classnames` on the calling scope.
required_repeated_param 'Any', :names
end
def include(scope, *classes)
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :operation => 'include' }
)
end
classes = scope.transform_and_assert_classnames(classes.flatten)
result = classes.map { |name| Puppet::Pops::Types::TypeFactory.host_class(name) }
scope.compiler.evaluate_classes(classes, scope, false)
# Result is an Array[Class, 1, n] which allows chaining other operations
result
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/yaml_data.rb | lib/puppet/functions/yaml_data.rb | # frozen_string_literal: true
require 'yaml'
# The `yaml_data` is a hiera 5 `data_hash` data provider function.
# See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for
# how to use this function.
#
# @since 4.8.0
#
Puppet::Functions.create_function(:yaml_data) do
# @since 4.8.0
dispatch :yaml_data do
param 'Struct[{path=>String[1]}]', :options
param 'Puppet::LookupContext', :context
end
argument_mismatch :missing_path do
param 'Hash', :options
param 'Puppet::LookupContext', :context
end
def yaml_data(options, context)
path = options['path']
context.cached_file_data(path) do |content|
data = Puppet::Util::Yaml.safe_load(content, [Symbol], path)
if data.is_a?(Hash)
Puppet::Pops::Lookup::HieraConfig.symkeys_to_string(data)
else
msg = _("%{path}: file does not contain a valid yaml hash" % { path: path })
raise Puppet::DataBinding::LookupError, msg if Puppet[:strict] == :error && data != false
Puppet.warning(msg)
{}
end
rescue Puppet::Util::Yaml::YamlLoadError => ex
# YamlLoadErrors include the absolute path to the file, so no need to add that
raise Puppet::DataBinding::LookupError, _("Unable to parse %{message}") % { message: ex.message }
end
end
def missing_path(options, context)
"one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/tree_each.rb | lib/puppet/functions/tree_each.rb | # frozen_string_literal: true
# Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# recursively and repeatedly using values from a data structure, then returns the unchanged data structure, or if
# a lambda is not given, returns an `Iterator` for the tree.
#
# This function takes one mandatory argument, one optional, and an optional block in this order:
#
# 1. An `Array`, `Hash`, `Iterator`, or `Object` that the function will iterate over.
# 2. An optional hash with the options:
# * `include_containers` => `Optional[Boolean]` # default `true` - if containers should be given to the lambda
# * `include_values` => `Optional[Boolean]` # default `true` - if non containers should be given to the lambda
# * `include_root` => `Optional[Boolean]` # default `true` - if the root container should be given to the lambda
# * `container_type` => `Optional[Type[Variant[Array, Hash, Object]]]` # a type that determines what a container is - can only
# be set to a type that matches the default `Variant[Array, Hash, Object]`.
# * `order` => `Enum[depth_first, breadth_first]` # default ´depth_first`, the order in which elements are visited
# * `include_refs` => `Optional[Boolean]` # default `false`, if attributes in objects marked as bing of `reference` kind
# should be included.
# 3. An optional lambda, which the function calls for each element in the first argument. It must
# accept one or two arguments; either `$path`, and `$value`, or just `$value`.
#
# @example Using the `tree_each` function
#
# `$data.tree_each |$path, $value| { <PUPPET CODE BLOCK> }`
# `$data.tree_each |$value| { <PUPPET CODE BLOCK> }`
#
# or
#
# `tree_each($data) |$path, $value| { <PUPPET CODE BLOCK> }`
# `tree_each($data) |$value| { <PUPPET CODE BLOCK> }`
#
# The parameter `$path` is always given as an `Array` containing the path that when applied to
# the tree as `$data.dig(*$path) yields the `$value`.
# The `$value` is the value at that path.
#
# For `Array` values, the path will contain `Integer` entries with the array index,
# and for `Hash` values, the path will contain the hash key, which may be `Any` value.
# For `Object` containers, the entry is the name of the attribute (a `String`).
#
# The tree is walked in either depth-first order, or in breadth-first order under the control of the
# `order` option, yielding each `Array`, `Hash`, `Object`, and each entry/attribute.
# The default is `depth_first` which means that children are processed before siblings.
# An order of `breadth_first` means that siblings are processed before children.
#
# @example depth- or breadth-first order
#
# ```puppet
# [1, [2, 3], 4]
# ```
#
# If containers are skipped, results in:
#
# * `depth_first` order `1`, `2`, `3`, `4`
# * `breadth_first` order `1`, `4`,`2`, `3`
#
# If containers and root are included, results in:
#
# * `depth_first` order `[1, [2, 3], 4]`, `1`, `[2, 3]`, `2`, `3`, `4`
# * `breadth_first` order `[1, [2, 3], 4]`, `1`, `[2, 3]`, `4`, `2`, `3`
#
# Typical use of the `tree_each` function include:
# * a more efficient way to iterate over a tree than first using `flatten` on an array
# as that requires a new (potentially very large) array to be created
# * when a tree needs to be transformed and 'pretty printed' in a template
# * avoiding having to write a special recursive function when tree contains hashes (flatten does
# not work on hashes)
#
# @example A flattened iteration over a tree excluding Collections
#
# ```puppet
# $data = [1, 2, [3, [4, 5]]]
# $data.tree_each({include_containers => false}) |$v| { notice "$v" }
# ```
#
# This would call the lambda 5 times with with the following values in sequence: `1`, `2`, `3`, `4`, `5`
#
# @example A flattened iteration over a tree (including containers by default)
#
# ```puppet
# $data = [1, 2, [3, [4, 5]]]
# $data.tree_each |$v| { notice "$v" }
# ```
#
# This would call the lambda 7 times with the following values in sequence:
# `1`, `2`, `[3, [4, 5]]`, `3`, `[4, 5]`, `4`, `5`
#
# @example A flattened iteration over a tree (including only non root containers)
#
# ```puppet
# $data = [1, 2, [3, [4, 5]]]
# $data.tree_each({include_values => false, include_root => false}) |$v| { notice "$v" }
# ```
#
# This would call the lambda 2 times with the following values in sequence:
# `[3, [4, 5]]`, `[4, 5]`
#
# Any Puppet Type system data type can be used to filter what is
# considered to be a container, but it must be a narrower type than one of
# the default `Array`, `Hash`, `Object` types - for example it is not possible to make a
# `String` be a container type.
#
# @example Only `Array` as container type
#
# ```puppet
# $data = [1, {a => 'hello', b => [100, 200]}, [3, [4, 5]]]
# $data.tree_each({container_type => Array, include_containers => false} |$v| { notice "$v" }
# ```
#
# Would call the lambda 5 times with `1`, `{a => 'hello', b => [100, 200]}`, `3`, `4`, `5`
#
# **Chaining** When calling `tree_each` without a lambda the function produces an `Iterator`
# that can be chained into another iteration. Thus it is easy to use one of:
#
# * `reverse_each` - get "leaves before root"
# * `filter` - prune the tree
# * `map` - transform each element
#
# Note than when chaining, the value passed on is a `Tuple` with `[path, value]`.
#
# @example Pruning a tree
#
# ```puppet
# # A tree of some complexity (here very simple for readability)
# $tree = [
# { name => 'user1', status => 'inactive', id => '10'},
# { name => 'user2', status => 'active', id => '20'}
# ]
# notice $tree.tree_each.filter |$v| {
# $value = $v[1]
# $value =~ Hash and $value[status] == active
# }
# ```
#
# Would notice `[[[1], {name => user2, status => active, id => 20}]]`, which can then be processed
# further as each filtered result appears as a `Tuple` with `[path, value]`.
#
#
# For general examples that demonstrates iteration see the Puppet
# [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html)
# documentation.
#
# @since 5.0.0
#
Puppet::Functions.create_function(:tree_each) do
local_types do
type "OptionsType = Struct[{\
container_type => Optional[Type],\
include_root => Optional[Boolean],
include_containers => Optional[Boolean],\
include_values => Optional[Boolean],\
order => Optional[Enum[depth_first, breadth_first]],\
include_refs => Optional[Boolean]\
}]"
end
dispatch :tree_Enumerable2 do
param 'Variant[Iterator, Array, Hash, Object]', :tree
optional_param 'OptionsType', :options
block_param 'Callable[2,2]', :block
end
dispatch :tree_Enumerable1 do
param 'Variant[Iterator, Array, Hash, Object]', :tree
optional_param 'OptionsType', :options
block_param 'Callable[1,1]', :block
end
dispatch :tree_Iterable do
param 'Variant[Iterator, Array, Hash, Object]', :tree
optional_param 'OptionsType', :options
end
def tree_Enumerable1(enum, options = {}, &block)
iterator(enum, options).each { |_, v| yield(v) }
enum
end
def tree_Enumerable2(enum, options = {}, &block)
iterator(enum, options).each { |path, v| yield(path, v) }
enum
end
def tree_Iterable(enum, options = {}, &block)
Puppet::Pops::Types::Iterable.on(iterator(enum, options))
end
def iterator(enum, options)
if depth_first?(options)
Puppet::Pops::Types::Iterable::DepthFirstTreeIterator.new(enum, options)
else
Puppet::Pops::Types::Iterable::BreadthFirstTreeIterator.new(enum, options)
end
end
def depth_first?(options)
(order = options['order']).nil? ? true : order == 'depth_first'
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/eyaml_lookup_key.rb | lib/puppet/functions/eyaml_lookup_key.rb | # frozen_string_literal: true
# The `eyaml_lookup_key` is a hiera 5 `lookup_key` data provider function.
# See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-hiera-eyaml) for
# how to use this function.
#
# @since 5.0.0
#
Puppet::Functions.create_function(:eyaml_lookup_key) do
unless Puppet.features.hiera_eyaml?
raise Puppet::DataBinding::LookupError, 'Lookup using eyaml lookup_key function is only supported when the hiera_eyaml library is present'
end
require 'hiera/backend/eyaml/encryptor'
require 'hiera/backend/eyaml/utils'
require 'hiera/backend/eyaml/options'
require 'hiera/backend/eyaml/parser/parser'
dispatch :eyaml_lookup_key do
param 'String[1]', :key
param 'Hash[String[1],Any]', :options
param 'Puppet::LookupContext', :context
end
def eyaml_lookup_key(key, options, context)
return context.cached_value(key) if context.cache_has_key(key)
# Can't do this with an argument_mismatch dispatcher since there is no way to declare a struct that at least
# contains some keys but may contain other arbitrary keys.
unless options.include?('path')
# TRANSLATORS 'eyaml_lookup_key':, 'path', 'paths' 'glob', 'globs', 'mapped_paths', and lookup_key should not be translated
raise ArgumentError,
_("'eyaml_lookup_key': one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml"\
" when using this lookup_key function")
end
# nil key is used to indicate that the cache contains the raw content of the eyaml file
raw_data = context.cached_value(nil)
if raw_data.nil?
raw_data = load_data_hash(options, context)
context.cache(nil, raw_data)
end
context.not_found unless raw_data.include?(key)
context.cache(key, decrypt_value(raw_data[key], context, options, key))
end
def load_data_hash(options, context)
path = options['path']
context.cached_file_data(path) do |content|
data = Puppet::Util::Yaml.safe_load(content, [Symbol], path)
if data.is_a?(Hash)
Puppet::Pops::Lookup::HieraConfig.symkeys_to_string(data)
else
msg = _("%{path}: file does not contain a valid yaml hash") % { path: path }
raise Puppet::DataBinding::LookupError, msg if Puppet[:strict] == :error && data != false
Puppet.warning(msg)
{}
end
rescue Puppet::Util::Yaml::YamlLoadError => ex
# YamlLoadErrors include the absolute path to the file, so no need to add that
raise Puppet::DataBinding::LookupError, _("Unable to parse %{message}") % { message: ex.message }
end
end
def decrypt_value(value, context, options, key)
case value
when String
decrypt(value, context, options, key)
when Hash
result = {}
value.each_pair { |k, v| result[context.interpolate(k)] = decrypt_value(v, context, options, key) }
result
when Array
value.map { |v| decrypt_value(v, context, options, key) }
else
value
end
end
def decrypt(data, context, options, key)
if encrypted?(data)
# Options must be set prior to each call to #parse since they end up as static variables in
# the Options class. They cannot be set once before #decrypt_value is called, since each #decrypt
# might cause a new lookup through interpolation. That lookup in turn, might use a different eyaml
# config.
#
Hiera::Backend::Eyaml::Options.set(options)
begin
tokens = Hiera::Backend::Eyaml::Parser::ParserFactory.hiera_backend_parser.parse(data)
data = tokens.map(&:to_plain_text).join.chomp
rescue StandardError => ex
raise Puppet::DataBinding::LookupError,
_("hiera-eyaml backend error decrypting %{data} when looking up %{key} in %{path}. Error was %{message}") % { data: data, key: key, path: options['path'], message: ex.message }
end
end
context.interpolate(data)
end
def encrypted?(data)
/.*ENC\[.*?\]/ =~ data ? true : false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/upcase.rb | lib/puppet/functions/upcase.rb | # frozen_string_literal: true
# Converts a String, Array or Hash (recursively) into upper case.
#
# This function is compatible with the stdlib function with the same name.
#
# The function does the following:
# * For a `String`, its upper case version is returned. This is done using Ruby system locale which handles some, but not all
# special international up-casing rules (for example German double-s ß is upcased to "SS", whereas upper case double-s
# is downcased to ß).
# * For `Array` and `Hash` the conversion to upper case is recursive and each key and value must be convertible by
# this function.
# * When a `Hash` is converted, some keys could result in the same key - in those cases, the
# latest key-value wins. For example if keys "aBC", and "abC" where both present, after upcase there would only be one
# key "ABC".
# * If the value is `Numeric` it is simply returned (this is for backwards compatibility).
# * An error is raised for all other data types.
#
# Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible.
# To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
#
# @example Converting a String to upper case
# ```puppet
# 'hello'.upcase()
# upcase('hello')
# ```
# Would both result in `"HELLO"`
#
# @example Converting an Array to upper case
# ```puppet
# ['a', 'b'].upcase()
# upcase(['a', 'b'])
# ```
# Would both result in `['A', 'B']`
#
# @example Converting a Hash to upper case
# ```puppet
# {'a' => 'hello', 'b' => 'goodbye'}.upcase()
# ```
# Would result in `{'A' => 'HELLO', 'B' => 'GOODBYE'}`
#
# @example Converting a recursive structure
# ```puppet
# ['a', 'b', ['c', ['d']], {'x' => 'y'}].upcase
# ```
# Would result in `['A', 'B', ['C', ['D']], {'X' => 'Y'}]`
#
Puppet::Functions.create_function(:upcase) do
local_types do
type 'StringData = Variant[String, Numeric, Array[StringData], Hash[StringData, StringData]]'
end
dispatch :on_numeric do
param 'Numeric', :arg
end
dispatch :on_string do
param 'String', :arg
end
dispatch :on_array do
param 'Array[StringData]', :arg
end
dispatch :on_hash do
param 'Hash[StringData, StringData]', :arg
end
# unit function - since the old implementation skipped Numeric values
def on_numeric(n)
n
end
def on_string(s)
s.upcase
end
def on_array(a)
a.map { |x| do_upcase(x) }
end
def on_hash(h)
result = {}
h.each_pair { |k, v| result[do_upcase(k)] = do_upcase(v) }
result
end
def do_upcase(x)
x.is_a?(String) ? x.upcase : call_function('upcase', x)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/type.rb | lib/puppet/functions/type.rb | # frozen_string_literal: true
# Returns the data type of a given value with a given degree of generality.
#
# ```puppet
# type InferenceFidelity = Enum[generalized, reduced, detailed]
#
# function type(Any $value, InferenceFidelity $fidelity = 'detailed') # returns Type
# ```
#
# @example Using `type`
#
# ``` puppet
# notice type(42) =~ Type[Integer]
# ```
#
# Would notice `true`.
#
# By default, the best possible inference is made where all details are retained.
# This is good when the type is used for further type calculations but is overwhelmingly
# rich in information if it is used in a error message.
#
# The optional argument `$fidelity` may be given as (from lowest to highest fidelity):
#
# * `generalized` - reduces to common type and drops size constraints
# * `reduced` - reduces to common type in collections
# * `detailed` - (default) all details about inferred types is retained
#
# @example Using `type()` with different inference fidelity:
#
# ``` puppet
# notice type([3.14, 42], 'generalized')
# notice type([3.14, 42], 'reduced'')
# notice type([3.14, 42], 'detailed')
# notice type([3.14, 42])
# ```
#
# Would notice the four values:
#
# 1. `Array[Numeric]`
# 2. `Array[Numeric, 2, 2]`
# 3. `Tuple[Float[3.14], Integer[42,42]]]`
# 4. `Tuple[Float[3.14], Integer[42,42]]]`
#
# @since 4.4.0
#
Puppet::Functions.create_function(:type) do
dispatch :type_detailed do
param 'Any', :value
optional_param 'Enum[detailed]', :inference_method
end
dispatch :type_parameterized do
param 'Any', :value
param 'Enum[reduced]', :inference_method
end
dispatch :type_generalized do
param 'Any', :value
param 'Enum[generalized]', :inference_method
end
def type_detailed(value, _ = nil)
Puppet::Pops::Types::TypeCalculator.infer_set(value)
end
def type_parameterized(value, _)
Puppet::Pops::Types::TypeCalculator.infer(value)
end
def type_generalized(value, _)
Puppet::Pops::Types::TypeCalculator.infer(value).generalize
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/hiera_hash.rb | lib/puppet/functions/hiera_hash.rb | # frozen_string_literal: true
require 'hiera/puppet_function'
# Finds all matches of a key throughout the hierarchy and returns them in a merged hash.
#
# This function is deprecated in favor of the `lookup` function. While this function
# continues to work, it does **not** support:
# * `lookup_options` stored in the data
# * lookup across global, environment, and module layers
#
# If any of the matched hashes share keys, the final hash uses the value from the
# highest priority match. This is called a
# [hash merge lookup](https://puppet.com/docs/hiera/latest/lookup_types.html#hash-merge).
#
# The merge strategy is determined by Hiera's
# [`:merge_behavior`](https://puppet.com/docs/hiera/latest/configuring.html#mergebehavior)
# setting.
#
# The `hiera_hash` function takes up to three arguments, in this order:
#
# 1. A string key that Hiera searches for in the hierarchy. **Required**.
# 2. An optional default value to return if Hiera doesn't find anything matching the key.
# * If this argument isn't provided and this function results in a lookup failure, Puppet
# fails with a compilation error.
# 3. The optional name of an arbitrary
# [hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
# top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
# * If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
# searching the rest of the hierarchy.
#
# @example Using `hiera_hash`
#
# ```yaml
# # Assuming hiera.yaml
# # :hierarchy:
# # - web01.example.com
# # - common
#
# # Assuming common.yaml:
# # users:
# # regular:
# # 'cdouglas': 'Carrie Douglas'
#
# # Assuming web01.example.com.yaml:
# # users:
# # administrators:
# # 'aberry': 'Amy Berry'
# ```
#
# ```puppet
# # Assuming we are not web01.example.com:
#
# $allusers = hiera_hash('users', undef)
#
# # $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
# # administrators => {"aberry" => "Amy Berry"}}
# ```
#
# You can optionally generate the default value with a
# [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
# takes one parameter.
#
# @example Using `hiera_hash` with a lambda
#
# ```puppet
# # Assuming the same Hiera data as the previous example:
#
# $allusers = hiera_hash('users') | $key | { "Key \'${key}\' not found" }
#
# # $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
# # administrators => {"aberry" => "Amy Berry"}}
# # If hiera_hash couldn't match its key, it would return the lambda result,
# # "Key 'users' not found".
# ```
#
# `hiera_hash` expects that all values returned will be hashes. If any of the values
# found in the data sources are strings or arrays, Puppet raises a type mismatch error.
#
# See
# [the 'Using the lookup function' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html) for how to perform lookup of data.
# Also see
# [the 'Using the deprecated hiera functions' documentation](https://puppet.com/docs/puppet/latest/hiera_automatic.html)
# for more information about the Hiera 3 functions.
#
# @since 4.0.0
#
Puppet::Functions.create_function(:hiera_hash, Hiera::PuppetFunction) do
init_dispatch
def merge_type
:hash
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/functions/annotate.rb | lib/puppet/functions/annotate.rb | # frozen_string_literal: true
# Handles annotations on objects. The function can be used in four different ways.
#
# With two arguments, an `Annotation` type and an object, the function returns the annotation
# for the object of the given type, or `undef` if no such annotation exists.
#
# @example Using `annotate` with two arguments
#
# ```puppet
# $annotation = Mod::NickNameAdapter.annotate(o)
#
# $annotation = annotate(Mod::NickNameAdapter.annotate, o)
# ```
#
# With three arguments, an `Annotation` type, an object, and a block, the function returns the
# annotation for the object of the given type, or annotates it with a new annotation initialized
# from the hash returned by the given block when no such annotation exists. The block will not
# be called when an annotation of the given type is already present.
#
# @example Using `annotate` with two arguments and a block
#
# ```puppet
# $annotation = Mod::NickNameAdapter.annotate(o) || { { 'nick_name' => 'Buddy' } }
#
# $annotation = annotate(Mod::NickNameAdapter.annotate, o) || { { 'nick_name' => 'Buddy' } }
# ```
#
# With three arguments, an `Annotation` type, an object, and an `Hash`, the function will annotate
# the given object with a new annotation of the given type that is initialized from the given hash.
# An existing annotation of the given type is discarded.
#
# @example Using `annotate` with three arguments where third argument is a Hash
#
# ```puppet
# $annotation = Mod::NickNameAdapter.annotate(o, { 'nick_name' => 'Buddy' })
#
# $annotation = annotate(Mod::NickNameAdapter.annotate, o, { 'nick_name' => 'Buddy' })
# ```
#
# With three arguments, an `Annotation` type, an object, and an the string `clear`, the function will
# clear the annotation of the given type in the given object. The old annotation is returned if
# it existed.
#
# @example Using `annotate` with three arguments where third argument is the string 'clear'
#
# ```puppet
# $annotation = Mod::NickNameAdapter.annotate(o, clear)
#
# $annotation = annotate(Mod::NickNameAdapter.annotate, o, clear)
# ```
#
# With three arguments, the type `Pcore`, an object, and a Hash of hashes keyed by `Annotation` types,
# the function will annotate the given object with all types used as keys in the given hash. Each annotation
# is initialized with the nested hash for the respective type. The annotated object is returned.
#
# @example Add multiple annotations to a new instance of `Mod::Person` using the `Pcore` type.
#
# ```puppet
# $person = Pcore.annotate(Mod::Person({'name' => 'William'}), {
# Mod::NickNameAdapter >= { 'nick_name' => 'Bill' },
# Mod::HobbiesAdapter => { 'hobbies' => ['Ham Radio', 'Philatelist'] }
# })
# ```
#
# @since 5.0.0
#
Puppet::Functions.create_function(:annotate) do
dispatch :annotate do
param 'Type[Annotation]', :type
param 'Any', :value
optional_block_param 'Callable[0, 0]', :block
end
dispatch :annotate_new do
param 'Type[Annotation]', :type
param 'Any', :value
param 'Variant[Enum[clear],Hash[Pcore::MemberName,Any]]', :annotation_hash
end
dispatch :annotate_multi do
param 'Type[Pcore]', :type
param 'Any', :value
param 'Hash[Type[Annotation], Hash[Pcore::MemberName,Any]]', :annotations
end
# @param type [Annotation] the annotation type
# @param value [Object] the value to annotate
# @param block [Proc] optional block to produce the annotation hash
#
def annotate(type, value, &block)
type.implementation_class.annotate(value, &block)
end
# @param type [Annotation] the annotation type
# @param value [Object] the value to annotate
# @param annotation_hash [Hash{String => Object}] the annotation hash
#
def annotate_new(type, value, annotation_hash)
type.implementation_class.annotate_new(value, annotation_hash)
end
# @param type [Type] the Pcore type
# @param value [Object] the value to annotate
# @param annotations [Hash{Annotation => Hash{String => Object}}] hash of annotation hashes
#
def annotate_multi(type, value, annotations)
type.implementation_class.annotate(value, annotations)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.