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 |
|---|---|---|---|---|---|---|---|---|
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/docs.rb | lib/puppet/util/docs.rb | # frozen_string_literal: true
# Some simple methods for helping manage automatic documentation generation.
module Puppet::Util::Docs
# Specify the actual doc string.
def desc(str)
@doc = str
end
# Add a new autodoc block. We have to define these as class methods,
# rather than just sticking them in a hash, because otherwise they're
# too difficult to do inheritance with.
def dochook(name, &block)
method = "dochook_#{name}"
meta_def method, &block
end
attr_writer :doc
# Generate the full doc string.
def doc
extra = methods.find_all { |m| m.to_s =~ /^dochook_.+/ }.sort.filter_map { |m|
send(m)
}.collect { |r| "* #{r}" }.join("\n")
if @doc
scrub(@doc) + (extra.empty? ? '' : "\n\n#{extra}")
else
extra
end
end
# Build a table
def doctable(headers, data)
str = "\n\n"
lengths = []
# Figure out the longest field for all columns
data.each do |name, values|
[name, values].flatten.each_with_index do |value, i|
lengths[i] ||= 0
lengths[i] = value.to_s.length if value.to_s.length > lengths[i]
end
end
# The headers could also be longest
headers.each_with_index do |value, i|
lengths[i] = value.to_s.length if value.to_s.length > lengths[i]
end
# Add the header names
str += headers.zip(lengths).collect { |value, num| pad(value, num) }.join(" | ") + " |" + "\n"
# And the header row
str += lengths.collect { |num| "-" * num }.join(" | ") + " |" + "\n"
# Now each data row
data.sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, rows|
str += [name, rows].flatten.zip(lengths).collect do |value, length|
pad(value, length)
end.join(" | ") + " |" + "\n"
end
str + "\n"
end
# There is nothing that would ever set this. It gets read in reference/type.rb, but will never have any value but nil.
attr_reader :nodoc
def nodoc?
nodoc
end
# Pad a field with spaces
def pad(value, length)
value.to_s + (" " * (length - value.to_s.length))
end
HEADER_LEVELS = [nil, "#", "##", "###", "####", "#####"]
def markdown_header(name, level)
"#{HEADER_LEVELS[level]} #{name}\n\n"
end
def markdown_definitionlist(term, definition)
lines = scrub(definition).split("\n")
str = "#{term}\n: #{lines.shift}\n"
lines.each do |line|
str << " " if line =~ /\S/
str << "#{line}\n"
end
str << "\n"
end
# Strip indentation and trailing whitespace from embedded doc fragments.
#
# Multi-line doc fragments are sometimes indented in order to preserve the
# formatting of the code they're embedded in. Since indents are syntactic
# elements in Markdown, we need to make sure we remove any indent that was
# added solely to preserve surrounding code formatting, but LEAVE any indent
# that delineates a Markdown element (code blocks, multi-line bulleted list
# items). We can do this by removing the *least common indent* from each line.
#
# Least common indent is defined as follows:
#
# * Find the smallest amount of leading space on any line...
# * ...excluding the first line (which may have zero indent without affecting
# the common indent)...
# * ...and excluding lines that consist solely of whitespace.
# * The least common indent may be a zero-length string, if the fragment is
# not indented to match code.
# * If there are hard tabs for some dumb reason, we assume they're at least
# consistent within this doc fragment.
#
# See tests in spec/unit/util/docs_spec.rb for examples.
def scrub(text)
# One-liners are easy! (One-liners may be buffered with extra newlines.)
return text.strip if text.strip !~ /\n/
excluding_first_line = text.partition("\n").last
indent = excluding_first_line.scan(/^[ \t]*(?=\S)/).min || '' # prevent nil
# Clean hanging indent, if any
if indent.length > 0
text = text.gsub(/^#{indent}/, '')
end
# Clean trailing space
text.lines.map(&:rstrip).join("\n").rstrip
end
module_function :scrub
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/logging.rb | lib/puppet/util/logging.rb | # frozen_string_literal: true
# A module to make logging a bit easier.
require_relative '../../puppet/util/log'
require_relative '../../puppet/error'
module Puppet::Util
module Logging
def send_log(level, message)
Puppet::Util::Log.create({ :level => level, :source => log_source, :message => message }.merge(log_metadata))
end
# Create a method for each log level.
Puppet::Util::Log.eachlevel do |level|
# handle debug a special way for performance reasons
next if level == :debug
define_method(level) do |args|
args = args.join(" ") if args.is_a?(Array)
send_log(level, args)
end
end
# Output a debug log message if debugging is on (but only then)
# If the output is anything except a static string, give the debug
# a block - it will be called with all other arguments, and is expected
# to return the single string result.
#
# Use a block at all times for increased performance.
#
# @example This takes 40% of the time compared to not using a block
# Puppet.debug { "This is a string that interpolated #{x} and #{y} }"
#
def debug(*args)
return nil unless Puppet::Util::Log.level == :debug
if block_given?
send_log(:debug, yield(*args))
else
send_log(:debug, args.join(" "))
end
end
# Log an exception via Puppet.err. Will also log the backtrace if Puppet[:trace] is set.
# Parameters:
# [exception] an Exception to log
# [message] an optional String overriding the message to be logged; by default, we log Exception.message.
# If you pass a String here, your string will be logged instead. You may also pass nil if you don't
# wish to log a message at all; in this case it is likely that you are only calling this method in order
# to take advantage of the backtrace logging.
def log_exception(exception, message = :default, options = {})
level = options[:level] || :err
combined_trace = Puppet[:trace] || options[:trace]
puppet_trace = Puppet[:puppet_trace] || options[:puppet_trace]
if message == :default && exception.is_a?(Puppet::ParseErrorWithIssue)
# Retain all detailed info and keep plain message and stacktrace separate
backtrace = build_exception_trace(exception, combined_trace, puppet_trace)
Puppet::Util::Log.create({
:level => level,
:source => log_source,
:message => exception.basic_message,
:issue_code => exception.issue_code,
:backtrace => backtrace.empty? ? nil : backtrace,
:file => exception.file,
:line => exception.line,
:pos => exception.pos,
:environment => exception.environment,
:node => exception.node
}.merge(log_metadata))
else
send_log(level, format_exception(exception, message, combined_trace, puppet_trace))
end
end
def build_exception_trace(exception, combined_trace = true, puppet_trace = false)
built_trace = format_backtrace(exception, combined_trace, puppet_trace)
if exception.respond_to?(:original)
original = exception.original
unless original.nil?
built_trace << _('Wrapped exception:')
built_trace << original.message
built_trace += build_exception_trace(original, combined_trace, puppet_trace)
end
end
built_trace
end
private :build_exception_trace
def format_exception(exception, message = :default, combined_trace = true, puppet_trace = false)
arr = []
case message
when :default
arr << exception.message
when nil
# don't log anything if they passed a nil; they are just calling for the optional backtrace logging
else
arr << message
end
arr += format_backtrace(exception, combined_trace, puppet_trace)
if exception.respond_to?(:original) and exception.original
arr << _("Wrapped exception:")
arr << format_exception(exception.original, :default, combined_trace, puppet_trace)
end
arr.flatten.join("\n")
end
def format_backtrace(exception, combined_trace, puppet_trace)
puppetstack = exception.respond_to?(:puppetstack) ? exception.puppetstack : []
if combined_trace and exception.backtrace
Puppet::Util.format_backtrace_array(exception.backtrace, puppetstack)
elsif puppet_trace && !puppetstack.empty?
Puppet::Util.format_backtrace_array(puppetstack)
else
[]
end
end
def log_and_raise(exception, message)
log_exception(exception, message)
raise exception, message + "\n" + exception.to_s, exception.backtrace
end
class DeprecationWarning < Exception; end # rubocop:disable Lint/InheritException
# Logs a warning indicating that the Ruby code path is deprecated. Note that
# this method keeps track of the offending lines of code that triggered the
# deprecation warning, and will only log a warning once per offending line of
# code. It will also stop logging deprecation warnings altogether after 100
# unique deprecation warnings have been logged. Finally, if
# Puppet[:disable_warnings] includes 'deprecations', it will squelch all
# warning calls made via this method.
#
# @param message [String] The message to log (logs via warning)
# @param key [String] Optional key to mark the message as unique. If not
# passed in, the originating call line will be used instead.
def deprecation_warning(message, key = nil)
issue_deprecation_warning(message, key, nil, nil, true)
end
# Logs a warning whose origin comes from Puppet source rather than somewhere
# internal within Puppet. Otherwise the same as deprecation_warning()
#
# @param message [String] The message to log (logs via warning)
# @param options [Hash]
# @option options [String] :file File we are warning from
# @option options [Integer] :line Line number we are warning from
# @option options [String] :key (:file + :line) Alternative key used to mark
# warning as unique
#
# Either :file and :line and/or :key must be passed.
def puppet_deprecation_warning(message, options = {})
key = options[:key]
file = options[:file]
line = options[:line]
# TRANSLATORS the literals ":file", ":line", and ":key" should not be translated
raise Puppet::DevError, _("Need either :file and :line, or :key") if key.nil? && (file.nil? || line.nil?)
key ||= "#{file}:#{line}"
issue_deprecation_warning(message, key, file, line, false)
end
# Logs a (non deprecation) warning once for a given key.
#
# @param kind [String] The kind of warning. The
# kind must be one of the defined kinds for the Puppet[:disable_warnings] setting.
# @param message [String] The message to log (logs via warning)
# @param key [String] Key used to make this warning unique
# @param file [String,:default,nil] the File related to the warning
# @param line [Integer,:default,nil] the Line number related to the warning
# warning as unique
# @param level [Symbol] log level to use, defaults to :warning
#
# Either :file and :line and/or :key must be passed.
def warn_once(kind, key, message, file = nil, line = nil, level = :warning)
return if Puppet[:disable_warnings].include?(kind)
$unique_warnings ||= {}
if $unique_warnings.length < 100 then
unless $unique_warnings.has_key?(key) then
$unique_warnings[key] = message
call_trace = if file == :default and line == :default
# Suppress the file and line number output
''
else
error_location_str = Puppet::Util::Errors.error_location(file, line)
if error_location_str.empty?
"\n " + _('(file & line not available)')
else
"\n %{error_location}" % { error_location: error_location_str }
end
end
send_log(level, "#{message}#{call_trace}")
end
end
end
def get_deprecation_offender
# we have to put this in its own method to simplify testing; we need to be able to mock the offender results in
# order to test this class, and our framework does not appear to enjoy it if you try to mock Kernel.caller
#
# let's find the offending line; we need to jump back up the stack a few steps to find the method that called
# the deprecated method
if Puppet[:trace]
caller(3)
else
[caller(3, 1).first]
end
end
def clear_deprecation_warnings
$unique_warnings.clear if $unique_warnings
$deprecation_warnings.clear if $deprecation_warnings
end
# TODO: determine whether there might be a potential use for adding a puppet configuration option that would
# enable this deprecation logging.
# utility method that can be called, e.g., from spec_helper config.after, when tracking down calls to deprecated
# code.
# Parameters:
# [deprecations_file] relative or absolute path of a file to log the deprecations to
# [pattern] (default nil) if specified, will only log deprecations whose message matches the provided pattern
def log_deprecations_to_file(deprecations_file, pattern = nil)
# this method may get called lots and lots of times (e.g., from spec_helper config.after) without the global
# list of deprecation warnings being cleared out. We don't want to keep logging the same offenders over and over,
# so, we need to keep track of what we've logged.
#
# It'd be nice if we could just clear out the list of deprecation warnings, but then the very next spec might
# find the same offender, and we'd end up logging it again.
$logged_deprecation_warnings ||= {}
# Deprecation messages are UTF-8 as they are produced by Ruby
Puppet::FileSystem.open(deprecations_file, nil, "a:UTF-8") do |f|
if $deprecation_warnings then
$deprecation_warnings.each do |offender, message|
next if $logged_deprecation_warnings.has_key?(offender)
$logged_deprecation_warnings[offender] = true
next unless pattern.nil? || (message =~ pattern)
f.puts(message)
f.puts(offender)
f.puts()
end
end
end
end
# Sets up Facter logging.
# This method causes Facter output to be forwarded to Puppet.
def self.setup_facter_logging!
Puppet.runtime[:facter]
true
end
private
def issue_deprecation_warning(message, key, file, line, use_caller)
return if Puppet[:disable_warnings].include?('deprecations')
$deprecation_warnings ||= {}
if $deprecation_warnings.length < 100
key ||= (offender = get_deprecation_offender)
unless $deprecation_warnings.has_key?(key)
$deprecation_warnings[key] = message
# split out to allow translation
call_trace = if use_caller
_("(location: %{location})") % { location: (offender || get_deprecation_offender).join('; ') }
else
Puppet::Util::Errors.error_location_with_unknowns(file, line)
end
warning("%{message}\n %{call_trace}" % { message: message, call_trace: call_trace })
end
end
end
def is_resource?
defined?(Puppet::Type) && is_a?(Puppet::Type)
end
def is_resource_parameter?
defined?(Puppet::Parameter) && is_a?(Puppet::Parameter)
end
def log_metadata
[:file, :line, :tags].each_with_object({}) do |attr, result|
result[attr] = send(attr) if respond_to?(attr)
end
end
def log_source
# We need to guard the existence of the constants, since this module is used by the base Puppet module.
(is_resource? or is_resource_parameter?) and respond_to?(:path) and return path.to_s
to_s
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/inifile.rb | lib/puppet/util/inifile.rb | # frozen_string_literal: true
# Module Puppet::IniConfig
# A generic way to parse .ini style files and manipulate them in memory
# One 'file' can be made up of several physical files. Changes to sections
# on the file are tracked so that only the physical files in which
# something has changed are written back to disk
# Great care is taken to preserve comments and blank lines from the original
# files
#
# The parsing tries to stay close to python's ConfigParser
require_relative '../../puppet/util/filetype'
require_relative '../../puppet/error'
module Puppet::Util::IniConfig
# A section in a .ini file
class Section
attr_reader :name, :file, :entries
attr_writer :destroy
def initialize(name, file)
@name = name
@file = file
@dirty = false
@entries = []
@destroy = false
end
# Does this section need to be updated in/removed from the associated file?
#
# @note This section is dirty if a key has been modified _or_ if the
# section has been modified so the associated file can be rewritten
# without this section.
def dirty?
@dirty or @destroy
end
def mark_dirty
@dirty = true
end
# Should only be used internally
def mark_clean
@dirty = false
end
# Should the file be destroyed?
def destroy?
@destroy
end
# Add a line of text (e.g., a comment) Such lines
# will be written back out in exactly the same
# place they were read in
def add_line(line)
@entries << line
end
# Set the entry 'key=value'. If no entry with the
# given key exists, one is appended to the end of the section
def []=(key, value)
entry = find_entry(key)
@dirty = true
if entry.nil?
@entries << [key, value]
else
entry[1] = value
end
end
# Return the value associated with KEY. If no such entry
# exists, return nil
def [](key)
entry = find_entry(key)
(entry.nil? ? nil : entry[1])
end
# Format the section as text in the way it should be
# written to file
def format
if @destroy
text = ''.dup
else
text = "[#{name}]\n"
@entries.each do |entry|
if entry.is_a?(Array)
key, value = entry
text << "#{key}=#{value}\n" unless value.nil?
else
text << entry
end
end
end
text
end
private
def find_entry(key)
@entries.each do |entry|
return entry if entry.is_a?(Array) && entry[0] == key
end
nil
end
end
class PhysicalFile
# @!attribute [r] filetype
# @api private
# @return [Puppet::Util::FileType::FileTypeFlat]
attr_reader :filetype
# @!attribute [r] contents
# @api private
# @return [Array<String, Puppet::Util::IniConfig::Section>]
attr_reader :contents
# @!attribute [rw] destroy_empty
# Whether empty files should be removed if no sections are defined.
# Defaults to false
attr_accessor :destroy_empty
# @!attribute [rw] file_collection
# @return [Puppet::Util::IniConfig::FileCollection]
attr_accessor :file_collection
def initialize(file, options = {})
@file = file
@contents = []
@filetype = Puppet::Util::FileType.filetype(:flat).new(file)
@destroy_empty = options.fetch(:destroy_empty, false)
end
# Read and parse the on-disk file associated with this object
def read
text = @filetype.read
if text.nil?
raise IniParseError, _("Cannot read nonexistent file %{file}") % { file: @file.inspect }
end
parse(text)
end
INI_COMMENT = Regexp.union(
/^\s*$/,
/^[#;]/,
/^\s*rem\s/i
)
INI_CONTINUATION = /^[ \t\r\n\f]/
INI_SECTION_NAME = /^\[([^\]]+)\]/
INI_PROPERTY = /^\s*([^\s=]+)\s*=\s*(.*)$/
# @api private
def parse(text)
section = nil # The name of the current section
optname = nil # The name of the last option in section
line_num = 0
text.each_line do |l|
line_num += 1
if l.match(INI_COMMENT)
# Whitespace or comment
if section.nil?
@contents << l
else
section.add_line(l)
end
elsif l.match(INI_CONTINUATION) && section && optname
# continuation line
section[optname] += "\n#{l.chomp}"
elsif (match = l.match(INI_SECTION_NAME))
# section heading
section.mark_clean if section
section_name = match[1]
section = add_section(section_name)
optname = nil
elsif (match = l.match(INI_PROPERTY))
# the regex strips leading white space from the value, and here we strip the trailing white space as well
key = match[1]
val = match[2].rstrip
if section.nil?
raise IniParseError, _("Property with key %{key} outside of a section") % { key: key.inspect }
end
section[key] = val
optname = key
else
raise IniParseError.new(_("Can't parse line '%{line}'") % { line: l.chomp }, @file, line_num)
end
end
section.mark_clean unless section.nil?
end
# @return [Array<Puppet::Util::IniConfig::Section>] All sections defined in
# this file.
def sections
@contents.select { |entry| entry.is_a? Section }
end
# @return [Puppet::Util::IniConfig::Section, nil] The section with the
# given name if it exists, else nil.
def get_section(name)
@contents.find { |entry| entry.is_a? Section and entry.name == name }
end
def format
text = ''.dup
@contents.each do |content|
if content.is_a? Section
text << content.format
else
text << content
end
end
text
end
def store
if @destroy_empty and (sections.empty? or sections.all?(&:destroy?))
::File.unlink(@file)
elsif sections.any?(&:dirty?)
text = self.format
@filetype.write(text)
end
sections.each(&:mark_clean)
end
# Create a new section and store it in the file contents
#
# @api private
# @param name [String] The name of the section to create
# @return [Puppet::Util::IniConfig::Section]
def add_section(name)
if section_exists?(name)
raise IniParseError.new(_("Section %{name} is already defined, cannot redefine") % { name: name.inspect }, @file)
end
section = Section.new(name, @file)
@contents << section
section
end
private
def section_exists?(name)
if get_section(name)
true
elsif @file_collection and @file_collection.get_section(name)
true
else
false
end
end
end
class FileCollection
attr_reader :files
def initialize
@files = {}
end
# Read and parse a file and store it in the collection. If the file has
# already been read it will be destroyed and re-read.
def read(file)
new_physical_file(file).read
end
def store
@files.values.each(&:store)
end
def each_section(&block)
@files.values.each do |file|
file.sections.each do |section|
yield section
end
end
end
def each_file(&block)
@files.keys.each do |path|
yield path
end
end
def get_section(name)
sect = nil
@files.values.each do |file|
if (current = file.get_section(name))
sect = current
end
end
sect
end
alias [] get_section
def include?(name)
!!get_section(name)
end
def add_section(name, file)
get_physical_file(file).add_section(name)
end
private
# Return a file if it's already been defined, create a new file if it hasn't
# been defined.
def get_physical_file(file)
@files[file] || new_physical_file(file)
end
# Create a new physical file and set required attributes on that file.
def new_physical_file(file)
@files[file] = PhysicalFile.new(file)
@files[file].file_collection = self
@files[file]
end
end
File = FileCollection
class IniParseError < Puppet::Error
include Puppet::ExternalFileError
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/warnings.rb | lib/puppet/util/warnings.rb | # frozen_string_literal: true
# Methods to help with handling warnings.
module Puppet::Util::Warnings
module_function
def notice_once(msg)
Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.notice msg }
end
def debug_once(msg)
return nil unless Puppet[:debug]
Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.debug msg }
end
def warnonce(msg)
Puppet::Util::Warnings.maybe_log(msg, self.class) { Puppet.warning msg }
end
def clear_warnings
@stampwarnings = {}
nil
end
def self.maybe_log(message, klass)
@stampwarnings ||= {}
@stampwarnings[klass] ||= []
return nil if @stampwarnings[klass].include? message
yield
@stampwarnings[klass] << message
nil
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/yaml.rb | lib/puppet/util/yaml.rb | # frozen_string_literal: true
require 'yaml'
module Puppet::Util::Yaml
YamlLoadExceptions = [::StandardError, ::Psych::Exception]
class YamlLoadError < Puppet::Error; end
# Safely load the content as YAML. By default only the following
# classes can be deserialized:
#
# * TrueClass
# * FalseClass
# * NilClass
# * Numeric
# * String
# * Array
# * Hash
#
# Attempting to deserialize other classes will raise an YamlLoadError
# exception unless they are specified in the array of *allowed_classes*.
# @param [String] yaml The yaml content to parse.
# @param [Array] allowed_classes Additional list of classes that can be deserialized.
# @param [String] filename The filename to load from, used if an exception is raised.
# @raise [YamlLoadException] If deserialization fails.
# @return The parsed YAML, which can be Hash, Array or scalar types.
def self.safe_load(yaml, allowed_classes = [], filename = nil)
if Gem::Version.new(Psych::VERSION) >= Gem::Version.new('3.1.0')
data = YAML.safe_load(yaml, permitted_classes: allowed_classes, aliases: true, filename: filename)
else
data = YAML.safe_load(yaml, allowed_classes, [], true, filename)
end
data = false if data.nil?
data
rescue ::Psych::DisallowedClass => detail
path = filename ? "(#{filename})" : "(<unknown>)"
raise YamlLoadError.new("#{path}: #{detail.message}", detail)
rescue *YamlLoadExceptions => detail
raise YamlLoadError.new(detail.message, detail)
end
# Safely load the content from a file as YAML.
#
# @see Puppet::Util::Yaml.safe_load
def self.safe_load_file(filename, allowed_classes = [])
yaml = Puppet::FileSystem.read(filename, :encoding => 'bom|utf-8')
safe_load(yaml, allowed_classes, filename)
end
# Safely load the content from a file as YAML if
# contents are in valid format. This method does not
# raise error but returns `nil` when invalid file is
# given.
def self.safe_load_file_if_valid(filename, allowed_classes = [])
safe_load_file(filename, allowed_classes)
rescue YamlLoadError, ArgumentError, Errno::ENOENT => detail
Puppet.debug("Could not retrieve YAML content from '#{filename}': #{detail.message}")
nil
end
def self.dump(structure, filename)
Puppet::FileSystem.replace_file(filename, 0o660) do |fh|
YAML.dump(structure, fh)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/selinux.rb | lib/puppet/util/selinux.rb | # frozen_string_literal: true
# Provides utility functions to help interface Puppet to SELinux.
#
# This requires the very new SELinux Ruby bindings. These bindings closely
# mirror the SELinux C library interface.
#
# Support for the command line tools is not provided because the performance
# was abysmal. At this time (2008-11-02) the only distribution providing
# these Ruby SELinux bindings which I am aware of is Fedora (in libselinux-ruby).
Puppet.features.selinux? # check, but continue even if it's not
require 'pathname'
module Puppet::Util::SELinux
S_IFREG = 0o100000
S_IFDIR = 0o040000
S_IFLNK = 0o120000
def self.selinux_support?
return false unless defined?(Selinux)
if Selinux.is_selinux_enabled == 1
return true
end
false
end
def selinux_support?
Puppet::Util::SELinux.selinux_support?
end
# Retrieve and return the full context of the file. If we don't have
# SELinux support or if the SELinux call fails then return nil.
def get_selinux_current_context(file)
return nil unless selinux_support?
retval = Selinux.lgetfilecon(file)
if retval == -1
return nil
end
retval[1]
end
# Retrieve and return the default context of the file. If we don't have
# SELinux support or if the SELinux call fails to file a default then return nil.
# @deprecated matchpathcon is a deprecated method, selabel_lookup is preferred
def get_selinux_default_context(file, resource_ensure = nil)
return nil unless selinux_support?
# If the filesystem has no support for SELinux labels, return a default of nil
# instead of what matchpathcon would return
return nil unless selinux_label_support?(file)
# If the file exists we should pass the mode to matchpathcon for the most specific
# matching. If not, we can pass a mode of 0.
mode = file_mode(file, resource_ensure)
retval = Selinux.matchpathcon(file, mode)
retval == -1 ? nil : retval[1]
end
# Retrieve and return the default context of the file using an selinux handle.
# If we don't have SELinux support or if the SELinux call fails to file a
# default then return nil.
def get_selinux_default_context_with_handle(file, handle, resource_ensure = nil)
return nil unless selinux_support?
# If the filesystem has no support for SELinux labels, return a default of nil
# instead of what selabel_lookup would return
return nil unless selinux_label_support?(file)
# Handle is needed for selabel_lookup
raise ArgumentError, _("Cannot get default context with nil handle") unless handle
# If the file exists we should pass the mode to selabel_lookup for the most specific
# matching. If not, we can pass a mode of 0.
mode = file_mode(file, resource_ensure)
retval = Selinux.selabel_lookup(handle, file, mode)
retval == -1 ? nil : retval[1]
end
# Take the full SELinux context returned from the tools and parse it
# out to the three (or four) component parts. Supports :seluser, :selrole,
# :seltype, and on systems with range support, :selrange.
def parse_selinux_context(component, context)
if context.nil? or context == "unlabeled"
return nil
end
components = /^([^\s:]+):([^\s:]+):([^\s:]+)(?::([\sa-zA-Z0-9:,._-]+))?$/.match(context)
unless components
raise Puppet::Error, _("Invalid context to parse: %{context}") % { context: context }
end
case component
when :seluser
components[1]
when :selrole
components[2]
when :seltype
components[3]
when :selrange
components[4]
else
raise Puppet::Error, _("Invalid SELinux parameter type")
end
end
# This updates the actual SELinux label on the file. You can update
# only a single component or update the entire context.
# The caveat is that since setting a partial context makes no sense the
# file has to already exist. Puppet (via the File resource) will always
# just try to set components, even if all values are specified by the manifest.
# I believe that the OS should always provide at least a fall-through context
# though on any well-running system.
def set_selinux_context(file, value, component = false)
return nil unless selinux_support? && selinux_label_support?(file)
if component
# Must first get existing context to replace a single component
context = Selinux.lgetfilecon(file)[1]
if context == -1
# We can't set partial context components when no context exists
# unless/until we can find a way to make Puppet call this method
# once for all selinux file label attributes.
Puppet.warning _("Can't set SELinux context on file unless the file already has some kind of context")
return nil
end
context = context.split(':')
case component
when :seluser
context[0] = value
when :selrole
context[1] = value
when :seltype
context[2] = value
when :selrange
context[3] = value
else
raise ArgumentError, _("set_selinux_context component must be one of :seluser, :selrole, :seltype, or :selrange")
end
context = context.join(':')
else
context = value
end
retval = Selinux.lsetfilecon(file, context)
if retval == 0
true
else
Puppet.warning _("Failed to set SELinux context %{context} on %{file}") % { context: context, file: file }
false
end
end
# Since this call relies on get_selinux_default_context it also needs a
# full non-relative path to the file. Fortunately, that seems to be all
# Puppet uses. This will set the file's SELinux context to the policy's
# default context (if any) if it differs from the context currently on
# the file.
def set_selinux_default_context(file, resource_ensure = nil)
new_context = get_selinux_default_context(file, resource_ensure)
return nil unless new_context
cur_context = get_selinux_current_context(file)
if new_context != cur_context
set_selinux_context(file, new_context)
return new_context
end
nil
end
##
# selinux_category_to_label is an internal method that converts all
# selinux categories to their internal representation, avoiding
# potential issues when mcstransd is not functional.
#
# It is not marked private because it is needed by File's
# selcontext.rb, but it is not intended for use outside of Puppet's
# code.
#
# @param category [String] An selinux category, such as "s0" or "SystemLow"
#
# @return [String] the numeric category name, such as "s0"
def selinux_category_to_label(category)
# We don't cache this, but there's already a ton of duplicate work
# in the selinux handling code.
path = Selinux.selinux_translations_path
begin
File.open(path).each do |line|
line.strip!
next if line.empty?
next if line[0] == "#" # skip comments
line.gsub!(/[[:space:]]+/m, '')
mapping = line.split("=", 2)
if category == mapping[1]
return mapping[0]
end
end
rescue SystemCallError => ex
log_exception(ex)
raise Puppet::Error, _("Could not open SELinux category translation file %{path}.") % { context: context }
end
category
end
########################################################################
# Internal helper methods from here on in, kids. Don't fiddle.
private
# Check filesystem a path resides on for SELinux support against
# whitelist of known-good filesystems.
# Returns true if the filesystem can support SELinux labels and
# false if not.
def selinux_label_support?(file)
fstype = find_fs(file)
return false if fstype.nil?
filesystems = %w[ext2 ext3 ext4 gfs gfs2 xfs jfs btrfs tmpfs zfs]
filesystems.include?(fstype)
end
# Get mode file type bits set based on ensure on
# the file resource. This helps SELinux determine
# what context a new resource being created should have.
def get_create_mode(resource_ensure)
mode = 0
case resource_ensure
when :present, :file
mode |= S_IFREG
when :directory
mode |= S_IFDIR
when :link
mode |= S_IFLNK
end
mode
end
# If the file/directory/symlink exists, return its mode. Otherwise, get the default mode
# that should be used to create the file/directory/symlink taking into account the desired
# file type specified in +resource_ensure+.
def file_mode(file, resource_ensure)
filestat = file_lstat(file)
filestat.mode
rescue Errno::EACCES
0
rescue Errno::ENOENT
if resource_ensure
get_create_mode(resource_ensure)
else
0
end
end
# Internal helper function to read and parse /proc/mounts
def read_mounts
mounts = ''.dup
begin
if File.method_defined? "read_nonblock"
# If possible we use read_nonblock in a loop rather than read to work-
# a linux kernel bug. See ticket #1963 for details.
mountfh = File.new("/proc/mounts")
loop do
mounts += mountfh.read_nonblock(1024)
end
else
# Otherwise we shell out and let cat do it for us
mountfh = IO.popen("/bin/cat /proc/mounts")
mounts = mountfh.read
end
rescue EOFError
# that's expected
rescue
return nil
ensure
mountfh.close if mountfh
end
mntpoint = {}
# Read all entries in /proc/mounts. The second column is the
# mountpoint and the third column is the filesystem type.
# We skip rootfs because it is always mounted at /
mounts.each_line do |line|
params = line.split(' ')
next if params[2] == 'rootfs'
mntpoint[params[1]] = params[2]
end
mntpoint
end
# Internal helper function to return which type of filesystem a given file
# path resides on
def find_fs(path)
mounts = read_mounts
return nil unless mounts
# cleanpath eliminates useless parts of the path (like '.', or '..', or
# multiple slashes), without touching the filesystem, and without
# following symbolic links. This gives the right (logical) tree to follow
# while we try and figure out what file-system the target lives on.
path = Pathname(path).cleanpath
unless path.absolute?
raise Puppet::DevError, _("got a relative path in SELinux find_fs: %{path}") % { path: path }
end
# Now, walk up the tree until we find a match for that path in the hash.
path.ascend do |segment|
return mounts[segment.to_s] if mounts.has_key?(segment.to_s)
end
# Should never be reached...
mounts['/']
end
##
# file_lstat is an internal, private method to allow precise stubbing and
# mocking without affecting the rest of the system.
#
# @return [File::Stat] File.lstat result
def file_lstat(path)
Puppet::FileSystem.lstat(path)
end
private :file_lstat
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/feature.rb | lib/puppet/util/feature.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/util/warnings'
class Puppet::Util::Feature
include Puppet::Util::Warnings
attr_reader :path
# Create a new feature test. You have to pass the feature name, and it must be
# unique. You can pass a block to determine if the feature is present:
#
# Puppet.features.add(:myfeature) do
# # return true or false if feature is available
# # return nil if feature may become available later
# end
#
# The block should return true if the feature is available, false if it is
# not, or nil if the state is unknown. True and false values will be cached. A
# nil value will not be cached, and should be used if the feature may become
# true in the future.
#
# Features are often used to detect if a ruby library is installed. To support
# that common case, you can pass one or more ruby libraries, and the feature
# will be true if all of the libraries load successfully:
#
# Puppet.features.add(:myfeature, libs: 'mylib')
# Puppet.features.add(:myfeature, libs: ['mylib', 'myotherlib'])
#
# If the ruby library is not installed, then the failure is not cached, as
# it's assumed puppet may install the gem during catalog application.
#
# If a feature is defined using `:libs` and a block, then the block is
# used and the `:libs` are ignored.
#
# Puppet evaluates the feature test when the `Puppet.features.myfeature?`
# method is called. If the feature test was defined using a block and the
# block returns nil, then the feature test will be re-evaluated the next time
# `Puppet.features.myfeature?` is called.
#
# @param [Symbol] name The unique feature name
# @param [Hash<Symbol,Array<String>>] options The libraries to load
def add(name, options = {}, &block)
method = name.to_s + "?"
@results.delete(name)
meta_def(method) do
# we return a cached result if:
# * if we've tested this feature before
# AND
# * the result was true/false
# OR
# * we're configured to never retry
unless @results.has_key?(name) &&
(!@results[name].nil? || !Puppet[:always_retry_plugins])
@results[name] = test(name, options, &block)
end
!!@results[name]
end
end
# Create a new feature collection.
def initialize(path)
@path = path
@results = {}
@loader = Puppet::Util::Autoload.new(self, @path)
end
def load
@loader.loadall(Puppet.lookup(:current_environment))
end
def method_missing(method, *args)
return super unless method.to_s =~ /\?$/
feature = method.to_s.sub(/\?$/, '')
@loader.load(feature, Puppet.lookup(:current_environment))
respond_to?(method) && send(method)
end
# Actually test whether the feature is present. We only want to test when
# someone asks for the feature, so we don't unnecessarily load
# files.
def test(name, options, &block)
if block_given?
begin
result = yield
rescue StandardError, ScriptError => detail
warn _("Failed to load feature test for %{name}: %{detail}") % { name: name, detail: detail }
result = nil
end
@results[name] = result
result
else
libs = options[:libs]
if libs
libs = [libs] unless libs.is_a?(Array)
libs.all? { |lib| load_library(lib, name) } ? true : nil
else
true
end
end
end
private
def load_library(lib, name)
raise ArgumentError, _("Libraries must be passed as strings not %{klass}") % { klass: lib.class } unless lib.is_a?(String)
@rubygems ||= Puppet::Util::RubyGems::Source.new
@rubygems.clear_paths
begin
require lib
true
rescue LoadError
# Expected case. Required library insn't installed.
debug_once(_("Could not find library '%{lib}' required to enable feature '%{name}'") %
{ lib: lib, name: name })
false
rescue StandardError, ScriptError => detail
debug_once(_("Exception occurred while loading library '%{lib}' required to enable feature '%{name}': %{detail}") %
{ lib: lib, name: name, detail: detail })
false
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/resource_template.rb | lib/puppet/util/resource_template.rb | # frozen_string_literal: true
require_relative '../../puppet/util'
require_relative '../../puppet/util/logging'
require 'erb'
# A template wrapper that evaluates a template in the
# context of a resource, allowing the resource attributes
# to be looked up from within the template.
# This provides functionality essentially equivalent to
# the language's template() function. You pass your file
# path and the resource you want to use into the initialization
# method, then call result on the instance, and you get back
# a chunk of text.
# The resource's parameters are available as instance variables
# (as opposed to the language, where we use a method_missing trick).
# For example, say you have a resource that generates a file. You would
# need to implement the following style of `generate` method:
#
# def generate
# template = Puppet::Util::ResourceTemplate.new("/path/to/template", self)
#
# return Puppet::Type.type(:file).new :path => "/my/file",
# :content => template.evaluate
# end
#
# This generated file gets added to the catalog (which is what `generate` does),
# and its content is the result of the template. You need to use instance
# variables in your template, so if your template just needs to have the name
# of the generating resource, it would just have:
#
# <%= @name %>
#
# Since the ResourceTemplate class sets as instance variables all of the resource's
# parameters.
#
# Note that this example uses the generating resource as its source of
# parameters, which is generally most useful, since it allows you to configure
# the generated resource via the generating resource.
class Puppet::Util::ResourceTemplate
include Puppet::Util::Logging
def evaluate
set_resource_variables
Puppet::Util.create_erb(Puppet::FileSystem.read(@file, :encoding => 'utf-8')).result(binding)
end
def initialize(file, resource)
raise ArgumentError, _("Template %{file} does not exist") % { file: file } unless Puppet::FileSystem.exist?(file)
@file = file
@resource = resource
end
private
def set_resource_variables
@resource.to_hash.each do |param, value|
var = "@#{param}"
instance_variable_set(var, value)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/json.rb | lib/puppet/util/json.rb | # frozen_string_literal: true
module Puppet::Util
module Json
class ParseError < StandardError
attr_reader :cause, :data
def self.build(original_exception, data)
new(original_exception.message).tap do |exception|
exception.instance_eval do
@cause = original_exception
set_backtrace original_exception.backtrace
@data = data
end
end
end
end
begin
require 'multi_json'
# Force backend detection before attempting to use the library
# or load any other JSON libraries
MultiJson.default_adapter
# Preserve core type monkey-patching done by the built-in JSON gem
require 'json'
rescue LoadError
require 'json'
end
# Load the content from a file as JSON if
# contents are in valid format. This method does not
# raise error but returns `nil` when invalid file is
# given.
def self.load_file_if_valid(filename, options = {})
load_file(filename, options)
rescue Puppet::Util::Json::ParseError, ArgumentError, Errno::ENOENT => detail
Puppet.debug("Could not retrieve JSON content from '#{filename}': #{detail.message}")
nil
end
# Load the content from a file as JSON.
def self.load_file(filename, options = {})
json = Puppet::FileSystem.read(filename, :encoding => 'utf-8')
load(json, options)
end
# These methods do similar processing to the fallback implemented by MultiJson
# when using the built-in JSON backend, to ensure consistent behavior
# whether or not MultiJson can be loaded.
def self.load(string, options = {})
if defined? MultiJson
begin
# This ensures that JrJackson and Oj will parse very large or very small
# numbers as floats rather than BigDecimals, which are serialized as
# strings by the built-in JSON gem and therefore can cause schema errors,
# for example, when we are rendering reports to JSON using `to_pson` in
# PuppetDB.
case MultiJson.adapter.name
when "MultiJson::Adapters::JrJackson"
options[:use_bigdecimal] = false
when "MultiJson::Adapters::Oj"
options[:bigdecimal_load] = :float
end
MultiJson.load(string, options)
rescue MultiJson::ParseError => e
raise Puppet::Util::Json::ParseError.build(e, string)
end
else
begin
string = string.read if string.respond_to?(:read)
options[:symbolize_names] = true if options.delete(:symbolize_keys)
::JSON.parse(string, options)
rescue JSON::ParserError => e
raise Puppet::Util::Json::ParseError.build(e, string)
end
end
end
def self.dump(object, options = {})
if defined? MultiJson
MultiJson.dump(object, options)
elsif options.is_a?(JSON::State)
# we're being called recursively
object.to_json(options)
else
options.merge!(::JSON::PRETTY_STATE_PROTOTYPE.to_h) if options.delete(:pretty)
object.to_json(options)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/suidmanager.rb | lib/puppet/util/suidmanager.rb | # frozen_string_literal: true
require_relative '../../puppet/util/warnings'
require 'forwardable'
require 'etc'
module Puppet::Util::SUIDManager
include Puppet::Util::Warnings
extend Forwardable
# Note groups= is handled specially due to a bug in OS X 10.6, 10.7,
# and probably upcoming releases...
to_delegate_to_process = [:euid=, :euid, :egid=, :egid, :uid=, :uid, :gid=, :gid, :groups]
to_delegate_to_process.each do |method|
def_delegator Process, method
module_function method
end
def osx_maj_ver
return @osx_maj_ver unless @osx_maj_ver.nil?
@osx_maj_ver = Puppet.runtime[:facter].value('os.macosx.version.major') || false
end
module_function :osx_maj_ver
def groups=(grouplist)
Process.groups = grouplist
rescue Errno::EINVAL => e
# We catch Errno::EINVAL as some operating systems (OS X in particular) can
# cause troubles when using Process#groups= to change *this* user / process
# list of supplementary groups membership. This is done via Ruby's function
# "static VALUE proc_setgroups(VALUE obj, VALUE ary)" which is effectively
# a wrapper for "int setgroups(size_t size, const gid_t *list)" (part of SVr4
# and 4.3BSD but not in POSIX.1-2001) that fails and sets errno to EINVAL.
#
# This does not appear to be a problem with Ruby but rather an issue on the
# operating system side. Therefore we catch the exception and look whether
# we run under OS X or not -- if so, then we acknowledge the problem and
# re-throw the exception otherwise.
if !osx_maj_ver || osx_maj_ver.empty?
raise e
end
end
module_function :groups=
def self.root?
if Puppet::Util::Platform.windows?
require_relative '../../puppet/util/windows/user'
Puppet::Util::Windows::User.admin?
else
Process.uid == 0
end
end
# Methods to handle changing uid/gid of the running process. In general,
# these will noop or fail on Windows, and require root to change to anything
# but the current uid/gid (which is a noop).
# Runs block setting euid and egid if provided then restoring original ids.
# If running on Windows or without root, the block will be run with the
# current euid/egid.
def asuser(new_uid = nil, new_gid = nil)
return yield if Puppet::Util::Platform.windows?
return yield unless root?
return yield unless new_uid or new_gid
old_euid = euid
old_egid = egid
begin
change_privileges(new_uid, new_gid, false)
yield
ensure
change_privileges(new_uid ? old_euid : nil, old_egid, false)
end
end
module_function :asuser
# If `permanently` is set, will permanently change the uid/gid of the
# process. If not, it will only set the euid/egid. If only uid is supplied,
# the primary group of the supplied gid will be used. If only gid is
# supplied, only gid will be changed. This method will fail if used on
# Windows.
def change_privileges(uid = nil, gid = nil, permanently = false)
return unless uid or gid
unless gid
uid = convert_xid(:uid, uid)
gid = Etc.getpwuid(uid).gid
end
change_group(gid, permanently)
change_user(uid, permanently) if uid
end
module_function :change_privileges
# Changes the egid of the process if `permanently` is not set, otherwise
# changes gid. This method will fail if used on Windows, or attempting to
# change to a different gid without root.
def change_group(group, permanently = false)
gid = convert_xid(:gid, group)
raise Puppet::Error, _("No such group %{group}") % { group: group } unless gid
return if Process.egid == gid
if permanently
Process::GID.change_privilege(gid)
else
Process.egid = gid
end
end
module_function :change_group
# As change_group, but operates on uids. If changing user permanently,
# supplementary groups will be set the to default groups for the new uid.
def change_user(user, permanently = false)
uid = convert_xid(:uid, user)
raise Puppet::Error, _("No such user %{user}") % { user: user } unless uid
return if Process.euid == uid
if permanently
# If changing uid, we must be root. So initgroups first here.
initgroups(uid)
Process::UID.change_privilege(uid)
elsif Process.euid == 0
# We must be root to initgroups, so initgroups before dropping euid if
# we're root, otherwise elevate euid before initgroups.
# change euid (to root) first.
initgroups(uid)
Process.euid = uid
else
Process.euid = uid
initgroups(uid)
end
end
module_function :change_user
# Make sure the passed argument is a number.
def convert_xid(type, id)
return id if id.is_a? Integer
map = { :gid => :group, :uid => :user }
raise ArgumentError, _("Invalid id type %{type}") % { type: type } unless map.include?(type)
ret = Puppet::Util.send(type, id)
if ret.nil?
raise Puppet::Error, _("Invalid %{klass}: %{id}") % { klass: map[type], id: id }
end
ret
end
module_function :convert_xid
# Initialize primary and supplemental groups to those of the target user. We
# take the UID and manually look up their details in the system database,
# including username and primary group. This method will fail on Windows, or
# if used without root to initgroups of another user.
def initgroups(uid)
pwent = Etc.getpwuid(uid)
Process.initgroups(pwent.name, pwent.gid)
end
module_function :initgroups
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/psych_support.rb | lib/puppet/util/psych_support.rb | # frozen_string_literal: true
# This module should be included when a class can be serialized to yaml and
# needs to handle the deserialization from Psych with more control. Psych normally
# pokes values directly into an instance using `instance_variable_set` which completely
# bypasses encapsulation.
#
# The class that includes this module must implement an instance method `initialize_from_hash`
# that is given a hash with attribute to value mappings.
#
module Puppet::Util::PsychSupport
# This method is called from the Psych Yaml deserializer when it encounters a tag
# in the form !ruby/object:<class name>.
#
def init_with(psych_coder)
# The PsychCoder has a hashmap of instance variable name (sans the @ symbol) to values
# to set, and can thus directly be fed to initialize_from_hash.
#
initialize_from_hash(psych_coder.map)
end
# This method is called from the Psych Yaml serializer
# The serializer will call this method to create a hash that will be serialized to YAML.
# Instead of using the object itself during the mapping process we use what is
# returned by calling `to_data_hash` on the object itself since some of the
# objects we manage have asymmetrical serialization and deserialization.
#
def encode_with(psych_encoder)
tag = Psych.dump_tags[self.class] || "!ruby/object:#{self.class.name}"
psych_encoder.represent_map(tag, to_data_hash)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/metaid.rb | lib/puppet/util/metaid.rb | # frozen_string_literal: true
class Object
# The hidden singleton lurks behind everyone
def singleton_class; class << self; self; end; end
def meta_eval(&blk); singleton_class.instance_eval(&blk); end
# Adds methods to a singleton_class
def meta_def(name, &blk)
meta_eval { define_method name, &blk }
end
# Remove singleton_class methods.
def meta_undef(name, &blk)
meta_eval { remove_method name }
end
# Defines an instance method within a class
def class_def(name, &blk)
class_eval { define_method name, &blk }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/tag_set.rb | lib/puppet/util/tag_set.rb | # frozen_string_literal: true
require 'set'
require_relative '../../puppet/network/format_support'
class Puppet::Util::TagSet < Set
include Puppet::Network::FormatSupport
def self.from_yaml(yaml)
new(Puppet::Util::Yaml.safe_load(yaml, [Symbol]))
end
def to_yaml
@hash.keys.to_yaml
end
def self.from_data_hash(data)
new(data)
end
# TODO: A method named #to_data_hash should not return an array
def to_data_hash
to_a
end
def join(*args)
to_a.join(*args)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/symbolic_file_mode.rb | lib/puppet/util/symbolic_file_mode.rb | # frozen_string_literal: true
require_relative '../../puppet/util'
module Puppet
module Util
module SymbolicFileMode
SetUIDBit = ReadBit = 4
SetGIDBit = WriteBit = 2
StickyBit = ExecBit = 1
SymbolicMode = { 'x' => ExecBit, 'w' => WriteBit, 'r' => ReadBit }
SymbolicSpecialToBit = {
't' => { 'u' => StickyBit, 'g' => StickyBit, 'o' => StickyBit },
's' => { 'u' => SetUIDBit, 'g' => SetGIDBit, 'o' => StickyBit }
}
def valid_symbolic_mode?(value)
value = normalize_symbolic_mode(value)
return true if value =~ /^0?[0-7]{1,4}$/
return true if value =~ /^([ugoa]*[-=+][-=+rstwxXugo]*)(,[ugoa]*[-=+][-=+rstwxXugo]*)*$/
false
end
def display_mode(value)
if value =~ /^0?[0-7]{1,4}$/
value.rjust(4, "0")
else
value
end
end
def normalize_symbolic_mode(value)
return nil if value.nil?
# We need to treat integers as octal numbers.
#
# "A numeric mode is from one to four octal digits (0-7), derived by adding
# up the bits with values 4, 2, and 1. Omitted digits are assumed to be
# leading zeros."
case value
when Numeric
value.to_s(8)
when /^0?[0-7]{1,4}$/
value.to_i(8).to_s(8) # strip leading 0's
else
value
end
end
def symbolic_mode_to_int(modification, to_mode = 0, is_a_directory = false)
if modification.nil? or modification == ''
raise Puppet::Error, _("An empty mode string is illegal")
elsif modification =~ /^[0-7]+$/
return modification.to_i(8)
elsif modification =~ /^\d+$/
raise Puppet::Error, _("Numeric modes must be in octal, not decimal!")
end
fail _("non-numeric current mode (%{mode})") % { mode: to_mode.inspect } unless to_mode.is_a?(Numeric)
original_mode = {
's' => (to_mode & 0o7000) >> 9,
'u' => (to_mode & 0o0700) >> 6,
'g' => (to_mode & 0o0070) >> 3,
'o' => (to_mode & 0o0007) >> 0,
# Are there any execute bits set in the original mode?
'any x?' => (to_mode & 0o0111) != 0
}
final_mode = {
's' => original_mode['s'],
'u' => original_mode['u'],
'g' => original_mode['g'],
'o' => original_mode['o'],
}
modification.split(/\s*,\s*/).each do |part|
_, to, dsl = /^([ugoa]*)([-+=].*)$/.match(part).to_a
if dsl.nil? then raise Puppet::Error, _('Missing action') end
to = "a" unless to and to.length > 0
# We want a snapshot of the mode before we start messing with it to
# make actions like 'a-g' atomic. Various parts of the DSL refer to
# the original mode, the final mode, or the current snapshot of the
# mode, for added fun.
snapshot_mode = {}
final_mode.each { |k, v| snapshot_mode[k] = v }
to.gsub('a', 'ugo').split('').uniq.each do |who|
value = snapshot_mode[who]
action = '!'
actions = {
'!' => ->(_, _) { raise Puppet::Error, _('Missing operation (-, =, or +)') },
'=' => ->(m, v) { m | v },
'+' => ->(m, v) { m | v },
'-' => ->(m, v) { m & ~v },
}
dsl.split('').each do |op|
case op
when /[-+=]/
action = op
# Clear all bits, if this is assignment
value = 0 if op == '='
when /[ugo]/
value = actions[action].call(value, snapshot_mode[op])
when /[rwx]/
value = actions[action].call(value, SymbolicMode[op])
when 'X'
# Only meaningful in combination with "set" actions.
if action != '+'
raise Puppet::Error, _("X only works with the '+' operator")
end
# As per the BSD manual page, set if this is a directory, or if
# any execute bit is set on the original (unmodified) mode.
# Ignored otherwise; it is "add if", not "add or clear".
if is_a_directory or original_mode['any x?']
value = actions[action].call(value, ExecBit)
end
when /[st]/
bit = SymbolicSpecialToBit[op][who] or fail _("internal error")
final_mode['s'] = actions[action].call(final_mode['s'], bit)
else
raise Puppet::Error, _('Unknown operation')
end
end
# Now, assign back the value.
final_mode[who] = value
end
rescue Puppet::Error => e
if part.inspect != modification.inspect
rest = " at #{part.inspect}"
else
rest = ''
end
raise Puppet::Error, _("%{error}%{rest} in symbolic mode %{modification}") % { error: e, rest: rest, modification: modification.inspect }, e.backtrace
end
final_mode['s'] << 9 |
final_mode['u'] << 6 |
final_mode['g'] << 3 |
final_mode['o'] << 0
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/classgen.rb | lib/puppet/util/classgen.rb | # frozen_string_literal: true
module Puppet
class ConstantAlreadyDefined < Error; end
class SubclassAlreadyDefined < Error; end
end
# This is a utility module for generating classes.
# @api public
#
module Puppet::Util::ClassGen
include Puppet::Util
# Create a new class.
# @param name [String] the name of the generated class
# @param options [Hash] a hash of options
# @option options [Array<Class>] :array if specified, the generated class is appended to this array
# @option options [Hash<{String => Object}>] :attributes a hash that is applied to the generated class
# by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given
# block is evaluated.
# @option options [Proc] :block a block to evaluate in the context of the class (this block can be provided
# this way, or as a normal yield block).
# @option options [String] :constant (name with first letter capitalized) what to set the constant that references
# the generated class to.
# @option options [Hash] :hash a hash of existing classes that this class is appended to (name => class).
# This hash must be specified if the `:overwrite` option is set to `true`.
# @option options [Boolean] :overwrite whether an overwrite of an existing class should be allowed (requires also
# defining the `:hash` with existing classes as the test is based on the content of this hash).
# @option options [Class] :parent (self) the parent class of the generated class.
# @option options [String] ('') :prefix the constant prefix to prepend to the constant name referencing the
# generated class.
# @return [Class] the generated class
#
def genclass(name, options = {}, &block)
genthing(name, Class, options, block)
end
# Creates a new module.
# @param name [String] the name of the generated module
# @param options [Hash] hash with options
# @option options [Array<Class>] :array if specified, the generated class is appended to this array
# @option options [Hash<{String => Object}>] :attributes a hash that is applied to the generated class
# by calling setter methods corresponding to this hash's keys/value pairs. This is done before the given
# block is evaluated.
# @option options [Proc] :block a block to evaluate in the context of the class (this block can be provided
# this way, or as a normal yield block).
# @option options [String] :constant (name with first letter capitalized) what to set the constant that references
# the generated class to.
# @option options [Hash] :hash a hash of existing classes that this class is appended to (name => class).
# This hash must be specified if the `:overwrite` option is set to `true`.
# @option options [Boolean] :overwrite whether an overwrite of an existing class should be allowed (requires also
# defining the `:hash` with existing classes as the test is based on the content of this hash).
# the capitalized name is appended and the result is set as the constant.
# @option options [String] ('') :prefix the constant prefix to prepend to the constant name referencing the
# generated class.
# @return [Module] the generated Module
def genmodule(name, options = {}, &block)
genthing(name, Module, options, block)
end
# Removes an existing class.
# @param name [String] the name of the class to remove
# @param options [Hash] options
# @option options [Hash] :hash a hash of existing classes from which the class to be removed is also removed
# @return [Boolean] whether the class was removed or not
#
def rmclass(name, options)
const = genconst_string(name, options)
retval = false
if const_defined?(const, false)
remove_const(const)
retval = true
end
hash = options[:hash]
if hash && hash.include?(name)
hash.delete(name)
retval = true
end
# Let them know whether we did actually delete a subclass.
retval
end
private
# Generates the constant to create or remove.
# @api private
def genconst_string(name, options)
const = options[:constant]
unless const
prefix = options[:prefix] || ""
const = prefix + name2const(name)
end
const
end
# This does the actual work of creating our class or module. It's just a
# slightly abstract version of genclass.
# @api private
def genthing(name, type, options, block)
name = name.to_s.downcase.intern
if type == Module
# evalmethod = :module_eval
evalmethod = :class_eval
# Create the class, with the correct name.
klass = Module.new do
class << self
attr_reader :name
end
@name = name
end
else
options[:parent] ||= self
evalmethod = :class_eval
# Create the class, with the correct name.
klass = Class.new(options[:parent]) do
@name = name
end
end
# Create the constant as appropriation.
handleclassconst(klass, name, options)
# Initialize any necessary variables.
initclass(klass, options)
block ||= options[:block]
# Evaluate the passed block if there is one. This should usually
# define all of the work.
klass.send(evalmethod, &block) if block
klass.postinit if klass.respond_to? :postinit
# Store the class in hashes or arrays or whatever.
storeclass(klass, name, options)
klass
end
# Handle the setting and/or removing of the associated constant.
# @api private
#
def handleclassconst(klass, name, options)
const = genconst_string(name, options)
if const_defined?(const, false)
if options[:overwrite]
Puppet.info _("Redefining %{name} in %{klass}") % { name: name, klass: self }
remove_const(const)
else
raise Puppet::ConstantAlreadyDefined,
_("Class %{const} is already defined in %{klass}") % { const: const, klass: self }
end
end
const_set(const, klass)
const
end
# Perform the initializations on the class.
# @api private
#
def initclass(klass, options)
klass.initvars if klass.respond_to? :initvars
attrs = options[:attributes]
if attrs
attrs.each do |param, value|
method = param.to_s + "="
klass.send(method, value) if klass.respond_to? method
end
end
[:include, :extend].each do |method|
set = options[method]
next unless set
set = [set] unless set.is_a?(Array)
set.each do |mod|
klass.send(method, mod)
end
end
klass.preinit if klass.respond_to? :preinit
end
# Convert our name to a constant.
# @api private
def name2const(name)
name.to_s.capitalize
end
# Store the class in the appropriate places.
# @api private
def storeclass(klass, klassname, options)
hash = options[:hash]
if hash
if hash.include? klassname and !options[:overwrite]
raise Puppet::SubclassAlreadyDefined,
_("Already a generated class named %{klassname}") % { klassname: klassname }
end
hash[klassname] = klass
end
# If we were told to stick it in a hash, then do so
array = options[:array]
if array
if klass.respond_to? :name and
array.find { |c| c.name == klassname } and
!options[:overwrite]
raise Puppet::SubclassAlreadyDefined,
_("Already a generated class named %{klassname}") % { klassname: klassname }
end
array << klass
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/fileparsing.rb | lib/puppet/util/fileparsing.rb | # frozen_string_literal: true
# A mini-language for parsing files. This is only used file the ParsedFile
# provider, but it makes more sense to split it out so it's easy to maintain
# in one place.
#
# You can use this module to create simple parser/generator classes. For instance,
# the following parser should go most of the way to parsing /etc/passwd:
#
# class Parser
# include Puppet::Util::FileParsing
# record_line :user, :fields => %w{name password uid gid gecos home shell},
# :separator => ":"
# end
#
# You would use it like this:
#
# parser = Parser.new
# lines = parser.parse(File.read("/etc/passwd"))
#
# lines.each do |type, hash| # type will always be :user, since we only have one
# p hash
# end
#
# Each line in this case would be a hash, with each field set appropriately.
# You could then call 'parser.to_line(hash)' on any of those hashes to generate
# the text line again.
module Puppet::Util::FileParsing
include Puppet::Util
attr_writer :line_separator, :trailing_separator
class FileRecord
include Puppet::Util
attr_accessor :absent, :joiner, :rts, :separator, :rollup, :name, :match, :block_eval
attr_reader :fields, :optional, :type
INVALID_FIELDS = [:record_type, :target, :on_disk]
# Customize this so we can do a bit of validation.
def fields=(fields)
@fields = fields.collect do |field|
r = field.intern
raise ArgumentError, _("Cannot have fields named %{name}") % { name: r } if INVALID_FIELDS.include?(r)
r
end
end
def initialize(type,
absent: nil,
block_eval: nil,
fields: nil,
joiner: nil,
match: nil,
optional: nil,
post_parse: nil,
pre_gen: nil,
rollup: nil,
rts: nil,
separator: nil,
to_line: nil,
&block)
@type = type.intern
raise ArgumentError, _("Invalid record type %{record_type}") % { record_type: @type } unless [:record, :text].include?(@type)
@absent = absent
@block_eval = block_eval
@joiner = joiner
@match = match
@rollup = rollup if rollup
@rts = rts
@separator = separator
self.fields = fields if fields
self.optional = optional if optional
self.post_parse = post_parse if post_parse
self.pre_gen = pre_gen if pre_gen
self.to_line = to_line if to_line
if self.type == :record
# Now set defaults.
self.absent ||= ""
self.separator ||= /\s+/
self.joiner ||= " "
self.optional ||= []
@rollup = true unless defined?(@rollup)
end
if block_given?
@block_eval ||= :process
# Allow the developer to specify that a block should be instance-eval'ed.
if @block_eval == :instance
instance_eval(&block)
else
meta_def(@block_eval, &block)
end
end
end
# Convert a record into a line by joining the fields together appropriately.
# This is pulled into a separate method so it can be called by the hooks.
def join(details)
joinchar = self.joiner
fields.filter_map { |field|
# If the field is marked absent, use the appropriate replacement
if details[field] == :absent or details[field] == [:absent] or details[field].nil?
if self.optional.include?(field)
self.absent
else
raise ArgumentError, _("Field '%{field}' is required") % { field: field }
end
else
details[field].to_s
end
}.join(joinchar)
end
# Customize this so we can do a bit of validation.
def optional=(optional)
@optional = optional.collect(&:intern)
end
# Create a hook that modifies the hash resulting from parsing.
def post_parse=(block)
meta_def(:post_parse, &block)
end
# Create a hook that modifies the hash just prior to generation.
def pre_gen=(block)
meta_def(:pre_gen, &block)
end
# Are we a text type?
def text?
type == :text
end
def to_line=(block)
meta_def(:to_line, &block)
end
end
# Clear all existing record definitions. Only used for testing.
def clear_records
@record_types.clear
@record_order.clear
end
def fields(type)
record = record_type(type)
if record
record.fields.dup
else
nil
end
end
# Try to match a specific text line.
def handle_text_line(line, record)
line =~ record.match ? { :record_type => record.name, :line => line } : nil
end
# Try to match a record.
#
# @param [String] line The line to be parsed
# @param [Puppet::Util::FileType] record The filetype to use for parsing
#
# @return [Hash<Symbol, Object>] The parsed elements of the line
def handle_record_line(line, record)
ret = nil
if record.respond_to?(:process)
ret = record.send(:process, line.dup)
if ret
unless ret.is_a?(Hash)
raise Puppet::DevError, _("Process record type %{record_name} returned non-hash") % { record_name: record.name }
end
else
return nil
end
else
regex = record.match
if regex
# In this case, we try to match the whole line and then use the
# match captures to get our fields.
match = regex.match(line)
if match
ret = {}
record.fields.zip(match.captures).each do |field, value|
if value == record.absent
ret[field] = :absent
else
ret[field] = value
end
end
else
nil
end
else
ret = {}
sep = record.separator
# String "helpfully" replaces ' ' with /\s+/ in splitting, so we
# have to work around it.
if sep == " "
sep = / /
end
line_fields = line.split(sep)
record.fields.each do |param|
value = line_fields.shift
if value and value != record.absent
ret[param] = value
else
ret[param] = :absent
end
end
if record.rollup and !line_fields.empty?
last_field = record.fields[-1]
val = ([ret[last_field]] + line_fields).join(record.joiner)
ret[last_field] = val
end
end
end
if ret
ret[:record_type] = record.name
ret
else
nil
end
end
def line_separator
@line_separator ||= "\n"
@line_separator
end
# Split text into separate lines using the record separator.
def lines(text)
# NOTE: We do not have to remove trailing separators because split will ignore
# them by default (unless you pass -1 as a second parameter)
text.split(line_separator)
end
# Split a bunch of text into lines and then parse them individually.
def parse(text)
count = 1
lines(text).collect do |line|
count += 1
val = parse_line(line)
if val
val
else
error = Puppet::ResourceError.new(_("Could not parse line %{line}") % { line: line.inspect })
error.line = count
raise error
end
end
end
# Handle parsing a single line.
def parse_line(line)
raise Puppet::DevError, _("No record types defined; cannot parse lines") unless records?
@record_order.each do |record|
# These are basically either text or record lines.
method = "handle_#{record.type}_line"
if respond_to?(method)
result = send(method, line, record)
if result
record.send(:post_parse, result) if record.respond_to?(:post_parse)
return result
end
else
raise Puppet::DevError, _("Somehow got invalid line type %{record_type}") % { record_type: record.type }
end
end
nil
end
# Define a new type of record. These lines get split into hashes. Valid
# options are:
# * <tt>:absent</tt>: What to use as value within a line, when a field is
# absent. Note that in the record object, the literal :absent symbol is
# used, and not this value. Defaults to "".
# * <tt>:fields</tt>: The list of fields, as an array. By default, all
# fields are considered required.
# * <tt>:joiner</tt>: How to join fields together. Defaults to '\t'.
# * <tt>:optional</tt>: Which fields are optional. If these are missing,
# you'll just get the 'absent' value instead of an ArgumentError.
# * <tt>:rts</tt>: Whether to remove trailing whitespace. Defaults to false.
# If true, whitespace will be removed; if a regex, then whatever matches
# the regex will be removed.
# * <tt>:separator</tt>: The record separator. Defaults to /\s+/.
def record_line(name, options, &block)
raise ArgumentError, _("Must include a list of fields") unless options.include?(:fields)
record = FileRecord.new(:record, **options, &block)
record.name = name.intern
new_line_type(record)
end
# Are there any record types defined?
def records?
defined?(@record_types) and !@record_types.empty?
end
# Define a new type of text record.
def text_line(name, options, &block)
raise ArgumentError, _("You must provide a :match regex for text lines") unless options.include?(:match)
record = FileRecord.new(:text, **options, &block)
record.name = name.intern
new_line_type(record)
end
# Generate a file from a bunch of hash records.
def to_file(records)
text = records.collect { |record| to_line(record) }.join(line_separator)
text += line_separator if trailing_separator
text
end
# Convert our parsed record into a text record.
def to_line(details)
record = record_type(details[:record_type])
unless record
raise ArgumentError, _("Invalid record type %{record_type}") % { record_type: details[:record_type].inspect }
end
if record.respond_to?(:pre_gen)
details = details.dup
record.send(:pre_gen, details)
end
case record.type
when :text; details[:line]
else
return record.to_line(details) if record.respond_to?(:to_line)
line = record.join(details)
regex = record.rts
if regex
# If they say true, then use whitespace; else, use their regex.
if regex == true
regex = /\s+$/
end
line.sub(regex, '')
else
line
end
end
end
# Whether to add a trailing separator to the file. Defaults to true
def trailing_separator
if defined?(@trailing_separator)
@trailing_separator
else
true
end
end
def valid_attr?(type, attr)
type = type.intern
record = record_type(type)
if record && record.fields.include?(attr.intern)
true
else
attr.intern == :ensure
end
end
private
# Define a new type of record.
def new_line_type(record)
@record_types ||= {}
@record_order ||= []
raise ArgumentError, _("Line type %{name} is already defined") % { name: record.name } if @record_types.include?(record.name)
@record_types[record.name] = record
@record_order << record
record
end
# Retrieve the record object.
def record_type(type)
@record_types[type.intern]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rubygems.rb | lib/puppet/util/rubygems.rb | # frozen_string_literal: true
require_relative '../../puppet/util'
module Puppet::Util::RubyGems
# Base/factory class for rubygems source. These classes introspec into
# rubygems to in order to list where the rubygems system will look for files
# to load.
class Source
class << self
# @api private
def has_rubygems?
# Gems are not actually available when Bundler is loaded, even
# though the Gem constant is defined. This is because Bundler
# loads in rubygems, but then removes the custom require that
# rubygems installs. So when Bundler is around we have to act
# as though rubygems is not, e.g. we shouldn't be able to load
# a gem that Bundler doesn't want us to see.
defined? ::Gem and !defined? ::Bundler
end
# @api private
def source
if has_rubygems?
Gems18Source
else
NoGemsSource
end
end
def new(*args)
object = source.allocate
object.send(:initialize, *args)
object
end
end
end
# For RubyGems >= 1.8.0
# @api private
class Gems18Source < Source
def directories
# `require 'mygem'` will consider and potentially load
# prerelease gems, so we need to match that behavior.
#
# Just load the stub which points to the gem path, and
# delay loading the full specification until if/when the
# gem is required.
Gem::Specification.stubs.collect do |spec|
File.join(spec.full_gem_path, 'lib')
end
end
def clear_paths
Gem.clear_paths
end
end
# @api private
class NoGemsSource < Source
def directories
[]
end
def clear_paths; end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/file_watcher.rb | lib/puppet/util/file_watcher.rb | # frozen_string_literal: true
class Puppet::Util::FileWatcher
include Enumerable
def each(&blk)
@files.keys.each(&blk)
end
def initialize
@files = {}
end
def changed?
@files.values.any?(&:changed?)
end
def watch(filename)
return if watching?(filename)
@files[filename] = Puppet::Util::WatchedFile.new(filename)
end
def watching?(filename)
@files.has_key?(filename)
end
def clear
@files.clear
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/user_attr.rb | lib/puppet/util/user_attr.rb | # frozen_string_literal: true
class UserAttr
def self.get_attributes_by_name(name)
attributes = nil
File.readlines('/etc/user_attr').each do |line|
next if line =~ /^#/
token = line.split(':')
next unless token[0] == name
attributes = { :name => name }
token[4].split(';').each do |attr|
key_value = attr.split('=')
attributes[key_value[0].intern] = key_value[1].strip
end
break
end
attributes
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/terminal.rb | lib/puppet/util/terminal.rb | # frozen_string_literal: true
module Puppet::Util::Terminal
# Attempts to determine the width of the terminal. This is currently only
# supported on POSIX systems, and relies on the claims of `stty` (or `tput`).
#
# Inspired by code from Thor; thanks wycats!
# @return [Number] The column width of the terminal. Defaults to 80 columns.
def self.width
if Puppet.features.posix?
result = %x(stty size 2>/dev/null).split[1] ||
%x(tput cols 2>/dev/null).split[0]
end
(result || '80').to_i
rescue
80
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/pidlock.rb | lib/puppet/util/pidlock.rb | # frozen_string_literal: true
require 'fileutils'
require_relative '../../puppet/util/lockfile'
class Puppet::Util::Pidlock
def initialize(lockfile)
@lockfile = Puppet::Util::Lockfile.new(lockfile)
end
def locked?
clear_if_stale
@lockfile.locked?
end
def mine?
Process.pid == lock_pid
end
def lock
return mine? if locked?
@lockfile.lock(Process.pid)
end
def unlock
if mine?
@lockfile.unlock
else
false
end
end
def lock_pid
pid = @lockfile.lock_data
begin
Integer(pid)
rescue ArgumentError, TypeError
nil
end
end
def file_path
@lockfile.file_path
end
private
def ps_argument_for_current_kernel
case Puppet.runtime[:facter].value(:kernel)
when "Linux"
"-eq"
when "AIX"
"-T"
else
"-p"
end
end
def clear_if_stale
pid = lock_pid
return @lockfile.unlock if pid.nil?
return if Process.pid == pid
errors = [Errno::ESRCH]
# Win32::Process now throws SystemCallError. Since this could be
# defined anywhere, only add when on Windows.
errors << SystemCallError if Puppet::Util::Platform.windows?
begin
Process.kill(0, pid)
rescue *errors
return @lockfile.unlock
end
# Ensure the process associated with this pid is our process. If
# not, we can unlock the lockfile. CLI arguments used for identifying
# on POSIX depend on the os and sometimes even version.
if Puppet.features.posix?
ps_argument = ps_argument_for_current_kernel
# Check, obtain and use the right ps argument
begin
procname = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "comm="]).strip
rescue Puppet::ExecutionFailure
ps_argument = "-p"
procname = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "comm="]).strip
end
args = Puppet::Util::Execution.execute(["ps", ps_argument, pid, "-o", "args="]).strip
@lockfile.unlock unless procname =~ /ruby/ && args =~ /puppet/ || procname =~ /puppet(-.*)?$/
elsif Puppet.features.microsoft_windows?
# On Windows, we're checking if the filesystem path name of the running
# process is our vendored ruby:
begin
exe_path = Puppet::Util::Windows::Process.get_process_image_name_by_pid(pid)
@lockfile.unlock unless exe_path =~ /\\bin\\ruby.exe$/
rescue Puppet::Util::Windows::Error => e
Puppet.debug("Failed to read pidfile #{file_path}: #{e.message}")
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/splayer.rb | lib/puppet/util/splayer.rb | # frozen_string_literal: true
# Handle splay options (sleeping for a random interval before executing)
module Puppet::Util::Splayer
# Have we splayed already?
def splayed?
!!@splayed
end
# Sleep when splay is enabled; else just return.
def splay(do_splay = Puppet[:splay])
return unless do_splay
return if splayed?
time = rand(Puppet[:splaylimit] + 1)
Puppet.info _("Sleeping for %{time} seconds (splay is enabled)") % { time: time }
sleep(time)
@splayed = true
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/command_line.rb | lib/puppet/util/command_line.rb | # frozen_string_literal: true
# Bundler and rubygems maintain a set of directories from which to
# load gems. If Bundler is loaded, let it determine what can be
# loaded. If it's not loaded, then use rubygems. But do this before
# loading any puppet code, so that our gem loading system is sane.
unless defined? ::Bundler
begin
require 'rubygems'
rescue LoadError
end
end
require_relative '../../puppet'
require_relative '../../puppet/util'
require_relative '../../puppet/util/rubygems'
require_relative '../../puppet/util/limits'
require_relative '../../puppet/util/colors'
require_relative '../../puppet/gettext/module_translations'
module Puppet
module Util
# This is the main entry point for all puppet applications / faces; it
# is basically where the bootstrapping process / lifecycle of an app
# begins.
class CommandLine
include Puppet::Util::Limits
OPTION_OR_MANIFEST_FILE = /^-|\.pp$/
# @param zero [String] the name of the executable
# @param argv [Array<String>] the arguments passed on the command line
# @param stdin [IO] (unused)
def initialize(zero = $PROGRAM_NAME, argv = ARGV, stdin = STDIN)
@command = File.basename(zero, '.rb')
@argv = argv
end
# @return [String] name of the subcommand is being executed
# @api public
def subcommand_name
return @command if @command != 'puppet'
if @argv.first =~ OPTION_OR_MANIFEST_FILE
nil
else
@argv.first
end
end
# @return [Array<String>] the command line arguments being passed to the subcommand
# @api public
def args
return @argv if @command != 'puppet'
if subcommand_name.nil?
@argv
else
@argv[1..]
end
end
# Run the puppet subcommand. If the subcommand is determined to be an
# external executable, this method will never return and the current
# process will be replaced via {Kernel#exec}.
#
# @return [void]
def execute
require_config = true
if @argv.first =~ /help|-h|--help|-V|--version/
require_config = false
end
Puppet::Util.exit_on_fail(_("Could not initialize global default settings")) do
Puppet.initialize_settings(args, require_config)
end
setpriority(Puppet[:priority])
find_subcommand.run
end
# @api private
def external_subcommand
Puppet::Util.which("puppet-#{subcommand_name}")
end
private
def find_subcommand
if subcommand_name.nil?
if args.include?("--help") || args.include?("-h")
ApplicationSubcommand.new("help", CommandLine.new("puppet", ["help"]))
else
NilSubcommand.new(self)
end
elsif Puppet::Application.available_application_names.include?(subcommand_name)
ApplicationSubcommand.new(subcommand_name, self)
else
path_to_subcommand = external_subcommand
if path_to_subcommand
ExternalSubcommand.new(path_to_subcommand, self)
else
UnknownSubcommand.new(subcommand_name, self)
end
end
end
# @api private
class ApplicationSubcommand
def initialize(subcommand_name, command_line)
@subcommand_name = subcommand_name
@command_line = command_line
end
def run
# For most applications, we want to be able to load code from the modulepath,
# such as apply, describe, resource, and faces.
# For agent and device in agent mode, we only want to load pluginsync'ed code from libdir.
# For master, we shouldn't ever be loading per-environment code into the master's
# ruby process, but that requires fixing (#17210, #12173, #8750). So for now
# we try to restrict to only code that can be autoloaded from the node's
# environment.
# PUP-2114 - at this point in the bootstrapping process we do not
# have an appropriate application-wide current_environment set.
# If we cannot find the configured environment, which may not exist,
# we do not attempt to add plugin directories to the load path.
unless @subcommand_name == 'master' || @subcommand_name == 'agent' || (@subcommand_name == 'device' && (['--apply', '--facts', '--resource'] - @command_line.args).empty?)
configured_environment = Puppet.lookup(:environments).get(Puppet[:environment])
if configured_environment
configured_environment.each_plugin_directory do |dir|
$LOAD_PATH << dir unless $LOAD_PATH.include?(dir)
end
Puppet::ModuleTranslations.load_from_modulepath(configured_environment.modules)
Puppet::ModuleTranslations.load_from_vardir(Puppet[:vardir])
# Puppet requires Facter, which initializes its lookup paths. Reset Facter to
# pickup the new $LOAD_PATH.
Puppet.runtime[:facter].reset
end
end
app = Puppet::Application.find(@subcommand_name).new(@command_line)
app.run
end
end
# @api private
class ExternalSubcommand
def initialize(path_to_subcommand, command_line)
@path_to_subcommand = path_to_subcommand
@command_line = command_line
end
def run
Kernel.exec(@path_to_subcommand, *@command_line.args)
end
end
# @api private
class NilSubcommand
include Puppet::Util::Colors
def initialize(command_line)
@command_line = command_line
end
def run
args = @command_line.args
if args.include? "--version" or args.include? "-V"
puts Puppet.version
elsif @command_line.subcommand_name.nil? && args.count > 0
# If the subcommand is truly nil and there is an arg, it's an option; print out the invalid option message
puts colorize(:hred, _("Error: Could not parse application options: invalid option: %{opt}") % { opt: args[0] })
exit 1
else
puts _("See 'puppet help' for help on available puppet subcommands")
end
end
end
# @api private
class UnknownSubcommand < NilSubcommand
def initialize(subcommand_name, command_line)
@subcommand_name = subcommand_name
super(command_line)
end
def run
puts colorize(:hred, _("Error: Unknown Puppet subcommand '%{cmd}'") % { cmd: @subcommand_name })
super
exit 1
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/ldap.rb | lib/puppet/util/ldap.rb | # frozen_string_literal: true
module Puppet::Util::Ldap
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/execution.rb | lib/puppet/util/execution.rb | # frozen_string_literal: true
require 'timeout'
require_relative '../../puppet/file_system/uniquefile'
module Puppet
require 'rbconfig'
require_relative '../../puppet/error'
# A command failed to execute.
# @api public
class ExecutionFailure < Puppet::Error
end
end
# This module defines methods for execution of system commands. It is intended for inclusion
# in classes that needs to execute system commands.
# @api public
module Puppet::Util::Execution
# This is the full output from a process. The object itself (a String) is the
# stdout of the process.
#
# @api public
class ProcessOutput < String
# @return [Integer] The exit status of the process
# @api public
attr_reader :exitstatus
# @api private
def initialize(value, exitstatus)
super(value)
@exitstatus = exitstatus
end
end
# The command can be a simple string, which is executed as-is, or an Array,
# which is treated as a set of command arguments to pass through.
#
# In either case, the command is passed directly to the shell, STDOUT and
# STDERR are connected together, and STDOUT will be streamed to the yielded
# pipe.
#
# @param command [String, Array<String>] the command to execute as one string,
# or as parts in an array. The parts of the array are joined with one
# separating space between each entry when converting to the command line
# string to execute.
# @param failonfail [Boolean] (true) if the execution should fail with
# Exception on failure or not.
# @yield [pipe] to a block executing a subprocess
# @yieldparam pipe [IO] the opened pipe
# @yieldreturn [String] the output to return
# @raise [Puppet::ExecutionFailure] if the executed child process did not
# exit with status == 0 and `failonfail` is `true`.
# @return [String] a string with the output from the subprocess executed by
# the given block
#
# @see Kernel#open for `mode` values
# @api public
def self.execpipe(command, failonfail = true)
# Paste together an array with spaces. We used to paste directly
# together, no spaces, which made for odd invocations; the user had to
# include whitespace between arguments.
#
# Having two spaces is really not a big drama, since this passes to the
# shell anyhow, while no spaces makes for a small developer cost every
# time this is invoked. --daniel 2012-02-13
command_str = command.respond_to?(:join) ? command.join(' ') : command
if respond_to? :debug
debug "Executing '#{command_str}'"
else
Puppet.debug { "Executing '#{command_str}'" }
end
# force the run of the command with
# the user/system locale to "C" (via environment variables LANG and LC_*)
# it enables to have non localized output for some commands and therefore
# a predictable output
english_env = ENV.to_hash.merge({ 'LANG' => 'C', 'LC_ALL' => 'C' })
output = Puppet::Util.withenv(english_env) do
# We are intentionally using 'pipe' with open to launch a process
open("| #{command_str} 2>&1") do |pipe| # rubocop:disable Security/Open
yield pipe
end
end
if failonfail && exitstatus != 0
raise Puppet::ExecutionFailure, output.to_s
end
output
end
def self.exitstatus
$CHILD_STATUS.exitstatus
end
private_class_method :exitstatus
# Default empty options for {execute}
NoOptionsSpecified = {}
# Executes the desired command, and return the status and output.
# def execute(command, options)
# @param command [Array<String>, String] the command to execute. If it is
# an Array the first element should be the executable and the rest of the
# elements should be the individual arguments to that executable.
# @param options [Hash] a Hash of options
# @option options [String] :cwd the directory from which to run the command. Raises an error if the directory does not exist.
# This option is only available on the agent. It cannot be used on the master, meaning it cannot be used in, for example,
# regular functions, hiera backends, or report processors.
# @option options [Boolean] :failonfail if this value is set to true, then this method will raise an error if the
# command is not executed successfully.
# @option options [Integer, String] :uid (nil) the user id of the user that the process should be run as. Will be ignored if the
# user id matches the effective user id of the current process.
# @option options [Integer, String] :gid (nil) the group id of the group that the process should be run as. Will be ignored if the
# group id matches the effective group id of the current process.
# @option options [Boolean] :combine sets whether or not to combine stdout/stderr in the output, if false stderr output is discarded
# @option options [String] :stdinfile (nil) sets a file that can be used for stdin. Passing a string for stdin is not currently
# supported.
# @option options [Boolean] :squelch (false) if true, ignore stdout / stderr completely.
# @option options [Boolean] :override_locale (true) by default (and if this option is set to true), we will temporarily override
# the user/system locale to "C" (via environment variables LANG and LC_*) while we are executing the command.
# This ensures that the output of the command will be formatted consistently, making it predictable for parsing.
# Passing in a value of false for this option will allow the command to be executed using the user/system locale.
# @option options [Hash<{String => String}>] :custom_environment ({}) a hash of key/value pairs to set as environment variables for the duration
# of the command.
# @return [Puppet::Util::Execution::ProcessOutput] output as specified by options
# @raise [Puppet::ExecutionFailure] if the executed chiled process did not exit with status == 0 and `failonfail` is
# `true`.
# @note Unfortunately, the default behavior for failonfail and combine (since
# 0.22.4 and 0.24.7, respectively) depend on whether options are specified
# or not. If specified, then failonfail and combine default to false (even
# when the options specified are neither failonfail nor combine). If no
# options are specified, then failonfail and combine default to true.
# @comment See commits efe9a833c and d32d7f30
# @api public
#
def self.execute(command, options = NoOptionsSpecified)
# specifying these here rather than in the method signature to allow callers to pass in a partial
# set of overrides without affecting the default values for options that they don't pass in
default_options = {
:failonfail => NoOptionsSpecified.equal?(options),
:uid => nil,
:gid => nil,
:combine => NoOptionsSpecified.equal?(options),
:stdinfile => nil,
:squelch => false,
:override_locale => true,
:custom_environment => {},
:sensitive => false,
:suppress_window => false,
}
options = default_options.merge(options)
case command
when Array
command = command.flatten.map(&:to_s)
command_str = command.join(" ")
when String
command_str = command
end
# do this after processing 'command' array or string
command_str = '[redacted]' if options[:sensitive]
user_log_s = ''.dup
if options[:uid]
user_log_s << " uid=#{options[:uid]}"
end
if options[:gid]
user_log_s << " gid=#{options[:gid]}"
end
if user_log_s != ''
user_log_s.prepend(' with')
end
if respond_to? :debug
debug "Executing#{user_log_s}: '#{command_str}'"
else
Puppet.debug { "Executing#{user_log_s}: '#{command_str}'" }
end
null_file = Puppet::Util::Platform.windows? ? 'NUL' : '/dev/null'
cwd = options[:cwd]
if cwd && !Puppet::FileSystem.directory?(cwd)
raise ArgumentError, _("Working directory %{cwd} does not exist!") % { cwd: cwd }
end
begin
stdin = Puppet::FileSystem.open(options[:stdinfile] || null_file, nil, 'r')
# On Windows, continue to use the file-based approach to avoid breaking people's existing
# manifests. If they use a script that doesn't background cleanly, such as
# `start /b ping 127.0.0.1`, we couldn't handle it with pipes as there's no non-blocking
# read available.
if options[:squelch]
stdout = Puppet::FileSystem.open(null_file, nil, 'w')
elsif Puppet.features.posix?
reader, stdout = IO.pipe
else
stdout = Puppet::FileSystem::Uniquefile.new('puppet')
end
stderr = options[:combine] ? stdout : Puppet::FileSystem.open(null_file, nil, 'w')
exec_args = [command, options, stdin, stdout, stderr]
output = ''.dup
# We close stdin/stdout/stderr immediately after fork/exec as they're no longer needed by
# this process. In most cases they could be closed later, but when `stdout` is the "writer"
# pipe we must close it or we'll never reach eof on the `reader` pipe.
execution_stub = Puppet::Util::ExecutionStub.current_value
if execution_stub
child_pid = execution_stub.call(*exec_args)
[stdin, stdout, stderr].each { |io|
begin
io.close
rescue
nil
end
}
return child_pid
elsif Puppet.features.posix?
child_pid = nil
begin
child_pid = execute_posix(*exec_args)
[stdin, stdout, stderr].each { |io|
begin
io.close
rescue
nil
end
}
if options[:squelch]
exit_status = Process.waitpid2(child_pid).last.exitstatus
else
# Use non-blocking read to check for data. After each attempt,
# check whether the child is done. This is done in case the child
# forks and inherits stdout, as happens in `foo &`.
# If we encounter EOF, though, then switch to a blocking wait for
# the child; after EOF, IO.select will never block and the loop
# below will use maximum CPU available.
wait_flags = Process::WNOHANG
until results = Process.waitpid2(child_pid, wait_flags) # rubocop:disable Lint/AssignmentInCondition
# If not done, wait for data to read with a timeout
# This timeout is selected to keep activity low while waiting on
# a long process, while not waiting too long for the pathological
# case where stdout is never closed.
ready = IO.select([reader], [], [], 0.1)
begin
output << reader.read_nonblock(4096) if ready
rescue Errno::EAGAIN
rescue EOFError
wait_flags = 0
end
end
# Read any remaining data. Allow for but don't expect EOF.
begin
loop do
output << reader.read_nonblock(4096)
end
rescue Errno::EAGAIN
rescue EOFError
end
# Force to external encoding to preserve prior behavior when reading a file.
# Wait until after reading all data so we don't encounter corruption when
# reading part of a multi-byte unicode character if default_external is UTF-8.
output.force_encoding(Encoding.default_external)
exit_status = results.last.exitstatus
end
child_pid = nil
rescue Timeout::Error => e
# NOTE: For Ruby 2.1+, an explicit Timeout::Error class has to be
# passed to Timeout.timeout in order for there to be something for
# this block to rescue.
unless child_pid.nil?
Process.kill(:TERM, child_pid)
# Spawn a thread to reap the process if it dies.
Thread.new { Process.waitpid(child_pid) }
end
raise e
end
elsif Puppet::Util::Platform.windows?
process_info = execute_windows(*exec_args)
begin
[stdin, stderr].each { |io|
begin
io.close
rescue
nil
end
}
exit_status = Puppet::Util::Windows::Process.wait_process(process_info.process_handle)
# read output in if required
unless options[:squelch]
output = wait_for_output(stdout)
Puppet.warning _("Could not get output") unless output
end
ensure
FFI::WIN32.CloseHandle(process_info.process_handle)
FFI::WIN32.CloseHandle(process_info.thread_handle)
end
end
if options[:failonfail] and exit_status != 0
raise Puppet::ExecutionFailure, _("Execution of '%{str}' returned %{exit_status}: %{output}") % { str: command_str, exit_status: exit_status, output: output.strip }
end
ensure
# Make sure all handles are closed in case an exception was thrown attempting to execute.
[stdin, stdout, stderr].each { |io|
begin
io.close
rescue
nil
end
}
unless options[:squelch]
# if we opened a pipe, we need to clean it up.
reader.close if reader
stdout.close! if stdout && Puppet::Util::Platform.windows?
end
end
Puppet::Util::Execution::ProcessOutput.new(output || '', exit_status)
end
# Returns the path to the ruby executable (available via Config object, even if
# it's not in the PATH... so this is slightly safer than just using Puppet::Util.which)
# @return [String] the path to the Ruby executable
# @api private
#
def self.ruby_path
File.join(RbConfig::CONFIG['bindir'],
RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'])
.sub(/.*\s.*/m, '"\&"')
end
# Because some modules provide their own version of this method.
class << self
alias util_execute execute
end
# This is private method.
# @comment see call to private_class_method after method definition
# @api private
#
def self.execute_posix(command, options, stdin, stdout, stderr)
Puppet::Util.safe_posix_fork(stdin, stdout, stderr) do
# We can't just call Array(command), and rely on it returning
# things like ['foo'], when passed ['foo'], because
# Array(command) will call command.to_a internally, which when
# given a string can end up doing Very Bad Things(TM), such as
# turning "/tmp/foo;\r\n /bin/echo" into ["/tmp/foo;\r\n", " /bin/echo"]
command = [command].flatten
Process.setsid
begin
# We need to chdir to our cwd before changing privileges as there's a
# chance that the user may not have permissions to access the cwd, which
# would cause execute_posix to fail.
cwd = options[:cwd]
Dir.chdir(cwd) if cwd
Puppet::Util::SUIDManager.change_privileges(options[:uid], options[:gid], true)
# if the caller has requested that we override locale environment variables,
if options[:override_locale] then
# loop over them and clear them
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |name| ENV.delete(name) }
# set LANG and LC_ALL to 'C' so that the command will have consistent, predictable output
# it's OK to manipulate these directly rather than, e.g., via "withenv", because we are in
# a forked process.
ENV['LANG'] = 'C'
ENV['LC_ALL'] = 'C'
end
# unset all of the user-related environment variables so that different methods of starting puppet
# (automatic start during boot, via 'service', via /etc/init.d, etc.) won't have unexpected side
# effects relating to user / home dir environment vars.
# it's OK to manipulate these directly rather than, e.g., via "withenv", because we are in
# a forked process.
Puppet::Util::POSIX::USER_ENV_VARS.each { |name| ENV.delete(name) }
options[:custom_environment] ||= {}
Puppet::Util.withenv(options[:custom_environment]) do
Kernel.exec(*command)
end
rescue => detail
Puppet.log_exception(detail, _("Could not execute posix command: %{detail}") % { detail: detail })
exit!(1)
end
end
end
private_class_method :execute_posix
# This is private method.
# @comment see call to private_class_method after method definition
# @api private
#
def self.execute_windows(command, options, stdin, stdout, stderr)
command = command.map do |part|
part.include?(' ') ? %Q("#{part.gsub(/"/, '\"')}") : part
end.join(" ") if command.is_a?(Array)
options[:custom_environment] ||= {}
Puppet::Util.withenv(options[:custom_environment]) do
Puppet::Util::Windows::Process.execute(command, options, stdin, stdout, stderr)
end
end
private_class_method :execute_windows
# This is private method.
# @comment see call to private_class_method after method definition
# @api private
#
def self.wait_for_output(stdout)
# Make sure the file's actually been written. This is basically a race
# condition, and is probably a horrible way to handle it, but, well, oh
# well.
# (If this method were treated as private / inaccessible from outside of this file, we shouldn't have to worry
# about a race condition because all of the places that we call this from are preceded by a call to "waitpid2",
# meaning that the processes responsible for writing the file have completed before we get here.)
2.times do |try|
if Puppet::FileSystem.exist?(stdout.path)
stdout.open
begin
return stdout.read
ensure
stdout.close
stdout.unlink
end
else
time_to_sleep = try / 2.0
Puppet.warning _("Waiting for output; will sleep %{time_to_sleep} seconds") % { time_to_sleep: time_to_sleep }
sleep(time_to_sleep)
end
end
nil
end
private_class_method :wait_for_output
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/multi_match.rb | lib/puppet/util/multi_match.rb | # frozen_string_literal: true
# MultiMatch allows multiple values to be tested at once in a case expression.
# This class is needed since Array does not implement the === operator to mean
# "each v === other.each v".
#
# This class is useful in situations when the Puppet Type System cannot be used
# (e.g. in Logging, since it needs to be able to log very early in the initialization
# cycle of puppet)
#
# Typically used with the constants
# NOT_NIL
# TUPLE
# TRIPLE
#
# which test against single NOT_NIL value, Array with two NOT_NIL, and Array with three NOT_NIL
#
module Puppet::Util
class MultiMatch
attr_reader :values
def initialize(*values)
@values = values
end
def ===(other)
lv = @values # local var is faster than instance var
case other
when MultiMatch
return false unless other.values.size == values.size
other.values.each_with_index { |v, i| return false unless lv[i] === v || v === lv[i] }
when Array
return false unless other.size == values.size
other.each_with_index { |v, i| return false unless lv[i] === v || v === lv[i] }
else
false
end
true
end
# Matches any value that is not nil using the === operator.
#
class MatchNotNil
def ===(v)
!v.nil?
end
end
NOT_NIL = MatchNotNil.new().freeze
TUPLE = MultiMatch.new(NOT_NIL, NOT_NIL).freeze
TRIPLE = MultiMatch.new(NOT_NIL, NOT_NIL, NOT_NIL).freeze
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/provider_features.rb | lib/puppet/util/provider_features.rb | # frozen_string_literal: true
# Provides feature definitions.
require_relative '../../puppet/util/docs'
require_relative '../../puppet/util'
# This module models provider features and handles checking whether the features
# are present.
# @todo Unclear what is api and what is private in this module.
#
module Puppet::Util::ProviderFeatures
include Puppet::Util::Docs
# This class models provider features and handles checking whether the features
# are present.
# @todo Unclear what is api and what is private in this class
class ProviderFeature
include Puppet::Util
include Puppet::Util::Docs
attr_accessor :name, :docs, :methods
# Are all of the requirements met?
# Requirements are checked by checking if feature predicate methods have been generated - see {#methods_available?}.
# @param obj [Object, Class] the object or class to check if requirements are met
# @return [Boolean] whether all requirements for this feature are met or not.
def available?(obj)
if methods
!!methods_available?(obj)
else
# In this case, the provider has to declare support for this
# feature, and that's been checked before we ever get to the
# method checks.
false
end
end
def initialize(name, docs, methods: nil)
self.name = name.intern
self.docs = docs
@methods = methods
end
private
# Checks whether all feature predicate methods are available.
# @param obj [Object, Class] the object or class to check if feature predicates are available or not.
# @return [Boolean] Returns whether all of the required methods are available or not in the given object.
def methods_available?(obj)
methods.each do |m|
if obj.is_a?(Class)
return false unless obj.public_method_defined?(m)
else
return false unless obj.respond_to?(m)
end
end
true
end
end
# Defines one feature.
# At a minimum, a feature requires a name
# and docs, and at this point they should also specify a list of methods
# required to determine if the feature is present.
# @todo How methods that determine if the feature is present are specified.
def feature(name, docs, hash = {})
@features ||= {}
raise Puppet::DevError, _("Feature %{name} is already defined") % { name: name } if @features.include?(name)
begin
obj = ProviderFeature.new(name, docs, **hash)
@features[obj.name] = obj
rescue ArgumentError => detail
error = ArgumentError.new(
_("Could not create feature %{name}: %{detail}") % { name: name, detail: detail }
)
error.set_backtrace(detail.backtrace)
raise error
end
end
# @return [String] Returns a string with documentation covering all features.
def featuredocs
str = ''.dup
@features ||= {}
return nil if @features.empty?
names = @features.keys.sort_by(&:to_s)
names.each do |name|
doc = @features[name].docs.gsub(/\n\s+/, " ")
str << "- *#{name}*: #{doc}\n"
end
if providers.length > 0
headers = ["Provider", names].flatten
data = {}
providers.each do |provname|
data[provname] = []
prov = provider(provname)
names.each do |name|
if prov.feature?(name)
data[provname] << "*X*"
else
data[provname] << ""
end
end
end
str << doctable(headers, data)
end
str
end
# @return [Array<String>] Returns a list of features.
def features
@features ||= {}
@features.keys
end
# Generates a module that sets up the boolean predicate methods to test for given features.
#
def feature_module
unless defined?(@feature_module)
@features ||= {}
@feature_module = ::Module.new
const_set("FeatureModule", @feature_module)
features = @features
# Create a feature? method that can be passed a feature name and
# determine if the feature is present.
@feature_module.send(:define_method, :feature?) do |name|
method = name.to_s + "?"
return !!(respond_to?(method) and send(method))
end
# Create a method that will list all functional features.
@feature_module.send(:define_method, :features) do
return false unless defined?(features)
features.keys.find_all { |n| feature?(n) }.sort_by(&:to_s)
end
# Create a method that will determine if a provided list of
# features are satisfied by the curred provider.
@feature_module.send(:define_method, :satisfies?) do |*needed|
ret = true
needed.flatten.each do |feature|
unless feature?(feature)
ret = false
break
end
end
ret
end
# Create a boolean method for each feature so you can test them
# individually as you might need.
@features.each do |name, feature|
method = name.to_s + "?"
@feature_module.send(:define_method, method) do
(is_a?(Class) ? declared_feature?(name) : self.class.declared_feature?(name)) or feature.available?(self)
end
end
# Allow the provider to declare that it has a given feature.
@feature_module.send(:define_method, :has_features) do |*names|
@declared_features ||= []
names.each do |name|
@declared_features << name.intern
end
end
# Aaah, grammatical correctness
@feature_module.send(:alias_method, :has_feature, :has_features)
end
@feature_module
end
# @return [ProviderFeature] Returns a provider feature instance by name.
# @param name [String] the name of the feature to return
# @note Should only be used for testing.
# @api private
#
def provider_feature(name)
return nil unless defined?(@features)
@features[name]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/skip_tags.rb | lib/puppet/util/skip_tags.rb | # frozen_string_literal: true
require_relative '../../puppet/util/tagging'
class Puppet::Util::SkipTags
include Puppet::Util::Tagging
def initialize(stags)
self.tags = stags unless defined?(@tags)
end
def split_qualified_tags?
false
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/network_device.rb | lib/puppet/util/network_device.rb | # frozen_string_literal: true
class Puppet::Util::NetworkDevice
class << self
attr_reader :current
end
def self.init(device)
require "puppet/util/network_device/#{device.provider}/device"
@current = Puppet::Util::NetworkDevice.const_get(device.provider.capitalize).const_get(:Device).new(device.url, device.options)
rescue => detail
raise detail, _("Can't load %{provider} for %{device}: %{detail}") % { provider: device.provider, device: device.name, detail: detail }, detail.backtrace
end
# Should only be used in tests
def self.teardown
@current = nil
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/run_mode.rb | lib/puppet/util/run_mode.rb | # frozen_string_literal: true
require 'etc'
module Puppet
module Util
class RunMode
def initialize(name)
@name = name.to_sym
end
attr_reader :name
def self.[](name)
@run_modes ||= {}
if Puppet::Util::Platform.windows?
@run_modes[name] ||= WindowsRunMode.new(name)
else
@run_modes[name] ||= UnixRunMode.new(name)
end
end
def server?
name == :master || name == :server
end
def master?
name == :master || name == :server
end
def agent?
name == :agent
end
def user?
name == :user
end
def run_dir
RunMode[name].run_dir
end
def log_dir
RunMode[name].log_dir
end
private
##
# select the system or the user directory depending on the context of
# this process. The most common use is determining filesystem path
# values for confdir and vardir. The intended semantics are:
# {https://projects.puppetlabs.com/issues/16637 #16637} for Puppet 3.x
#
# @todo this code duplicates {Puppet::Settings#which\_configuration\_file}
# as described in {https://projects.puppetlabs.com/issues/16637 #16637}
def which_dir(system, user)
if Puppet.features.root?
File.expand_path(system)
else
File.expand_path(user)
end
end
end
class UnixRunMode < RunMode
def conf_dir
which_dir("/etc/puppetlabs/puppet", "~/.puppetlabs/etc/puppet")
end
def code_dir
which_dir("/etc/puppetlabs/code", "~/.puppetlabs/etc/code")
end
def var_dir
which_dir("/opt/puppetlabs/puppet/cache", "~/.puppetlabs/opt/puppet/cache")
end
def public_dir
which_dir("/opt/puppetlabs/puppet/public", "~/.puppetlabs/opt/puppet/public")
end
def run_dir
which_dir("/var/run/puppetlabs", "~/.puppetlabs/var/run")
end
def log_dir
which_dir("/var/log/puppetlabs/puppet", "~/.puppetlabs/var/log")
end
def pkg_config_path
'/opt/puppetlabs/puppet/lib/pkgconfig'
end
def gem_cmd
'/opt/puppetlabs/puppet/bin/gem'
end
def common_module_dir
'/opt/puppetlabs/puppet/modules'
end
def vendor_module_dir
'/opt/puppetlabs/puppet/vendor_modules'
end
end
class WindowsRunMode < RunMode
def conf_dir
which_dir(File.join(windows_common_base("puppet/etc")), "~/.puppetlabs/etc/puppet")
end
def code_dir
which_dir(File.join(windows_common_base("code")), "~/.puppetlabs/etc/code")
end
def var_dir
which_dir(File.join(windows_common_base("puppet/cache")), "~/.puppetlabs/opt/puppet/cache")
end
def public_dir
which_dir(File.join(windows_common_base("puppet/public")), "~/.puppetlabs/opt/puppet/public")
end
def run_dir
which_dir(File.join(windows_common_base("puppet/var/run")), "~/.puppetlabs/var/run")
end
def log_dir
which_dir(File.join(windows_common_base("puppet/var/log")), "~/.puppetlabs/var/log")
end
def pkg_config_path
nil
end
def gem_cmd
if (puppet_dir = ENV.fetch('PUPPET_DIR', nil))
File.join(puppet_dir.to_s, 'bin', 'gem.bat')
else
File.join(Gem.default_bindir, 'gem.bat')
end
end
def common_module_dir
"#{installdir}/puppet/modules" if installdir
end
def vendor_module_dir
"#{installdir}\\puppet\\vendor_modules" if installdir
end
private
def installdir
ENV.fetch('FACTER_env_windows_installdir', nil)
end
def windows_common_base(*extra)
[ENV.fetch('ALLUSERSPROFILE', nil), "PuppetLabs"] + extra
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/tagging.rb | lib/puppet/util/tagging.rb | # frozen_string_literal: true
require_relative '../../puppet/util/tag_set'
module Puppet::Util::Tagging
ValidTagRegex = /\A[[:alnum:]_][[:alnum:]_:.-]*\Z/u
# Add a tag to the current tag set.
# When a tag set is used for a scope, these tags will be added to all of
# the objects contained in this scope when the objects are finished.
#
def tag(*ary)
@tags ||= new_tags
ary.flatten.compact.each do |tag|
name = tag.to_s.downcase
# Add the tag before testing if it's valid since this means that
# we never need to test the same valid tag twice. This speeds things
# up since we get a lot of duplicates and rarely fail on bad tags
if @tags.add?(name)
# not seen before, so now we test if it is valid
if valid_tag?(name)
if split_qualified_tags?
# avoid adding twice by first testing if the string contains '::'
@tags.merge(name.split('::')) if name.include?('::')
end
else
@tags.delete(name)
fail(Puppet::ParseError, _("Invalid tag '%{name}'") % { name: name })
end
end
end
end
# Add a name to the current tag set. Silently ignore names that does not
# represent valid tags.
#
# Use this method instead of doing this:
#
# tag(name) if is_valid?(name)
#
# since that results in testing the same string twice
#
def tag_if_valid(name)
if name.is_a?(String) && valid_tag?(name)
name = name.downcase
@tags ||= new_tags
if @tags.add?(name) && name.include?('::')
@tags.merge(name.split('::'))
end
end
end
# Answers if this resource is tagged with at least one of the given tags.
#
# The given tags are converted to downcased strings before the match is performed.
#
# @param *tags [String] splat of tags to look for
# @return [Boolean] true if this instance is tagged with at least one of the provided tags
#
def tagged?(*tags)
raw_tagged?(tags.collect { |t| t.to_s.downcase })
end
# Answers if this resource is tagged with at least one of the tags given in downcased string form.
#
# The method is a faster variant of the tagged? method that does no conversion of its
# arguments.
#
# @param tag_array [Array[String]] array of tags to look for
# @return [Boolean] true if this instance is tagged with at least one of the provided tags
#
def raw_tagged?(tag_array)
my_tags = tags
!tag_array.index { |t| my_tags.include?(t) }.nil?
end
# Only use this method when copying known tags from one Tagging instance to another
def set_tags(tag_source)
@tags = tag_source.tags
end
# Return a copy of the tag list, so someone can't ask for our tags
# and then modify them.
def tags
@tags ||= new_tags
@tags.dup
end
# Merge tags from a tagged instance with no attempts to split, downcase
# or verify the tags
def merge_tags_from(tag_source)
@tags ||= new_tags
tag_source.merge_into(@tags)
end
# Merge the tags of this instance into the provide TagSet
def merge_into(tag_set)
tag_set.merge(@tags) unless @tags.nil?
end
def tags=(tags)
@tags = new_tags
return if tags.nil?
tags = tags.strip.split(/\s*,\s*/) if tags.is_a?(String)
tag(*tags)
end
def valid_tag?(maybe_tag)
tag_enc = maybe_tag.encoding
if tag_enc == Encoding::UTF_8 || tag_enc == Encoding::ASCII
maybe_tag =~ ValidTagRegex
else
maybe_tag.encode(Encoding::UTF_8) =~ ValidTagRegex
end
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError
false
end
private
def split_qualified_tags?
true
end
def new_tags
Puppet::Util::TagSet.new
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rpm_compare.rb | lib/puppet/util/rpm_compare.rb | # frozen_string_literal: true
require 'English'
module Puppet::Util::RpmCompare
ARCH_LIST = %w[
noarch i386 i686 ppc ppc64 armv3l armv4b armv4l armv4tl armv5tel
armv5tejl armv6l armv7l m68kmint s390 s390x ia64 x86_64 sh3 sh4
].freeze
ARCH_REGEX = Regexp.new(ARCH_LIST.map { |arch| "\\.#{arch}" }.join('|'))
# This is an attempt at implementing RPM's
# lib/rpmvercmp.c rpmvercmp(a, b) in Ruby.
#
# Some of the things in here look REALLY
# UGLY and/or arbitrary. Our goal is to
# match how RPM compares versions, quirks
# and all.
#
# I've kept a lot of C-like string processing
# in an effort to keep this as identical to RPM
# as possible.
#
# returns 1 if str1 is newer than str2,
# 0 if they are identical
# -1 if str1 is older than str2
def rpmvercmp(str1, str2)
return 0 if str1 == str2
front_strip_re = /^[^A-Za-z0-9~]+/
while str1.length > 0 or str2.length > 0
# trim anything that's in front_strip_re and != '~' off the beginning of each string
str1 = str1.gsub(front_strip_re, '')
str2 = str2.gsub(front_strip_re, '')
# "handle the tilde separator, it sorts before everything else"
if str1 =~ /^~/ && str2 =~ /^~/
# if they both have ~, strip it
str1 = str1[1..]
str2 = str2[1..]
next
elsif str1 =~ /^~/
return -1
elsif str2 =~ /^~/
return 1
end
break if str1.length == 0 or str2.length == 0
# "grab first completely alpha or completely numeric segment"
isnum = false
# if the first char of str1 is a digit, grab the chunk of continuous digits from each string
if str1 =~ /^[0-9]+/
if str1 =~ /^[0-9]+/
segment1 = $LAST_MATCH_INFO.to_s
str1 = $LAST_MATCH_INFO.post_match
else
segment1 = ''
end
if str2 =~ /^[0-9]+/
segment2 = $LAST_MATCH_INFO.to_s
str2 = $LAST_MATCH_INFO.post_match
else
segment2 = ''
end
isnum = true
# else grab the chunk of continuous alphas from each string (which may be '')
else
if str1 =~ /^[A-Za-z]+/
segment1 = $LAST_MATCH_INFO.to_s
str1 = $LAST_MATCH_INFO.post_match
else
segment1 = ''
end
if str2 =~ /^[A-Za-z]+/
segment2 = $LAST_MATCH_INFO.to_s
str2 = $LAST_MATCH_INFO.post_match
else
segment2 = ''
end
end
# if the segments we just grabbed from the strings are different types (i.e. one numeric one alpha),
# where alpha also includes ''; "numeric segments are always newer than alpha segments"
if segment2.length == 0
return 1 if isnum
return -1
end
if isnum
# "throw away any leading zeros - it's a number, right?"
segment1 = segment1.gsub(/^0+/, '')
segment2 = segment2.gsub(/^0+/, '')
# "whichever number has more digits wins"
return 1 if segment1.length > segment2.length
return -1 if segment1.length < segment2.length
end
# "strcmp will return which one is greater - even if the two segments are alpha
# or if they are numeric. don't return if they are equal because there might
# be more segments to compare"
rc = segment1 <=> segment2
return rc if rc != 0
end # end while loop
# if we haven't returned anything yet, "whichever version still has characters left over wins"
return 1 if str1.length > str2.length
return -1 if str1.length < str2.length
0
end
# parse a rpm "version" specification
# this re-implements rpm's
# rpmUtils.miscutils.stringToVersion() in ruby
def rpm_parse_evr(full_version)
epoch_index = full_version.index(':')
if epoch_index
epoch = full_version[0, epoch_index]
full_version = full_version[epoch_index + 1, full_version.length]
else
epoch = nil
end
begin
epoch = String(Integer(epoch))
rescue
# If there are non-digits in the epoch field, default to nil
epoch = nil
end
release_index = full_version.index('-')
if release_index
version = full_version[0, release_index]
release = full_version[release_index + 1, full_version.length]
arch = release.scan(ARCH_REGEX)[0]
if arch
architecture = arch.delete('.')
release.gsub!(ARCH_REGEX, '')
end
else
version = full_version
release = nil
end
{ :epoch => epoch, :version => version, :release => release, :arch => architecture }
end
# this method is a native implementation of the
# compare_values function in rpm's python bindings,
# found in python/header-py.c, as used by rpm.
def compare_values(s1, s2)
return 0 if s1.nil? && s2.nil?
return 1 if !s1.nil? && s2.nil?
return -1 if s1.nil? && !s2.nil?
rpmvercmp(s1, s2)
end
# how rpm compares two package versions:
# rpmUtils.miscutils.compareEVR(), which massages data types and then calls
# rpm.labelCompare(), found in rpm.git/python/header-py.c, which
# sets epoch to 0 if null, then compares epoch, then ver, then rel
# using compare_values() and returns the first non-0 result, else 0.
# This function combines the logic of compareEVR() and labelCompare().
#
# "version_should" can be v, v-r, or e:v-r.
# "version_is" will always be at least v-r, can be e:v-r
#
# return 1: a is newer than b
# 0: a and b are the same version
# -1: b is newer than a
def rpm_compare_evr(should, is)
# pass on to rpm labelCompare
should_hash = rpm_parse_evr(should)
is_hash = rpm_parse_evr(is)
unless should_hash[:epoch].nil?
rc = compare_values(should_hash[:epoch], is_hash[:epoch])
return rc unless rc == 0
end
rc = compare_values(should_hash[:version], is_hash[:version])
return rc unless rc == 0
# here is our special case, PUP-1244.
# if should_hash[:release] is nil (not specified by the user),
# and comparisons up to here are equal, return equal. We need to
# evaluate to whatever level of detail the user specified, so we
# don't end up upgrading or *downgrading* when not intended.
#
# This should NOT be triggered if we're trying to ensure latest.
return 0 if should_hash[:release].nil?
compare_values(should_hash[:release], is_hash[:release])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/posix.rb | lib/puppet/util/posix.rb | # frozen_string_literal: true
# Utility methods for interacting with POSIX objects; mostly user and group
module Puppet::Util::POSIX
# This is a list of environment variables that we will set when we want to override the POSIX locale
LOCALE_ENV_VARS = %w[LANG LC_ALL LC_MESSAGES LANGUAGE
LC_COLLATE LC_CTYPE LC_MONETARY LC_NUMERIC LC_TIME]
# This is a list of user-related environment variables that we will unset when we want to provide a pristine
# environment for "exec" runs
USER_ENV_VARS = %w[HOME USER LOGNAME]
class << self
# Returns an array of all the groups that the user's a member of.
def groups_of(user)
begin
require_relative '../../puppet/ffi/posix'
groups = get_groups_list(user)
rescue StandardError, LoadError => e
Puppet.debug("Falling back to Puppet::Etc.group: #{e.message}")
groups = []
Puppet::Etc.group do |group|
groups << group.name if group.mem.include?(user)
end
end
uniq_groups = groups.uniq
if uniq_groups != groups
Puppet.debug(_('Removing any duplicate group entries'))
end
uniq_groups
end
private
def get_groups_list(user)
raise LoadError, "The 'getgrouplist' method is not available" unless Puppet::FFI::POSIX::Functions.respond_to?(:getgrouplist)
user_gid = Puppet::Etc.getpwnam(user).gid
ngroups = Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS
loop do
FFI::MemoryPointer.new(:int) do |ngroups_ptr|
FFI::MemoryPointer.new(:uint, ngroups) do |groups_ptr|
old_ngroups = ngroups
ngroups_ptr.write_int(ngroups)
if Puppet::FFI::POSIX::Functions.getgrouplist(user, user_gid, groups_ptr, ngroups_ptr) != -1
groups_gids = groups_ptr.get_array_of_uint(0, ngroups_ptr.read_int)
result = []
groups_gids.each do |group_gid|
group_info = Puppet::Etc.getgrgid(group_gid)
result |= [group_info.name] if group_info.mem.include?(user)
end
return result
end
ngroups = ngroups_ptr.read_int
if ngroups <= old_ngroups
ngroups *= 2
end
end
end
end
end
end
# Retrieve a field from a POSIX Etc object. The id can be either an integer
# or a name. This only works for users and groups. It's also broken on
# some platforms, unfortunately, which is why we fall back to the other
# method search_posix_field in the gid and uid methods if a sanity check
# fails
def get_posix_field(space, field, id)
raise Puppet::DevError, _("Did not get id from caller") unless id
if id.is_a?(Integer)
if id > Puppet[:maximum_uid].to_i
Puppet.err _("Tried to get %{field} field for silly id %{id}") % { field: field, id: id }
return nil
end
method = methodbyid(space)
else
method = methodbyname(space)
end
begin
Etc.send(method, id).send(field)
rescue NoMethodError, ArgumentError
# ignore it; we couldn't find the object
nil
end
end
# A degenerate method of retrieving name/id mappings. The job of this method is
# to retrieve all objects of a certain type, search for a specific entry
# and then return a given field from that entry.
def search_posix_field(type, field, id)
idmethod = idfield(type)
integer = false
if id.is_a?(Integer)
integer = true
if id > Puppet[:maximum_uid].to_i
Puppet.err _("Tried to get %{field} field for silly id %{id}") % { field: field, id: id }
return nil
end
end
Etc.send(type) do |object|
if integer and object.send(idmethod) == id
return object.send(field)
elsif object.name == id
return object.send(field)
end
end
# Apparently the group/passwd methods need to get reset; if we skip
# this call, then new users aren't found.
case type
when :passwd; Etc.send(:endpwent)
when :group; Etc.send(:endgrent)
end
nil
end
# Determine what the field name is for users and groups.
def idfield(space)
case space.intern
when :gr, :group; :gid
when :pw, :user, :passwd; :uid
else
raise ArgumentError, _("Can only handle users and groups")
end
end
# Determine what the method is to get users and groups by id
def methodbyid(space)
case space.intern
when :gr, :group; :getgrgid
when :pw, :user, :passwd; :getpwuid
else
raise ArgumentError, _("Can only handle users and groups")
end
end
# Determine what the method is to get users and groups by name
def methodbyname(space)
case space.intern
when :gr, :group; :getgrnam
when :pw, :user, :passwd; :getpwnam
else
raise ArgumentError, _("Can only handle users and groups")
end
end
# Get the GID
def gid(group)
get_posix_value(:group, :gid, group)
end
# Get the UID
def uid(user)
get_posix_value(:passwd, :uid, user)
end
private
# Get the specified id_field of a given field (user or group),
# whether an ID name is provided
def get_posix_value(location, id_field, field)
begin
field = Integer(field)
rescue ArgumentError
# pass
end
if field.is_a?(Integer)
name = get_posix_field(location, :name, field)
return nil unless name
id = get_posix_field(location, id_field, name)
check_value = id
else
id = get_posix_field(location, id_field, field)
return nil unless id
name = get_posix_field(location, :name, id)
check_value = name
end
if check_value != field
check_value_id = get_posix_field(location, id_field, check_value) if check_value
if id == check_value_id
Puppet.debug("Multiple entries found for resource: '#{location}' with #{id_field}: #{id}")
id
else
Puppet.debug("The value retrieved: '#{check_value}' is different than the required state: '#{field}', searching in all entries")
search_posix_field(location, id_field, field)
end
else
id
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/colors.rb | lib/puppet/util/colors.rb | # frozen_string_literal: true
require_relative '../../puppet/util/platform'
module Puppet::Util::Colors
BLACK = { :console => "\e[0;30m", :html => "color: #FFA0A0" }
RED = { :console => "\e[0;31m", :html => "color: #FFA0A0" }
GREEN = { :console => "\e[0;32m", :html => "color: #00CD00" }
YELLOW = { :console => "\e[0;33m", :html => "color: #FFFF60" }
BLUE = { :console => "\e[0;34m", :html => "color: #80A0FF" }
MAGENTA = { :console => "\e[0;35m", :html => "color: #FFA500" }
CYAN = { :console => "\e[0;36m", :html => "color: #40FFFF" }
WHITE = { :console => "\e[0;37m", :html => "color: #FFFFFF" }
HBLACK = { :console => "\e[1;30m", :html => "color: #FFA0A0" }
HRED = { :console => "\e[1;31m", :html => "color: #FFA0A0" }
HGREEN = { :console => "\e[1;32m", :html => "color: #00CD00" }
HYELLOW = { :console => "\e[1;33m", :html => "color: #FFFF60" }
HBLUE = { :console => "\e[1;34m", :html => "color: #80A0FF" }
HMAGENTA = { :console => "\e[1;35m", :html => "color: #FFA500" }
HCYAN = { :console => "\e[1;36m", :html => "color: #40FFFF" }
HWHITE = { :console => "\e[1;37m", :html => "color: #FFFFFF" }
BG_RED = { :console => "\e[0;41m", :html => "background: #FFA0A0" }
BG_GREEN = { :console => "\e[0;42m", :html => "background: #00CD00" }
BG_YELLOW = { :console => "\e[0;43m", :html => "background: #FFFF60" }
BG_BLUE = { :console => "\e[0;44m", :html => "background: #80A0FF" }
BG_MAGENTA = { :console => "\e[0;45m", :html => "background: #FFA500" }
BG_CYAN = { :console => "\e[0;46m", :html => "background: #40FFFF" }
BG_WHITE = { :console => "\e[0;47m", :html => "background: #FFFFFF" }
BG_HRED = { :console => "\e[1;41m", :html => "background: #FFA0A0" }
BG_HGREEN = { :console => "\e[1;42m", :html => "background: #00CD00" }
BG_HYELLOW = { :console => "\e[1;43m", :html => "background: #FFFF60" }
BG_HBLUE = { :console => "\e[1;44m", :html => "background: #80A0FF" }
BG_HMAGENTA = { :console => "\e[1;45m", :html => "background: #FFA500" }
BG_HCYAN = { :console => "\e[1;46m", :html => "background: #40FFFF" }
BG_HWHITE = { :console => "\e[1;47m", :html => "background: #FFFFFF" }
RESET = { :console => "\e[0m", :html => "" }
Colormap = {
:debug => WHITE,
:info => GREEN,
:notice => CYAN,
:warning => YELLOW,
:err => HMAGENTA,
:alert => RED,
:emerg => HRED,
:crit => HRED,
:black => BLACK,
:red => RED,
:green => GREEN,
:yellow => YELLOW,
:blue => BLUE,
:magenta => MAGENTA,
:cyan => CYAN,
:white => WHITE,
:hblack => HBLACK,
:hred => HRED,
:hgreen => HGREEN,
:hyellow => HYELLOW,
:hblue => HBLUE,
:hmagenta => HMAGENTA,
:hcyan => HCYAN,
:hwhite => HWHITE,
:bg_red => BG_RED,
:bg_green => BG_GREEN,
:bg_yellow => BG_YELLOW,
:bg_blue => BG_BLUE,
:bg_magenta => BG_MAGENTA,
:bg_cyan => BG_CYAN,
:bg_white => BG_WHITE,
:bg_hred => BG_HRED,
:bg_hgreen => BG_HGREEN,
:bg_hyellow => BG_HYELLOW,
:bg_hblue => BG_HBLUE,
:bg_hmagenta => BG_HMAGENTA,
:bg_hcyan => BG_HCYAN,
:bg_hwhite => BG_HWHITE,
:reset => { :console => "\e[m", :html => "" }
}
def colorize(color, str)
case Puppet[:color]
when true, :ansi, "ansi", "yes"
console_color(color, str)
when :html, "html"
html_color(color, str)
else
str
end
end
def console_color(color, str)
Colormap[color][:console] +
str.gsub(RESET[:console], Colormap[color][:console]) +
RESET[:console]
end
def html_color(color, str)
span = '<span style="%s">' % Colormap[color][:html]
"#{span}%s</span>" % str.gsub(%r{<span .*?</span>}, "</span>\\0#{span}")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/watched_file.rb | lib/puppet/util/watched_file.rb | # frozen_string_literal: true
require_relative '../../puppet/util/watcher'
# Monitor a given file for changes on a periodic interval. Changes are detected
# by looking for a change in the file ctime.
class Puppet::Util::WatchedFile
# @!attribute [r] filename
# @return [String] The fully qualified path to the file.
attr_reader :filename
# @param filename [String] The fully qualified path to the file.
# @param timer [Puppet::Util::Watcher::Timer] The polling interval for checking for file
# changes. Setting the timeout to a negative value will treat the file as
# always changed. Defaults to `Puppet[:filetimeout]`
def initialize(filename, timer = Puppet::Util::Watcher::Timer.new(Puppet[:filetimeout]))
@filename = filename
@timer = timer
@info = Puppet::Util::Watcher::PeriodicWatcher.new(
Puppet::Util::Watcher::Common.file_ctime_change_watcher(@filename),
timer
)
end
# @return [true, false] If the file has changed since it was last checked.
def changed?
@info.changed?
end
# Allow this to be used as the name of the file being watched in various
# other methods (such as Puppet::FileSystem.exist?)
def to_str
@filename
end
def to_s
"<WatchedFile: filename = #{@filename}, timeout = #{@timer.timeout}>"
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/retry_action.rb | lib/puppet/util/retry_action.rb | # frozen_string_literal: true
module Puppet::Util::RetryAction
class RetryException < Exception; end # rubocop:disable Lint/InheritException
class RetryException::NoBlockGiven < RetryException; end
class RetryException::NoRetriesGiven < RetryException; end
class RetryException::RetriesExceeded < RetryException; end
# Execute the supplied block retrying with exponential backoff.
#
# @param [Hash] options the retry options
# @option options [Integer] :retries Maximum number of times to retry.
# @option options [Array<Exception>] :retry_exceptions ([StandardError]) Optional array of exceptions that are allowed to be retried.
# @yield The block to be executed.
def self.retry_action(options = {})
# Retry actions for a specified amount of time. This method will allow the final
# retry to complete even if that extends beyond the timeout period.
unless block_given?
raise RetryException::NoBlockGiven
end
retries = options[:retries]
if retries.nil?
raise RetryException::NoRetriesGiven
end
retry_exceptions = options[:retry_exceptions] || [StandardError]
failures = 0
begin
yield
rescue *retry_exceptions => e
if failures >= retries
raise RetryException::RetriesExceeded, _("%{retries} exceeded") % { retries: retries }, e.backtrace
end
Puppet.info(_("Caught exception %{klass}:%{error} retrying") % { klass: e.class, error: e })
failures += 1
# Increase the amount of time that we sleep after every
# failed retry attempt.
sleep(((2**failures) - 1) * 0.1)
retry
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/backups.rb | lib/puppet/util/backups.rb | # frozen_string_literal: true
require 'find'
require 'fileutils'
module Puppet::Util::Backups
# Deal with backups.
def perform_backup(file = nil)
# if they specifically don't want a backup, then just say
# we're good
return true unless self[:backup]
# let the path be specified
file ||= self[:path]
return true unless Puppet::FileSystem.exist?(file)
(bucket ? perform_backup_with_bucket(file) : perform_backup_with_backuplocal(file, self[:backup]))
end
private
def perform_backup_with_bucket(fileobj)
file = fileobj.instance_of?(String) ? fileobj : fileobj.name
case Puppet::FileSystem.lstat(file).ftype
when "directory"
# we don't need to backup directories when recurse is on
return true if self[:recurse]
info _("Recursively backing up to filebucket")
Find.find(self[:path]) { |f| backup_file_with_filebucket(f) if File.file?(f) }
when "file"; backup_file_with_filebucket(file)
when "link"; # do nothing
end
true
end
def perform_backup_with_backuplocal(fileobj, backup)
file = fileobj.instance_of?(String) ? fileobj : fileobj.name
newfile = file + backup
remove_backup(newfile)
begin
bfile = file + backup
# N.B. cp_r works on both files and directories
FileUtils.cp_r(file, bfile, :preserve => true)
true
rescue => detail
# since they said they want a backup, let's error out
# if we couldn't make one
self.fail Puppet::Error, _("Could not back %{file} up: %{message}") % { file: file, message: detail.message }, detail
end
end
def remove_backup(newfile)
if instance_of?(Puppet::Type::File) and self[:links] != :follow
method = :lstat
else
method = :stat
end
begin
stat = Puppet::FileSystem.send(method, newfile)
rescue Errno::ENOENT
return
end
if stat.ftype == "directory"
raise Puppet::Error, _("Will not remove directory backup %{newfile}; use a filebucket") % { newfile: newfile }
end
info _("Removing old backup of type %{file_type}") % { file_type: stat.ftype }
begin
Puppet::FileSystem.unlink(newfile)
rescue => detail
message = _("Could not remove old backup: %{detail}") % { detail: detail }
log_exception(detail, message)
self.fail Puppet::Error, message, detail
end
end
def backup_file_with_filebucket(f)
sum = bucket.backup(f)
info _("Filebucketed %{f} to %{filebucket} with sum %{sum}") % { f: f, filebucket: bucket.name, sum: sum }
sum
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows.rb | lib/puppet/util/windows.rb | # frozen_string_literal: true
require_relative '../../puppet/util/platform'
module Puppet::Util::Windows
module ADSI
class ADSIObject; end
class User < ADSIObject; end
class UserProfile; end
class Group < ADSIObject; end
end
module File; end
module Registry
end
module Service
DEFAULT_TIMEOUT = 30
end
module SID
class Principal; end
end
class EventLog; end
if Puppet::Util::Platform.windows?
# Note: Setting codepage here globally ensures all strings returned via
# WIN32OLE (Ruby's late-bound COM support) are encoded in Encoding::UTF_8
#
# Also, this does not modify the value of WIN32OLE.locale - which defaults
# to 2048 (at least on US English Windows) and is not listed in the MS
# locales table, here: https://msdn.microsoft.com/en-us/library/ms912047(v=winembedded.10).aspx
require 'win32ole'; WIN32OLE.codepage = WIN32OLE::CP_UTF8
# these reference platform specific gems
require_relative '../../puppet/ffi/windows'
require_relative 'windows/string'
require_relative 'windows/error'
require_relative 'windows/com'
require_relative 'windows/sid'
require_relative 'windows/principal'
require_relative 'windows/file'
require_relative 'windows/security'
require_relative 'windows/user'
require_relative 'windows/process'
require_relative 'windows/root_certs'
require_relative 'windows/access_control_entry'
require_relative 'windows/access_control_list'
require_relative 'windows/security_descriptor'
require_relative 'windows/adsi'
require_relative 'windows/registry'
require_relative 'windows/eventlog'
require_relative 'windows/service'
require_relative 'windows/monkey_patches/process'
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/character_encoding.rb | lib/puppet/util/character_encoding.rb | # frozen_string_literal: true
# A module to centralize heuristics/practices for managing character encoding in Puppet
module Puppet::Util::CharacterEncoding
class << self
# Given a string, attempts to convert a copy of the string to UTF-8. Conversion uses
# encode - the string's internal byte representation is modifed to UTF-8.
#
# This method is intended for situations where we generally trust that the
# string's bytes are a faithful representation of the current encoding
# associated with it, and can use it as a starting point for transcoding
# (conversion) to UTF-8.
#
# @api public
# @param [String] string a string to transcode
# @return [String] copy of the original string, in UTF-8 if transcodable
def convert_to_utf_8(string)
original_encoding = string.encoding
string_copy = string.dup
begin
if original_encoding == Encoding::UTF_8
unless string_copy.valid_encoding?
Puppet.debug {
_("%{value} is already labeled as UTF-8 but this encoding is invalid. It cannot be transcoded by Puppet.") % { value: string.dump }
}
end
# String is already valid UTF-8 - noop
string_copy
else
# If the string comes to us as BINARY encoded, we don't know what it
# started as. However, to encode! we need a starting place, and our
# best guess is whatever the system currently is (default_external).
# So set external_encoding to default_external before we try to
# transcode to UTF-8.
string_copy.force_encoding(Encoding.default_external) if original_encoding == Encoding::BINARY
string_copy.encode(Encoding::UTF_8)
end
rescue EncodingError => detail
# Set the encoding on our copy back to its original if we modified it
string_copy.force_encoding(original_encoding) if original_encoding == Encoding::BINARY
# Catch both our own self-determined failure to transcode as well as any
# error on ruby's part, ie Encoding::UndefinedConversionError on a
# failure to encode!.
Puppet.debug {
_("%{error}: %{value} cannot be transcoded by Puppet.") % { error: detail.inspect, value: string.dump }
}
string_copy
end
end
# Given a string, tests if that string's bytes represent valid UTF-8, and if
# so return a copy of the string with external encoding set to UTF-8. Does
# not modify the byte representation of the string. If the string does not
# represent valid UTF-8, does not set the external encoding.
#
# This method is intended for situations where we do not believe that the
# encoding associated with a string is an accurate reflection of its actual
# bytes, i.e., effectively when we believe Ruby is incorrect in its
# assertion of the encoding of the string.
#
# @api public
# @param [String] string to set external encoding (re-label) to utf-8
# @return [String] a copy of string with external encoding set to utf-8, or
# a copy of the original string if override would result in invalid encoding.
def override_encoding_to_utf_8(string)
string_copy = string.dup
original_encoding = string_copy.encoding
return string_copy if original_encoding == Encoding::UTF_8
if string_copy.force_encoding(Encoding::UTF_8).valid_encoding?
string_copy
else
Puppet.debug {
_("%{value} is not valid UTF-8 and result of overriding encoding would be invalid.") % { value: string.dump }
}
# Set copy back to its original encoding before returning
string_copy.force_encoding(original_encoding)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/metric.rb | lib/puppet/util/metric.rb | # frozen_string_literal: true
# included so we can test object types
require_relative '../../puppet'
require_relative '../../puppet/network/format_support'
# A class for handling metrics. This is currently ridiculously hackish.
class Puppet::Util::Metric
include Puppet::Util::PsychSupport
include Puppet::Network::FormatSupport
attr_accessor :type, :name, :value, :label
attr_writer :values
def self.from_data_hash(data)
metric = allocate
metric.initialize_from_hash(data)
metric
end
def initialize_from_hash(data)
@name = data['name']
@label = data['label'] || self.class.labelize(@name)
@values = data['values']
end
def to_data_hash
{
'name' => @name,
'label' => @label,
'values' => @values
}
end
# Return a specific value
def [](name)
value = @values.find { |v| v[0] == name }
if value
value[2]
else
0
end
end
def initialize(name, label = nil)
@name = name.to_s
@label = label || self.class.labelize(name)
@values = []
end
def newvalue(name, value, label = nil)
raise ArgumentError, "metric name #{name.inspect} is not a string" unless name.is_a? String
label ||= self.class.labelize(name)
@values.push [name, label, value]
end
def values
@values.sort_by { |a| a[1] }
end
# Convert a name into a label.
def self.labelize(name)
name.to_s.capitalize.tr("_", " ")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/constant_inflector.rb | lib/puppet/util/constant_inflector.rb | # frozen_string_literal: true
# Created on 2008-02-12
# Copyright Luke Kanies
# NOTE: I think it might be worth considering moving these methods directly into Puppet::Util.
# A common module for converting between constants and
# file names.
module Puppet
module Util
module ConstantInflector
def file2constant(file)
file.split("/").collect(&:capitalize).join("::").gsub(/_+(.)/) { |_term| ::Regexp.last_match(1).capitalize }
end
module_function :file2constant
def constant2file(constant)
constant.to_s.gsub(/([a-z])([A-Z])/) { |_term| ::Regexp.last_match(1) + "_#{::Regexp.last_match(2)}" }.gsub("::", "/").downcase
end
module_function :constant2file
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/checksums.rb | lib/puppet/util/checksums.rb | # frozen_string_literal: true
require 'digest/md5'
require 'digest/sha1'
require 'time'
# A stand-alone module for calculating checksums
# in a generic way.
module Puppet::Util::Checksums
module_function
# If you modify this, update puppet/type/file/checksum.rb too
KNOWN_CHECKSUMS = [
:sha256, :sha256lite,
:md5, :md5lite,
:sha1, :sha1lite,
:sha512,
:sha384,
:sha224,
:mtime, :ctime, :none
].freeze
# It's not a good idea to use some of these in some contexts: for example, I
# wouldn't try bucketing a file using the :none checksum type.
def known_checksum_types
KNOWN_CHECKSUMS
end
def valid_checksum?(type, value)
!!send("#{type}?", value)
rescue NoMethodError
false
end
class FakeChecksum
def <<(*args)
self
end
end
# Is the provided string a checksum?
def checksum?(string)
# 'sha256lite'.length == 10
string =~ /^\{(\w{3,10})\}\S+/
end
# Strip the checksum type from an existing checksum
def sumdata(checksum)
checksum =~ /^\{(\w+)\}(.+)/ ? ::Regexp.last_match(2) : nil
end
# Strip the checksum type from an existing checksum
def sumtype(checksum)
checksum =~ /^\{(\w+)\}/ ? ::Regexp.last_match(1) : nil
end
# Calculate a checksum using Digest::SHA256.
def sha256(content)
require 'digest/sha2'
Digest::SHA256.hexdigest(content)
end
def sha256?(string)
string =~ /^\h{64}$/
end
def sha256_file(filename, lite = false)
require 'digest/sha2'
digest = Digest::SHA256.new
checksum_file(digest, filename, lite)
end
def sha256_stream(lite = false, &block)
require 'digest/sha2'
digest = Digest::SHA256.new
checksum_stream(digest, block, lite)
end
def sha256_hex_length
64
end
def sha256lite(content)
sha256(content[0..511])
end
def sha256lite?(string)
sha256?(string)
end
def sha256lite_file(filename)
sha256_file(filename, true)
end
def sha256lite_stream(&block)
sha256_stream(true, &block)
end
def sha256lite_hex_length
sha256_hex_length
end
# Calculate a checksum using Digest::SHA384.
def sha384(content)
require 'digest/sha2'
Digest::SHA384.hexdigest(content)
end
def sha384?(string)
string =~ /^\h{96}$/
end
def sha384_file(filename, lite = false)
require 'digest/sha2'
digest = Digest::SHA384.new
checksum_file(digest, filename, lite)
end
def sha384_stream(lite = false, &block)
require 'digest/sha2'
digest = Digest::SHA384.new
checksum_stream(digest, block, lite)
end
def sha384_hex_length
96
end
# Calculate a checksum using Digest::SHA512.
def sha512(content)
require 'digest/sha2'
Digest::SHA512.hexdigest(content)
end
def sha512?(string)
string =~ /^\h{128}$/
end
def sha512_file(filename, lite = false)
require 'digest/sha2'
digest = Digest::SHA512.new
checksum_file(digest, filename, lite)
end
def sha512_stream(lite = false, &block)
require 'digest/sha2'
digest = Digest::SHA512.new
checksum_stream(digest, block, lite)
end
def sha512_hex_length
128
end
# Calculate a checksum using Digest::SHA224.
def sha224(content)
require_relative '../../puppet/ssl/openssl_loader'
OpenSSL::Digest.new('SHA224').hexdigest(content)
end
def sha224?(string)
string =~ /^\h{56}$/
end
def sha224_file(filename, lite = false)
require_relative '../../puppet/ssl/openssl_loader'
digest = OpenSSL::Digest.new('SHA224')
checksum_file(digest, filename, lite)
end
def sha224_stream(lite = false, &block)
require_relative '../../puppet/ssl/openssl_loader'
digest = OpenSSL::Digest.new('SHA224')
checksum_stream(digest, block, lite)
end
def sha224_hex_length
56
end
# Calculate a checksum using Digest::MD5.
def md5(content)
Digest::MD5.hexdigest(content)
end
def md5?(string)
string =~ /^\h{32}$/
end
# Calculate a checksum of a file's content using Digest::MD5.
def md5_file(filename, lite = false)
digest = Digest::MD5.new
checksum_file(digest, filename, lite)
end
def md5_stream(lite = false, &block)
digest = Digest::MD5.new
checksum_stream(digest, block, lite)
end
def md5_hex_length
32
end
# Calculate a checksum of the first 500 chars of the content using Digest::MD5.
def md5lite(content)
md5(content[0..511])
end
def md5lite?(string)
md5?(string)
end
# Calculate a checksum of the first 500 chars of a file's content using Digest::MD5.
def md5lite_file(filename)
md5_file(filename, true)
end
def md5lite_stream(&block)
md5_stream(true, &block)
end
def md5lite_hex_length
md5_hex_length
end
def mtime(content)
""
end
def mtime?(string)
return true if string.is_a? Time
!!DateTime.parse(string)
rescue
false
end
# Return the :mtime timestamp of a file.
def mtime_file(filename)
Puppet::FileSystem.stat(filename).mtime
end
# by definition this doesn't exist
# but we still need to execute the block given
def mtime_stream(&block)
noop_digest = FakeChecksum.new
yield noop_digest
nil
end
# Calculate a checksum using Digest::SHA1.
def sha1(content)
Digest::SHA1.hexdigest(content)
end
def sha1?(string)
string =~ /^\h{40}$/
end
# Calculate a checksum of a file's content using Digest::SHA1.
def sha1_file(filename, lite = false)
digest = Digest::SHA1.new
checksum_file(digest, filename, lite)
end
def sha1_stream(lite = false, &block)
digest = Digest::SHA1.new
checksum_stream(digest, block, lite)
end
def sha1_hex_length
40
end
# Calculate a checksum of the first 500 chars of the content using Digest::SHA1.
def sha1lite(content)
sha1(content[0..511])
end
def sha1lite?(string)
sha1?(string)
end
# Calculate a checksum of the first 500 chars of a file's content using Digest::SHA1.
def sha1lite_file(filename)
sha1_file(filename, true)
end
def sha1lite_stream(&block)
sha1_stream(true, &block)
end
def sha1lite_hex_length
sha1_hex_length
end
def ctime(content)
""
end
def ctime?(string)
return true if string.is_a? Time
!!DateTime.parse(string)
rescue
false
end
# Return the :ctime of a file.
def ctime_file(filename)
Puppet::FileSystem.stat(filename).ctime
end
def ctime_stream(&block)
mtime_stream(&block)
end
def none(content)
""
end
def none?(string)
string.empty?
end
# Return a "no checksum"
def none_file(filename)
""
end
def none_stream
noop_digest = FakeChecksum.new
yield noop_digest
""
end
class DigestLite
def initialize(digest, lite = false)
@digest = digest
@lite = lite
@bytes = 0
end
# Provide an interface for digests. If lite, only digest the first 512 bytes
def <<(str)
if @lite
if @bytes < 512
buf = str[0, 512 - @bytes]
@digest << buf
@bytes += buf.length
end
else
@digest << str
end
end
end
# Perform an incremental checksum on a file.
def checksum_file(digest, filename, lite = false)
buffer = lite ? 512 : 4096
File.open(filename, 'rb') do |file|
while content = file.read(buffer) # rubocop:disable Lint/AssignmentInCondition
digest << content
break if lite
end
end
digest.hexdigest
end
def checksum_stream(digest, block, lite = false)
block.call(DigestLite.new(digest, lite))
digest.hexdigest
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler/logging.rb | lib/puppet/util/profiler/logging.rb | # frozen_string_literal: true
class Puppet::Util::Profiler::Logging
def initialize(logger, identifier)
@logger = logger
@identifier = identifier
@sequence = Sequence.new
end
def start(description, metric_id)
@sequence.next
@sequence.down
do_start(description, metric_id)
end
def finish(context, description, metric_id)
profile_explanation = do_finish(context, description, metric_id)[:msg]
@sequence.up
@logger.call("PROFILE [#{@identifier}] #{@sequence} #{description}: #{profile_explanation}")
end
def shutdown
# nothing to do
end
class Sequence
INITIAL = 0
SEPARATOR = '.'
def initialize
@elements = [INITIAL]
end
def next
@elements[-1] += 1
end
def down
@elements << INITIAL
end
def up
@elements.pop
end
def to_s
@elements.join(SEPARATOR)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler/object_counts.rb | lib/puppet/util/profiler/object_counts.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/profiler/logging'
class Puppet::Util::Profiler::ObjectCounts < Puppet::Util::Profiler::Logging
def start
ObjectSpace.count_objects
end
def finish(before)
after = ObjectSpace.count_objects
diff = before.collect do |type, count|
[type, after[type] - count]
end
diff.sort.collect { |pair| pair.join(': ') }.join(', ')
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler/around_profiler.rb | lib/puppet/util/profiler/around_profiler.rb | # frozen_string_literal: true
# A Profiler that can be used to wrap around blocks of code. It is configured
# with other profilers and controls them to start before the block is executed
# and finish after the block is executed.
#
# @api private
class Puppet::Util::Profiler::AroundProfiler
def initialize
@profilers = []
end
# Reset the profiling system to the original state
#
# @api private
def clear
@profilers = []
end
# Retrieve the current list of profilers
#
# @api private
def current
@profilers
end
# @param profiler [#profile] A profiler for the current thread
# @api private
def add_profiler(profiler)
@profilers << profiler
profiler
end
# @param profiler [#profile] A profiler to remove from the current thread
# @api private
def remove_profiler(profiler)
@profilers.delete(profiler)
end
# Profile a block of code and log the time it took to execute.
#
# This outputs logs entries to the Puppet masters logging destination
# providing the time it took, a message describing the profiled code
# and a leaf location marking where the profile method was called
# in the profiled hierarchy.
#
# @param message [String] A description of the profiled event
# @param metric_id [Array] A list of strings making up the ID of a metric to profile
# @param block [Block] The segment of code to profile
# @api private
def profile(message, metric_id)
retval = nil
contexts = {}
@profilers.each do |profiler|
contexts[profiler] = profiler.start(message, metric_id)
end
begin
retval = yield
ensure
@profilers.each do |profiler|
profiler.finish(contexts[profiler], message, metric_id)
end
end
retval
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler/wall_clock.rb | lib/puppet/util/profiler/wall_clock.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/profiler/logging'
# A profiler implementation that measures the number of seconds a segment of
# code takes to execute and provides a callback with a string representation of
# the profiling information.
#
# @api private
class Puppet::Util::Profiler::WallClock < Puppet::Util::Profiler::Logging
def do_start(description, metric_id)
Timer.new
end
def do_finish(context, description, metric_id)
{ :time => context.stop,
:msg => _("took %{context} seconds") % { context: context } }
end
class Timer
FOUR_DECIMAL_DIGITS = '%0.4f'
def initialize
@start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second)
end
def stop
@time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) - @start
@time
end
def to_s
format(FOUR_DECIMAL_DIGITS, @time)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/profiler/aggregate.rb | lib/puppet/util/profiler/aggregate.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/profiler'
require_relative '../../../puppet/util/profiler/wall_clock'
class Puppet::Util::Profiler::Aggregate < Puppet::Util::Profiler::WallClock
def initialize(logger, identifier)
super(logger, identifier)
@metrics_hash = Metric.new
end
def shutdown
super
@logger.call("AGGREGATE PROFILING RESULTS:")
@logger.call("----------------------------")
print_metrics(@metrics_hash, "")
@logger.call("----------------------------")
end
def do_finish(context, description, metric_id)
result = super(context, description, metric_id)
update_metric(@metrics_hash, metric_id, result[:time])
result
end
def update_metric(metrics_hash, metric_id, time)
first, *rest = *metric_id
if first
m = metrics_hash[first]
m.increment
m.add_time(time)
if rest.count > 0
update_metric(m, rest, time)
end
end
end
def values
@metrics_hash
end
def print_metrics(metrics_hash, prefix)
metrics_hash.sort_by { |_k, v| v.time }.reverse_each do |k, v|
@logger.call("#{prefix}#{k}: #{v.time} s (#{v.count} calls)")
print_metrics(metrics_hash[k], "#{prefix}#{k} -> ")
end
end
class Metric < Hash
def initialize
super
@count = 0
@time = 0
end
attr_reader :count, :time
def [](key)
unless has_key?(key)
self[key] = Metric.new
end
super(key)
end
def increment
@count += 1
end
def add_time(time)
@time += time
end
end
class Timer
def initialize
@start = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second)
end
def stop
Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) - @start
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/at_fork/solaris.rb | lib/puppet/util/at_fork/solaris.rb | # frozen_string_literal: true
require_relative '../../../puppet'
require 'fiddle'
# Early versions of Fiddle relied on the deprecated DL module and used
# classes defined in the namespace of that module instead of classes defined
# in the Fiddle's own namespace e.g. DL::Handle instead of Fiddle::Handle.
# We don't support those.
raise LoadError, _('The loaded Fiddle version is not supported.') unless defined?(Fiddle::Handle)
# Solaris implementation of the Puppet::Util::AtFork handler.
# The callbacks defined in this implementation ensure the forked process runs
# in a different contract than the parent process. This is necessary in order
# for the child process to be able to survive termination of the contract its
# parent process runs in. This is needed notably for an agent run executed
# by a puppet agent service to be able to restart that service without being
# killed in the process as a consequence of running in the same contract as
# the service, as all processes in the contract are killed when the contract
# is terminated during the service restart.
class Puppet::Util::AtFork::Solaris
private
{
'libcontract.so.1' => [
# function name, return value type, parameter types, ...
[:ct_ctl_abandon, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_tmpl_activate, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_tmpl_clear, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_tmpl_set_informative, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_tmpl_set_critical, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_pr_tmpl_set_param, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_pr_tmpl_set_fatal, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT],
[:ct_status_read, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP],
[:ct_status_get_id, Fiddle::TYPE_INT, Fiddle::TYPE_VOIDP],
[:ct_status_free, Fiddle::TYPE_VOID, Fiddle::TYPE_VOIDP]
],
}.each do |library, functions|
libhandle = Fiddle::Handle.new(library)
functions.each do |f|
define_method f[0], Fiddle::Function.new(libhandle[f[0].to_s], f[2..], f[1]).method(:call).to_proc
end
end
CTFS_PR_ROOT = File.join('', %w[system contract process])
CTFS_PR_TEMPLATE = File.join(CTFS_PR_ROOT, 'template')
CTFS_PR_LATEST = File.join(CTFS_PR_ROOT, 'latest')
CT_PR_PGRPONLY = 0x4
CT_PR_EV_HWERR = 0x20
CTD_COMMON = 0
def raise_if_error(&block)
unless (e = yield) == 0
e = SystemCallError.new(nil, e)
raise e, e.message, caller
end
end
def activate_new_contract_template
tmpl = File.new(CTFS_PR_TEMPLATE, File::RDWR)
begin
tmpl_fd = tmpl.fileno
raise_if_error { ct_pr_tmpl_set_param(tmpl_fd, CT_PR_PGRPONLY) }
raise_if_error { ct_pr_tmpl_set_fatal(tmpl_fd, CT_PR_EV_HWERR) }
raise_if_error { ct_tmpl_set_critical(tmpl_fd, 0) }
raise_if_error { ct_tmpl_set_informative(tmpl_fd, CT_PR_EV_HWERR) }
raise_if_error { ct_tmpl_activate(tmpl_fd) }
rescue
tmpl.close
raise
end
@tmpl = tmpl
rescue => detail
Puppet.log_exception(detail, _('Failed to activate a new process contract template'))
end
def deactivate_contract_template(parent)
return if @tmpl.nil?
tmpl = @tmpl
@tmpl = nil
begin
raise_if_error { ct_tmpl_clear(tmpl.fileno) }
rescue => detail
msg = if parent
_('Failed to deactivate process contract template in the parent process')
else
_('Failed to deactivate process contract template in the child process')
end
Puppet.log_exception(detail, msg)
exit(1)
ensure
tmpl.close
end
end
def get_latest_child_contract_id
stat = File.new(CTFS_PR_LATEST, File::RDONLY)
begin
stathdl = Fiddle::Pointer.new(0)
raise_if_error { ct_status_read(stat.fileno, CTD_COMMON, stathdl.ref) }
ctid = ct_status_get_id(stathdl)
ct_status_free(stathdl)
ensure
stat.close
end
ctid
rescue => detail
Puppet.log_exception(detail, _('Failed to get latest child process contract id'))
nil
end
def abandon_latest_child_contract
ctid = get_latest_child_contract_id
return if ctid.nil?
begin
ctl = File.new(File.join(CTFS_PR_ROOT, ctid.to_s, 'ctl'), File::WRONLY)
begin
raise_if_error { ct_ctl_abandon(ctl.fileno) }
ensure
ctl.close
end
rescue => detail
Puppet.log_exception(detail, _('Failed to abandon a child process contract'))
end
end
public
def prepare
activate_new_contract_template
end
def parent
deactivate_contract_template(true)
abandon_latest_child_contract
end
def child
deactivate_contract_template(false)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/at_fork/noop.rb | lib/puppet/util/at_fork/noop.rb | # frozen_string_literal: true
# A noop implementation of the Puppet::Util::AtFork handler
class Puppet::Util::AtFork::Noop
class << self
def new
# no need to instantiate every time, return the class object itself
self
end
def prepare
end
def parent
end
def child
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/command_line/trollop.rb | lib/puppet/util/command_line/trollop.rb | # frozen_string_literal: true
## lib/trollop.rb -- trollop command-line processing library
## Author:: William Morgan (mailto: wmorgan-trollop@masanjin.net)
## Copyright:: Copyright 2007 William Morgan
## License:: the same terms as ruby itself
##
## 2012-03: small changes made by cprice (chris@puppetlabs.com);
## patch submitted for upstream consideration:
## https://gitorious.org/trollop/mainline/merge_requests/9
## 2012-08: namespace changes made by Jeff McCune (jeff@puppetlabs.com)
## moved Trollop into Puppet::Util::CommandLine to prevent monkey
## patching the upstream trollop library if also loaded.
require 'date'
module Puppet
module Util
class CommandLine
module Trollop
VERSION = "1.16.2"
## Thrown by Parser in the event of a commandline error. Not needed if
## you're using the Trollop::options entry.
class CommandlineError < StandardError; end
## Thrown by Parser if the user passes in '-h' or '--help'. Handled
## automatically by Trollop#options.
class HelpNeeded < StandardError; end
## Thrown by Parser if the user passes in '-h' or '--version'. Handled
## automatically by Trollop#options.
class VersionNeeded < StandardError; end
## Regex for floating point numbers
FLOAT_RE = /^-?((\d+(\.\d+)?)|(\.\d+))([eE][-+]?\d+)?$/
## Regex for parameters
PARAM_RE = /^-(-|\.$|[^\d.])/
## The commandline parser. In typical usage, the methods in this class
## will be handled internally by Trollop::options. In this case, only the
## #opt, #banner and #version, #depends, and #conflicts methods will
## typically be called.
##
## If you want to instantiate this class yourself (for more complicated
## argument-parsing logic), call #parse to actually produce the output hash,
## and consider calling it from within
## Trollop::with_standard_exception_handling.
class Parser
## The set of values that indicate a flag option when passed as the
## +:type+ parameter of #opt.
FLAG_TYPES = [:flag, :bool, :boolean]
## The set of values that indicate a single-parameter (normal) option when
## passed as the +:type+ parameter of #opt.
##
## A value of +io+ corresponds to a readable IO resource, including
## a filename, URI, or the strings 'stdin' or '-'.
SINGLE_ARG_TYPES = [:int, :integer, :string, :double, :float, :io, :date]
## The set of values that indicate a multiple-parameter option (i.e., that
## takes multiple space-separated values on the commandline) when passed as
## the +:type+ parameter of #opt.
MULTI_ARG_TYPES = [:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
## The complete set of legal values for the +:type+ parameter of #opt.
TYPES = FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
INVALID_SHORT_ARG_REGEX = /[\d-]/ # :nodoc:
## The values from the commandline that were not interpreted by #parse.
attr_reader :leftovers
## The complete configuration hashes for each option. (Mainly useful
## for testing.)
attr_reader :specs
## A flag that determines whether or not to attempt to automatically generate "short" options if they are not
## explicitly specified.
attr_accessor :create_default_short_options
## A flag that determines whether or not to raise an error if the parser is passed one or more
## options that were not registered ahead of time. If 'true', then the parser will simply
## ignore options that it does not recognize.
attr_accessor :ignore_invalid_options
## A flag indicating whether or not the parser should attempt to handle "--help" and
## "--version" specially. If 'false', it will treat them just like any other option.
attr_accessor :handle_help_and_version
## Initializes the parser, and instance-evaluates any block given.
def initialize *a, &b
@version = nil
@leftovers = []
@specs = {}
@long = {}
@short = {}
@order = []
@constraints = []
@stop_words = []
@stop_on_unknown = false
# instance_eval(&b) if b # can't take arguments
cloaker(&b).bind_call(self, *a) if b
end
## Define an option. +name+ is the option name, a unique identifier
## for the option that you will use internally, which should be a
## symbol or a string. +desc+ is a string description which will be
## displayed in help messages.
##
## Takes the following optional arguments:
##
## [+:long+] Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the +name+ option into a string, and replacing any _'s by -'s.
## [+:short+] Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from +name+.
## [+:type+] Require that the argument take a parameter or parameters of type +type+. For a single parameter, the value can be a member of +SINGLE_ARG_TYPES+, or a corresponding Ruby class (e.g. +Integer+ for +:int+). For multiple-argument parameters, the value can be any member of +MULTI_ARG_TYPES+ constant. If unset, the default argument type is +:flag+, meaning that the argument does not take a parameter. The specification of +:type+ is not necessary if a +:default+ is given.
## [+:default+] Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a +nil+ value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a +:type+ is not necessary if a +:default+ is given. (But see below for an important caveat when +:multi+: is specified too.) If the argument is a flag, and the default is set to +true+, then if it is specified on the commandline the value will be +false+.
## [+:required+] If set to +true+, the argument must be provided on the commandline.
## [+:multi+] If set to +true+, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
##
## Note that there are two types of argument multiplicity: an argument
## can take multiple values, e.g. "--arg 1 2 3". An argument can also
## be allowed to occur multiple times, e.g. "--arg 1 --arg 2".
##
## Arguments that take multiple values should have a +:type+ parameter
## drawn from +MULTI_ARG_TYPES+ (e.g. +:strings+), or a +:default:+
## value of an array of the correct type (e.g. [String]). The
## value of this argument will be an array of the parameters on the
## commandline.
##
## Arguments that can occur multiple times should be marked with
## +:multi+ => +true+. The value of this argument will also be an array.
## In contrast with regular non-multi options, if not specified on
## the commandline, the default value will be [], not nil.
##
## These two attributes can be combined (e.g. +:type+ => +:strings+,
## +:multi+ => +true+), in which case the value of the argument will be
## an array of arrays.
##
## There's one ambiguous case to be aware of: when +:multi+: is true and a
## +:default+ is set to an array (of something), it's ambiguous whether this
## is a multi-value argument as well as a multi-occurrence argument.
## In this case, Trollop assumes that it's not a multi-value argument.
## If you want a multi-value, multi-occurrence argument with a default
## value, you must specify +:type+ as well.
def opt name, desc = "", opts = {}
raise ArgumentError, _("you already have an argument named '%{name}'") % { name: name } if @specs.member? name
## fill in :type
opts[:type] = # normalize
case opts[:type]
when :boolean, :bool; :flag
when :integer; :int
when :integers; :ints
when :double; :float
when :doubles; :floats
when Class
case opts[:type].name
when 'TrueClass', 'FalseClass'; :flag
when 'String'; :string
when 'Integer'; :int
when 'Float'; :float
when 'IO'; :io
when 'Date'; :date
else
raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type].class.name }
end
when nil; nil
else
raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type] } unless TYPES.include?(opts[:type])
opts[:type]
end
## for options with :multi => true, an array default doesn't imply
## a multi-valued argument. for that you have to specify a :type
## as well. (this is how we disambiguate an ambiguous situation;
## see the docs for Parser#opt for details.)
disambiguated_default =
if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
opts[:default].first
else
opts[:default]
end
type_from_default =
case disambiguated_default
when Integer; :int
when Numeric; :float
when TrueClass, FalseClass; :flag
when String; :string
when IO; :io
when Date; :date
when Array
if opts[:default].empty?
raise ArgumentError, _("multiple argument type cannot be deduced from an empty array for '%{value0}'") % { value0: opts[:default][0].class.name }
end
case opts[:default][0] # the first element determines the types
when Integer; :ints
when Numeric; :floats
when String; :strings
when IO; :ios
when Date; :dates
else
raise ArgumentError, _("unsupported multiple argument type '%{value0}'") % { value0: opts[:default][0].class.name }
end
when nil; nil
else
raise ArgumentError, _("unsupported argument type '%{value0}'") % { value0: opts[:default].class.name }
end
raise ArgumentError, _(":type specification and default type don't match (default type is %{type_from_default})") % { type_from_default: type_from_default } if opts[:type] && type_from_default && opts[:type] != type_from_default
opts[:type] = opts[:type] || type_from_default || :flag
## fill in :long
opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.tr("_", "-")
opts[:long] =
case opts[:long]
when /^--([^-].*)$/
::Regexp.last_match(1)
when /^[^-]/
opts[:long]
else
raise ArgumentError, _("invalid long option name %{name}") % { name: opts[:long].inspect }
end
raise ArgumentError, _("long option name %{value0} is already taken; please specify a (different) :long") % { value0: opts[:long].inspect } if @long[opts[:long]]
## fill in :short
unless opts[:short] == :none
opts[:short] = opts[:short].to_s if opts[:short]
end
opts[:short] = case opts[:short]
when /^-(.)$/; ::Regexp.last_match(1)
when nil, :none, /^.$/; opts[:short]
else raise ArgumentError, _("invalid short option name '%{name}'") % { name: opts[:short].inspect }
end
if opts[:short]
raise ArgumentError, _("short option name %{value0} is already taken; please specify a (different) :short") % { value0: opts[:short].inspect } if @short[opts[:short]]
raise ArgumentError, _("a short option name can't be a number or a dash") if opts[:short] =~ INVALID_SHORT_ARG_REGEX
end
## fill in :default for flags
opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
## autobox :default for :multi (multi-occurrence) arguments
opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
## fill in :multi
opts[:multi] ||= false
opts[:desc] ||= desc
@long[opts[:long]] = name
@short[opts[:short]] = name if opts[:short] && opts[:short] != :none
@specs[name] = opts
@order << [:opt, name]
end
## Sets the version string. If set, the user can request the version
## on the commandline. Should probably be of the form "<program name>
## <version number>".
def version s = nil; @version = s if s; @version end
## Adds text to the help display. Can be interspersed with calls to
## #opt to build a multi-section help page.
def banner s; @order << [:text, s] end
alias :text :banner
## Marks two (or more!) options as requiring each other. Only handles
## undirected (i.e., mutual) dependencies. Directed dependencies are
## better modeled with Trollop::die.
def depends *syms
syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] }
@constraints << [:depends, syms]
end
## Marks two (or more!) options as conflicting.
def conflicts *syms
syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] }
@constraints << [:conflicts, syms]
end
## Defines a set of words which cause parsing to terminate when
## encountered, such that any options to the left of the word are
## parsed as usual, and options to the right of the word are left
## intact.
##
## A typical use case would be for subcommand support, where these
## would be set to the list of subcommands. A subsequent Trollop
## invocation would then be used to parse subcommand options, after
## shifting the subcommand off of ARGV.
def stop_on *words
@stop_words = [*words].flatten
end
## Similar to #stop_on, but stops on any unknown word when encountered
## (unless it is a parameter for an argument). This is useful for
## cases where you don't know the set of subcommands ahead of time,
## i.e., without first parsing the global options.
def stop_on_unknown
@stop_on_unknown = true
end
## Parses the commandline. Typically called by Trollop::options,
## but you can call it directly if you need more control.
##
## throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
def parse cmdline = ARGV
vals = {}
required = {}
if handle_help_and_version
unless @specs[:version] || @long["version"]
opt :version, _("Print version and exit") if @version
end
opt :help, _("Show this message") unless @specs[:help] || @long["help"]
end
@specs.each do |sym, opts|
required[sym] = true if opts[:required]
vals[sym] = opts[:default]
vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
end
resolve_default_short_options if create_default_short_options
## resolve symbols
given_args = {}
@leftovers = each_arg cmdline do |arg, params|
sym = case arg
when /^-([^-])$/
@short[::Regexp.last_match(1)]
when /^--no-([^-]\S*)$/
possible_match = @long["[no-]#{::Regexp.last_match(1)}"]
if !possible_match
partial_match = @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"]
if partial_match
Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match }
end
partial_match
else
possible_match
end
when /^--([^-]\S*)$/
possible_match = @long[::Regexp.last_match(1)] || @long["[no-]#{::Regexp.last_match(1)}"]
if !possible_match
partial_match = @long[::Regexp.last_match(1).tr('-', '_')] || @long[::Regexp.last_match(1).tr('_', '-')] || @long["[no-]#{::Regexp.last_match(1).tr('-', '_')}"] || @long["[no-]#{::Regexp.last_match(1).tr('_', '-')}"]
if partial_match
Puppet.deprecation_warning _("Partial argument match detected: correct argument is %{partial_match}, got %{arg}. Partial argument matching is deprecated and will be removed in a future release.") % { arg: arg, partial_match: partial_match }
end
partial_match
else
possible_match
end
else
raise CommandlineError, _("invalid argument syntax: '%{arg}'") % { arg: arg }
end
unless sym
next 0 if ignore_invalid_options
raise CommandlineError, _("unknown argument '%{arg}'") % { arg: arg } unless sym
end
if given_args.include?(sym) && !@specs[sym][:multi]
raise CommandlineError, _("option '%{arg}' specified multiple times") % { arg: arg }
end
given_args[sym] ||= {}
given_args[sym][:arg] = arg
given_args[sym][:params] ||= []
# The block returns the number of parameters taken.
num_params_taken = 0
unless params.nil?
if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params[0, 1] # take the first parameter
num_params_taken = 1
elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params # take all the parameters
num_params_taken = params.size
end
end
num_params_taken
end
if handle_help_and_version
## check for version and help args
raise VersionNeeded if given_args.include? :version
raise HelpNeeded if given_args.include? :help
end
## check constraint satisfaction
@constraints.each do |type, syms|
constraint_sym = syms.find { |sym| given_args[sym] }
next unless constraint_sym
case type
when :depends
syms.each { |sym| raise CommandlineError, _("--%{value0} requires --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } unless given_args.include? sym }
when :conflicts
syms.each { |sym| raise CommandlineError, _("--%{value0} conflicts with --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } if given_args.include?(sym) && (sym != constraint_sym) }
end
end
required.each do |sym, _val|
raise CommandlineError, _("option --%{opt} must be specified") % { opt: @specs[sym][:long] } unless given_args.include? sym
end
## parse parameters
given_args.each do |sym, given_data|
arg = given_data[:arg]
params = given_data[:params]
opts = @specs[sym]
raise CommandlineError, _("option '%{arg}' needs a parameter") % { arg: arg } if params.empty? && opts[:type] != :flag
vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
case opts[:type]
when :flag
if arg =~ /^--no-/ and sym.to_s =~ /^--\[no-\]/
vals[sym] = opts[:default]
else
vals[sym] = !opts[:default]
end
when :int, :ints
vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
when :float, :floats
vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
when :string, :strings
vals[sym] = params.map { |pg| pg.map(&:to_s) }
when :io, :ios
vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
when :date, :dates
vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
end
if SINGLE_ARG_TYPES.include?(opts[:type])
if opts[:multi] # multiple options, each with a single parameter
vals[sym] = vals[sym].map { |p| p[0] }
else # single parameter
vals[sym] = vals[sym][0][0]
end
elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
vals[sym] = vals[sym][0] # single option, with multiple parameters
end
# else: multiple options, with multiple parameters
opts[:callback].call(vals[sym]) if opts.has_key?(:callback)
end
## modify input in place with only those
## arguments we didn't process
cmdline.clear
@leftovers.each { |l| cmdline << l }
## allow openstruct-style accessors
class << vals
def method_missing(m, *args)
self[m] || self[m.to_s]
end
end
vals
end
def parse_date_parameter param, arg # :nodoc:
begin
time = Chronic.parse(param)
rescue NameError
# chronic is not available
end
time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError => e
raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, e.backtrace
end
## Print the help message to +stream+.
def educate stream = $stdout
width # just calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
left = {}
@specs.each do |name, spec|
left[name] = "--#{spec[:long]}" +
(spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
case spec[:type]
when :flag; ""
when :int; " <i>"
when :ints; " <i+>"
when :string; " <s>"
when :strings; " <s+>"
when :float; " <f>"
when :floats; " <f+>"
when :io; " <filename/uri>"
when :ios; " <filename/uri+>"
when :date; " <date>"
when :dates; " <date+>"
end
end
leftcol_width = left.values.map(&:length).max || 0
rightcol_start = leftcol_width + 6 # spaces
unless @order.size > 0 && @order.first.first == :text
stream.puts "#{@version}\n" if @version
stream.puts _("Options:")
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %#{leftcol_width}s: ", left[opt]
desc = spec[:desc] + begin
default_s = case spec[:default]
when $stdout; "<stdout>"
when $stdin; "<stdin>"
when $stderr; "<stderr>"
when Array
spec[:default].join(", ")
else
spec[:default].to_s
end
if spec[:default]
if spec[:desc] =~ /\.$/
_(" (Default: %{default_s})") % { default_s: default_s }
else
_(" (default: %{default_s})") % { default_s: default_s }
end
else
""
end
end
stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
end
end
def width # :nodoc:
@width ||= if $stdout.tty?
begin
require 'curses'
Curses.init_screen
x = Curses.cols
Curses.close_screen
x
rescue Exception
80
end
else
80
end
end
def wrap str, opts = {} # :nodoc:
if str == ""
[""]
else
str.split("\n").map { |s| wrap_line s, opts }.flatten
end
end
## The per-parser version of Trollop::die (see that for documentation).
def die arg, msg
if msg
$stderr.puts _("Error: argument --%{value0} %{msg}.") % { value0: @specs[arg][:long], msg: msg }
else
$stderr.puts _("Error: %{arg}.") % { arg: arg }
end
$stderr.puts _("Try --help for help.")
exit(-1)
end
private
## yield successive arg, parameter pairs
def each_arg args
remains = []
i = 0
until i >= args.length
if @stop_words.member? args[i]
remains += args[i..]
return remains
end
case args[i]
when /^--$/ # arg terminator
remains += args[(i + 1)..]
return remains
when /^--(\S+?)=(.*)$/ # long argument with equals
yield "--#{::Regexp.last_match(1)}", [::Regexp.last_match(2)]
i += 1
when /^--(\S+)$/ # long argument
params = collect_argument_parameters(args, i + 1)
if params.empty? # long argument no parameter
yield args[i], nil
i += 1
else
num_params_taken = yield args[i], params
unless num_params_taken
if @stop_on_unknown
remains += args[i + 1..]
return remains
else
remains += params
end
end
i += 1 + num_params_taken
end
when /^-(\S+)$/ # one or more short arguments
shortargs = ::Regexp.last_match(1).split(//)
shortargs.each_with_index do |a, j|
if j == (shortargs.length - 1)
params = collect_argument_parameters(args, i + 1)
if params.empty? # argument no parameter
yield "-#{a}", nil
i += 1
else
num_params_taken = yield "-#{a}", params
unless num_params_taken
if @stop_on_unknown
remains += args[i + 1..]
return remains
else
remains += params
end
end
i += 1 + num_params_taken
end
else
yield "-#{a}", nil
end
end
else
if @stop_on_unknown
remains += args[i..]
return remains
else
remains << args[i]
i += 1
end
end
end
remains
end
def parse_integer_parameter param, arg
raise CommandlineError, _("option '%{arg}' needs an integer") % { arg: arg } unless param =~ /^\d+$/
param.to_i
end
def parse_float_parameter param, arg
raise CommandlineError, _("option '%{arg}' needs a floating-point number") % { arg: arg } unless param =~ FLOAT_RE
param.to_f
end
def parse_io_parameter param, arg
case param
when /^(stdin|-)$/i; $stdin
else
require 'open-uri'
begin
URI.parse(param).open
rescue SystemCallError => e
raise CommandlineError, _("file or url for option '%{arg}' cannot be opened: %{value0}") % { arg: arg, value0: e.message }, e.backtrace
end
end
end
def collect_argument_parameters args, start_at
params = []
pos = start_at
while args[pos] && args[pos] !~ PARAM_RE && !@stop_words.member?(args[pos])
params << args[pos]
pos += 1
end
params
end
def resolve_default_short_options
@order.each do |type, name|
next unless type == :opt
opts = @specs[name]
next if opts[:short]
c = opts[:long].split(//).find { |d| d !~ INVALID_SHORT_ARG_REGEX && !@short.member?(d) }
if c # found a character to use
opts[:short] = c
@short[c] = name
end
end
end
def wrap_line str, opts = {}
prefix = opts[:prefix] || 0
width = opts[:width] || (self.width - 1)
start = 0
ret = []
until start > str.length
nextt =
if start + width >= str.length
str.length
else
x = str.rindex(/\s/, start + width)
x = str.index(/\s/, start) if x && x < start
x || str.length
end
ret << (ret.empty? ? "" : " " * prefix) + str[start...nextt]
start = nextt + 1
end
ret
end
## instance_eval but with ability to handle block arguments
## thanks to why: http://redhanded.hobix.com/inspect/aBlockCostume.html
def cloaker &b
(class << self; self; end).class_eval do
define_method :cloaker_, &b
meth = instance_method :cloaker_
remove_method :cloaker_
meth
end
end
end
## The easy, syntactic-sugary entry method into Trollop. Creates a Parser,
## passes the block to it, then parses +args+ with it, handling any errors or
## requests for help or version information appropriately (and then exiting).
## Modifies +args+ in place. Returns a hash of option values.
##
## The block passed in should contain zero or more calls to +opt+
## (Parser#opt), zero or more calls to +text+ (Parser#text), and
## probably a call to +version+ (Parser#version).
##
## The returned block contains a value for every option specified with
## +opt+. The value will be the value given on the commandline, or the
## default value if the option was not specified on the commandline. For
## every option specified on the commandline, a key "<option
## name>_given" will also be set in the hash.
##
## Example:
##
## require 'trollop'
## opts = Trollop::options do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
## opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs <i>, defaulting to 4
## opt :num_thumbs, "Number of thumbs", :type => :int # an integer --num-thumbs <i>, defaulting to nil
## end
##
## ## if called with no arguments
## p opts # => { :monkey => false, :goat => true, :num_limbs => 4, :num_thumbs => nil }
##
## ## if called with --monkey
## p opts # => {:monkey_given=>true, :monkey=>true, :goat=>true, :num_limbs=>4, :help=>false, :num_thumbs=>nil}
##
## See more examples at http://trollop.rubyforge.org.
def options args = ARGV, *a, &b
@last_parser = Parser.new(*a, &b)
with_standard_exception_handling(@last_parser) { @last_parser.parse args }
end
## If Trollop::options doesn't do quite what you want, you can create a Parser
## object and call Parser#parse on it. That method will throw CommandlineError,
## HelpNeeded and VersionNeeded exceptions when necessary; if you want to
## have these handled for you in the standard manner (e.g. show the help
## and then exit upon an HelpNeeded exception), call your code from within
## a block passed to this method.
##
## Note that this method will call System#exit after handling an exception!
##
## Usage example:
##
## require 'trollop'
## p = Trollop::Parser.new do
## opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
## opt :goat, "Use goat mode", :default => true # a flag --goat, defaulting to true
## end
##
## opts = Trollop::with_standard_exception_handling p do
## o = p.parse ARGV
## raise Trollop::HelpNeeded if ARGV.empty? # show help screen
## o
## end
##
## Requires passing in the parser object.
def with_standard_exception_handling parser
yield
rescue CommandlineError => e
$stderr.puts _("Error: %{value0}.") % { value0: e.message }
$stderr.puts _("Try --help for help.")
exit(-1)
rescue HelpNeeded
parser.educate
exit
rescue VersionNeeded
puts parser.version
exit
end
## Informs the user that their usage of 'arg' was wrong, as detailed by
## 'msg', and dies. Example:
##
## options do
## opt :volume, :default => 0.0
## end
##
## die :volume, "too loud" if opts[:volume] > 10.0
## die :volume, "too soft" if opts[:volume] < 0.1
##
## In the one-argument case, simply print that message, a notice
## about -h, and die. Example:
##
## options do
## opt :whatever # ...
## end
##
## Trollop::die "need at least one filename" if ARGV.empty?
def die arg, msg = nil
if @last_parser
@last_parser.die arg, msg
else
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/command_line/puppet_option_parser.rb | lib/puppet/util/command_line/puppet_option_parser.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/command_line/trollop'
module Puppet
module Util
class CommandLine
class PuppetOptionError < Puppet::Error
end
class TrollopCommandlineError < Puppet::Util::CommandLine::Trollop::CommandlineError; end
# This is a command line option parser. It is intended to have an API that is very similar to
# the ruby stdlib 'OptionParser' API, for ease of integration into our existing code... however,
# However, we've removed the OptionParser-based implementation and are only maintaining the
# it's implemented based on the third-party "trollop" library. This was done because there
# are places where the stdlib OptionParser is not flexible enough to meet our needs.
class PuppetOptionParser
def initialize(usage_msg = nil)
require_relative '../../../puppet/util/command_line/trollop'
@create_default_short_options = false
@parser = Trollop::Parser.new do
banner usage_msg
end
end
# This parameter, if set, will tell the underlying option parser not to throw an
# exception if we pass it options that weren't explicitly registered. We need this
# capability because we need to be able to pass all of the command-line options before
# we know which application/face they are going to be running, but the app/face
# may specify additional command-line arguments that are valid for that app/face.
attr_reader :ignore_invalid_options
def ignore_invalid_options=(value)
@parser.ignore_invalid_options = value
end
def on(*args, &block)
# The 2nd element is an optional "short" representation.
case args.length
when 3
long, desc, type = args
when 4
long, short, desc, type = args
else
raise ArgumentError, _("this method only takes 3 or 4 arguments. Given: %{args}") % { args: args.inspect }
end
options = {
:long => long,
:short => short,
:required => false,
:callback => pass_only_last_value_on_to(block),
:multi => true,
}
case type
when :REQUIRED
options[:type] = :string
when :NONE
options[:type] = :flag
else
raise PuppetOptionError, _("Unsupported type: '%{type}'") % { type: type }
end
@parser.opt long.sub("^--", "").intern, desc, options
end
def parse(*args)
args = args[0] if args.size == 1 and args[0].is_a?(Array)
args_copy = args.dup
begin
@parser.parse args_copy
rescue Puppet::Util::CommandLine::Trollop::CommandlineError => err
raise PuppetOptionError.new(_("Error parsing arguments"), err)
end
end
def pass_only_last_value_on_to(block)
->(values) { block.call(values.is_a?(Array) ? values.last : values) }
end
private :pass_only_last_value_on_to
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/watcher/periodic_watcher.rb | lib/puppet/util/watcher/periodic_watcher.rb | # frozen_string_literal: true
# Monitor a given watcher for changes on a periodic interval.
class Puppet::Util::Watcher::PeriodicWatcher
# @param watcher [Puppet::Util::Watcher::ChangeWatcher] a watcher for the value to watch
# @param timer [Puppet::Util::Watcher::Timer] A timer to determine when to
# recheck the watcher. If the timeout of the timer is negative, then the
# watched value is always considered to be changed
def initialize(watcher, timer)
@watcher = watcher
@timer = timer
@timer.start
end
# @return [true, false] If the file has changed since it was last checked.
def changed?
return true if always_consider_changed?
@watcher = examine_watched_info(@watcher)
@watcher.changed?
end
private
def always_consider_changed?
@timer.timeout < 0
end
def examine_watched_info(known)
if @timer.expired?
@timer.start
known.next_reading
else
known
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/watcher/timer.rb | lib/puppet/util/watcher/timer.rb | # frozen_string_literal: true
class Puppet::Util::Watcher::Timer
attr_reader :timeout
def initialize(timeout)
@timeout = timeout
end
def start
@start_time = now
end
def expired?
(now - @start_time) >= @timeout
end
def now
Time.now.to_i
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/watcher/change_watcher.rb | lib/puppet/util/watcher/change_watcher.rb | # frozen_string_literal: true
# Watches for changes over time. It only re-examines the values when it is requested to update readings.
# @api private
class Puppet::Util::Watcher::ChangeWatcher
def self.watch(reader)
Puppet::Util::Watcher::ChangeWatcher.new(nil, nil, reader).next_reading
end
def initialize(previous, current, value_reader)
@previous = previous
@current = current
@value_reader = value_reader
end
def changed?
if uncertain?
false
else
@previous != @current
end
end
def uncertain?
@previous.nil? || @current.nil?
end
def change_current_reading_to(new_value)
Puppet::Util::Watcher::ChangeWatcher.new(@current, new_value, @value_reader)
end
def next_reading
change_current_reading_to(@value_reader.call)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/ldap/connection.rb | lib/puppet/util/ldap/connection.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/ldap'
class Puppet::Util::Ldap::Connection
attr_accessor :host, :port, :user, :password, :reset, :ssl
attr_reader :connection
# Return a default connection, using our default settings.
def self.instance
ssl = if Puppet[:ldaptls]
:tls
elsif Puppet[:ldapssl]
true
else
false
end
options = {}
options[:ssl] = ssl
user = Puppet.settings[:ldapuser]
if user && user != ""
options[:user] = user
pass = Puppet.settings[:ldappassword]
if pass && pass != ""
options[:password] = pass
end
end
new(Puppet[:ldapserver], Puppet[:ldapport], options)
end
def close
connection.unbind if connection.bound?
end
def initialize(host, port, user: nil, password: nil, reset: nil, ssl: nil)
raise Puppet::Error, _("Could not set up LDAP Connection: Missing ruby/ldap libraries") unless Puppet.features.ldap?
@host = host
@port = port
@user = user
@password = password
@reset = reset
@ssl = ssl
end
# Create a per-connection unique name.
def name
[host, port, user, password, ssl].collect(&:to_s).join("/")
end
# Should we reset the connection?
def reset?
reset
end
# Start our ldap connection.
def start
case ssl
when :tls
@connection = LDAP::SSLConn.new(host, port, true)
when true
@connection = LDAP::SSLConn.new(host, port)
else
@connection = LDAP::Conn.new(host, port)
end
@connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
@connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)
@connection.simple_bind(user, password)
rescue => detail
raise Puppet::Error, _("Could not connect to LDAP: %{detail}") % { detail: detail }, detail.backtrace
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/ldap/generator.rb | lib/puppet/util/ldap/generator.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/ldap'
class Puppet::Util::Ldap::Generator
# Declare the attribute we'll use to generate the value.
def from(source)
@source = source
self
end
# Actually do the generation.
def generate(value = nil)
if value.nil?
@generator.call
else
@generator.call(value)
end
end
# Initialize our generator with the name of the parameter
# being generated.
def initialize(name)
@name = name
end
def name
@name.to_s
end
def source
if @source
@source.to_s
else
nil
end
end
# Provide the code that does the generation.
def with(&block)
@generator = block
self
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/ldap/manager.rb | lib/puppet/util/ldap/manager.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/ldap'
require_relative '../../../puppet/util/ldap/connection'
require_relative '../../../puppet/util/ldap/generator'
# The configuration class for LDAP providers, plus
# connection handling for actually interacting with ldap.
class Puppet::Util::Ldap::Manager
attr_reader :objectclasses, :puppet2ldap, :location, :rdn
# A null-op that just returns the config.
def and
self
end
# Set the offset from the search base and return the config.
def at(location)
@location = location
self
end
# The basic search base.
def base
[location, Puppet[:ldapbase]].join(",")
end
# Convert the name to a dn, then pass the args along to
# our connection.
def create(name, attributes)
attributes = attributes.dup
# Add the objectclasses
attributes["objectClass"] = objectclasses.collect(&:to_s)
attributes["objectClass"] << "top" unless attributes["objectClass"].include?("top")
attributes[rdn.to_s] = [name]
# Generate any new values we might need.
generate(attributes)
# And create our resource.
connect { |conn| conn.add dn(name), attributes }
end
# Open, yield, and close the connection. Cannot be left
# open, at this point.
def connect
# TRANSLATORS '#connect' is a method name and and should not be translated, 'block' refers to a Ruby code block
raise ArgumentError, _("You must pass a block to #connect") unless block_given?
unless @connection
if Puppet[:ldaptls]
ssl = :tls
elsif Puppet[:ldapssl]
ssl = true
else
ssl = false
end
options = { :ssl => ssl }
user = Puppet[:ldapuser]
if user && user != ""
options[:user] = user
end
password = Puppet[:ldappassword]
if password && password != ""
options[:password] = password
end
@connection = Puppet::Util::Ldap::Connection.new(Puppet[:ldapserver], Puppet[:ldapport], options)
end
@connection.start
begin
yield @connection.connection
ensure
@connection.close
end
nil
end
# Convert the name to a dn, then pass the args along to
# our connection.
def delete(name)
connect { |connection| connection.delete dn(name) }
end
# Calculate the dn for a given resource.
def dn(name)
["#{rdn}=#{name}", base].join(",")
end
# Convert an ldap-style entry hash to a provider-style hash.
def entry2provider(entry)
# TRANSLATOR 'dn' refers to a 'distinguished name' in LDAP (Lightweight Directory Access Protocol) and they should not be translated
raise ArgumentError, _("Could not get dn from ldap entry") unless entry["dn"]
# DN is always a single-entry array. Strip off the bits before the
# first comma, then the bits after the remaining equal sign. This is the
# name.
name = entry["dn"].dup.pop.split(",").shift.split("=").pop
result = { :name => name }
@ldap2puppet.each do |ldap, puppet|
result[puppet] = entry[ldap.to_s] || :absent
end
result
end
# Create our normal search filter.
def filter
(objectclasses.length == 1 ? "objectclass=#{objectclasses[0]}" : "(&(objectclass=" + objectclasses.join(")(objectclass=") + "))")
end
# Find the associated entry for a resource. Returns a hash, minus
# 'dn', or nil if the entry cannot be found.
def find(name)
connect do |conn|
conn.search2(dn(name), 0, "objectclass=*") do |result|
# Convert to puppet-appropriate attributes
return entry2provider(result)
end
rescue
return nil
end
end
# Declare a new attribute generator.
def generates(parameter)
@generators << Puppet::Util::Ldap::Generator.new(parameter)
@generators[-1]
end
# Generate any extra values we need to make the ldap entry work.
def generate(values)
return unless @generators.length > 0
@generators.each do |generator|
# Don't override any values that might exist.
next if values[generator.name]
if generator.source
value = values[generator.source]
unless value
raise ArgumentError, _("%{source} must be defined to generate %{name}") %
{ source: generator.source, name: generator.name }
end
result = generator.generate(value)
else
result = generator.generate
end
result = [result] unless result.is_a?(Array)
result = result.collect(&:to_s)
values[generator.name] = result
end
end
def initialize
@rdn = :cn
@generators = []
end
# Specify what classes this provider models.
def manages(*classes)
@objectclasses = classes
self
end
# Specify the attribute map. Assumes the keys are the puppet
# attributes, and the values are the ldap attributes, and creates a map
# for each direction.
def maps(attributes)
# The map with the puppet attributes as the keys
@puppet2ldap = attributes
# and the ldap attributes as the keys.
@ldap2puppet = attributes.each_with_object({}) { |ary, map| map[ary[1]] = ary[0]; }
self
end
# Return the ldap name for a puppet attribute.
def ldap_name(attribute)
@puppet2ldap[attribute].to_s
end
# Convert the name to a dn, then pass the args along to
# our connection.
def modify(name, mods)
connect { |connection| connection.modify dn(name), mods }
end
# Specify the rdn that we use to build up our dn.
def named_by(attribute)
@rdn = attribute
self
end
# Return the puppet name for an ldap attribute.
def puppet_name(attribute)
@ldap2puppet[attribute]
end
# Search for all entries at our base. A potentially expensive search.
def search(sfilter = nil)
sfilter ||= filter
result = []
connect do |conn|
conn.search2(base, 1, sfilter) do |entry|
result << entry2provider(entry)
end
end
(result.empty? ? nil : result)
end
# Update the ldap entry with the desired state.
def update(name, is, should)
if should[:ensure] == :absent
Puppet.info _("Removing %{name} from ldap") % { name: dn(name) }
delete(name)
return
end
# We're creating a new entry
if is.empty? or is[:ensure] == :absent
Puppet.info _("Creating %{name} in ldap") % { name: dn(name) }
# Remove any :absent params and :ensure, then convert the names to ldap names.
attrs = ldap_convert(should)
create(name, attrs)
return
end
# We're modifying an existing entry. Yuck.
mods = []
# For each attribute we're deleting that is present, create a
# modify instance for deletion.
[is.keys, should.keys].flatten.uniq.each do |property|
# They're equal, so do nothing.
next if is[property] == should[property]
attributes = ldap_convert(should)
prop_name = ldap_name(property).to_s
# We're creating it.
if is[property] == :absent or is[property].nil?
mods << LDAP::Mod.new(LDAP::LDAP_MOD_ADD, prop_name, attributes[prop_name])
next
end
# We're deleting it
if should[property] == :absent or should[property].nil?
mods << LDAP::Mod.new(LDAP::LDAP_MOD_DELETE, prop_name, [])
next
end
# We're replacing an existing value
mods << LDAP::Mod.new(LDAP::LDAP_MOD_REPLACE, prop_name, attributes[prop_name])
end
modify(name, mods)
end
# Is this a complete ldap configuration?
def valid?
location and objectclasses and !objectclasses.empty? and puppet2ldap
end
private
# Convert a hash of attributes to ldap-like forms. This mostly means
# getting rid of :ensure and making sure everything's an array of strings.
def ldap_convert(attributes)
attributes.reject { |param, value| value == :absent or param == :ensure }.each_with_object({}) do |ary, result|
value = (ary[1].is_a?(Array) ? ary[1] : [ary[1]]).collect(&:to_s)
result[ldap_name(ary[0])] = value
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/network_device/base.rb | lib/puppet/util/network_device/base.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/autoload'
require 'uri'
require_relative '../../../puppet/util/network_device/transport'
require_relative '../../../puppet/util/network_device/transport/base'
class Puppet::Util::NetworkDevice::Base
attr_accessor :url, :transport
def initialize(url, options = {})
@url = URI.parse(url)
@autoloader = Puppet::Util::Autoload.new(self, "puppet/util/network_device/transport")
if @autoloader.load(@url.scheme, Puppet.lookup(:current_environment))
@transport = Puppet::Util::NetworkDevice::Transport.const_get(@url.scheme.capitalize).new(options[:debug])
@transport.host = @url.host
@transport.port = @url.port || case @url.scheme; when "ssh"; 22; when "telnet"; 23; end
@transport.user = @url.user
@transport.password = @url.password
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/network_device/config.rb | lib/puppet/util/network_device/config.rb | # frozen_string_literal: true
require 'ostruct'
require_relative '../../../puppet/util/watched_file'
require_relative '../../../puppet/util/network_device'
class Puppet::Util::NetworkDevice::Config
def self.main
@main ||= new
end
def self.devices
main.devices || []
end
attr_reader :devices
def exists?
Puppet::FileSystem.exist?(@file.to_str)
end
def initialize
@file = Puppet::Util::WatchedFile.new(Puppet[:deviceconfig])
@devices = {}
read(true) # force reading at start
end
# Read the configuration file.
def read(force = false)
return unless exists?
parse if force or @file.changed?
end
private
def parse
begin
devices = {}
device = nil
File.open(@file) do |f|
file_line_count = 1
f.each do |line|
case line
when /^\s*#/ # skip comments
file_line_count += 1
next
when /^\s*$/ # skip blank lines
file_line_count += 1
next
when /^\[([\w.-]+)\]\s*$/ # [device.fqdn]
name = ::Regexp.last_match(1)
name.chomp!
if devices.include?(name)
file_error_location = Puppet::Util::Errors.error_location(nil, file_line_count)
device_error_location = Puppet::Util::Errors.error_location(nil, device.line)
raise Puppet::Error, _("Duplicate device found at %{file_error_location}, already found at %{device_error_location}") %
{ file_error_location: file_error_location, device_error_location: device_error_location }
end
device = OpenStruct.new
device.name = name
device.line = file_line_count
device.options = { :debug => false }
Puppet.debug "found device: #{device.name} at #{device.line}"
devices[name] = device
when /^\s*(type|url|debug)(\s+(.+)\s*)*$/
parse_directive(device, ::Regexp.last_match(1), ::Regexp.last_match(3), file_line_count)
else
error_location_str = Puppet::Util::Errors.error_location(nil, file_line_count)
raise Puppet::Error, _("Invalid entry at %{error_location}: %{file_text}") %
{ error_location: error_location_str, file_text: line }
end
end
end
rescue Errno::EACCES
Puppet.err _("Configuration error: Cannot read %{file}; cannot serve") % { file: @file }
# raise Puppet::Error, "Cannot read #{@config}"
rescue Errno::ENOENT
Puppet.err _("Configuration error: '%{file}' does not exit; cannot serve") % { file: @file }
end
@devices = devices
end
def parse_directive(device, var, value, count)
case var
when "type"
device.provider = value
when "url"
begin
URI.parse(value)
rescue URI::InvalidURIError
raise Puppet::Error, _("%{value} is an invalid url") % { value: value }
end
device.url = value
when "debug"
device.options[:debug] = true
else
error_location_str = Puppet::Util::Errors.error_location(nil, count)
raise Puppet::Error, _("Invalid argument '%{var}' at %{error_location}") % { var: var, error_location: error_location_str }
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/network_device/transport.rb | lib/puppet/util/network_device/transport.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/network_device'
# stub
module Puppet::Util::NetworkDevice::Transport
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/network_device/transport/base.rb | lib/puppet/util/network_device/transport/base.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/network_device'
require_relative '../../../../puppet/util/network_device/transport'
class Puppet::Util::NetworkDevice::Transport::Base
attr_accessor :user, :password, :host, :port
attr_accessor :default_prompt, :timeout
def initialize
@timeout = 10
end
def send(cmd)
end
def expect(prompt)
end
def command(cmd, options = {})
send(cmd)
expect(options[:prompt] || default_prompt) do |output|
yield output if block_given?
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/parser.rb | lib/puppet/util/rdoc/parser.rb | # frozen_string_literal: true
# Puppet "parser" for the rdoc system
# The parser uses puppet parser and traverse the AST to instruct RDoc about
# our current structures. It also parses ruby files that could contain
# either custom facts or puppet plugins (functions, types...)
# rdoc2 includes
require 'rdoc/code_objects'
require_relative '../../../puppet/util/rdoc/code_objects'
require 'rdoc/token_stream'
require 'rdoc/markup/pre_process'
require 'rdoc/parser'
require_relative 'parser/puppet_parser_rdoc2'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/code_objects.rb | lib/puppet/util/rdoc/code_objects.rb | # frozen_string_literal: true
require 'rdoc/code_objects'
module RDoc
# This modules contains various class that are used to hold information
# about the various Puppet language structures we found while parsing.
#
# Those will be mapped to their html counterparts which are defined in
# PuppetGenerator.
# PuppetTopLevel is a top level (usually a .pp/.rb file)
module PuppetTopLevel
attr_accessor :module_name, :global
end
# Add top level comments to a class or module
# @api private
module AddClassModuleComment
def add_comment(comment, location = nil)
super
end
end
# PuppetModule holds a Puppet Module
# This is mapped to an HTMLPuppetModule
# it leverage the RDoc (ruby) module infrastructure
class PuppetModule < NormalModule
include AddClassModuleComment
attr_accessor :facts, :plugins
def initialize(name, superclass = nil)
@facts = []
@plugins = []
@nodes = {}
super(name, superclass)
end
def add_plugin(plugin)
name = plugin.name
type = plugin.type
meth = AnyMethod.new("*args", name)
meth.params = "(*args)"
meth.visibility = :public
meth.document_self = true
meth.singleton = false
meth.comment = plugin.comment
case type
when 'function'
@function_container ||= add_module(NormalModule, "__functions__")
@function_container.add_method(meth)
when 'type'
@type_container ||= add_module(NormalModule, "__types__")
@type_container.add_method(meth)
end
end
def add_fact(fact)
@fact_container ||= add_module(NormalModule, "__facts__")
confine_str = fact.confine.empty? ? '' : fact.confine.to_s
const = Constant.new(fact.name, confine_str, fact.comment)
@fact_container.add_constant(const)
end
# Adds a module called __nodes__ and adds nodes to it as classes
#
def add_node(name, superclass)
cls = @nodes[name]
if cls
return cls
end
@node_container ||= add_module(NormalModule, "__nodes__")
cls = @node_container.add_class(PuppetNode, name, superclass)
@nodes[name] = cls unless @done_documenting
cls
end
def each_fact
@facts.each { |c| yield c }
end
def each_plugin
@plugins.each { |c| yield c }
end
def each_node
@nodes.each { |c| yield c }
end
def nodes
@nodes.values
end
end
# PuppetClass holds a puppet class
# It is mapped to a HTMLPuppetClass for display
# It leverages RDoc (ruby) Class
class PuppetClass < ClassModule
include AddClassModuleComment
attr_accessor :resource_list, :requires, :childs, :realizes
def initialize(name, superclass)
super(name, superclass)
@resource_list = []
@requires = []
@realizes = []
@childs = []
end
def aref_prefix
'puppet_class'
end
def add_resource(resource)
add_to(@resource_list, resource)
end
def is_module?
false
end
def superclass=(superclass)
@superclass = superclass
end
# we're (ab)using the RDoc require system here.
# we're adding a required Puppet class, overriding
# the RDoc add_require method which sees ruby required files.
def add_require(required)
add_to(@requires, required)
end
def add_realize(realized)
add_to(@realizes, realized)
end
def add_child(child)
@childs << child
end
# Look up the given symbol. RDoc only looks for class1::class2.method
# or class1::class2#method. Since our definitions are mapped to RDoc methods
# but are written class1::class2::define we need to perform the lookup by
# ourselves.
def find_symbol(symbol, method = nil)
result = super(symbol)
if !result and symbol =~ /::/
modules = symbol.split(/::/)
unless modules.empty?
module_name = modules.shift
result = find_module_named(module_name)
if result
last_name = ""
previous = nil
modules.each do |mod|
previous = result
last_name = mod
result = result.find_module_named(mod)
break unless result
end
unless result
result = previous
method = last_name
end
end
end
if result && method
unless result.respond_to?(:find_local_symbol)
p result.name
p method
fail
end
result = result.find_local_symbol(method)
end
end
result
end
end
# PuppetNode holds a puppet node
# It is mapped to a HTMLPuppetNode for display
# A node is just a variation of a class
class PuppetNode < PuppetClass
include AddClassModuleComment
def is_module?
false
end
end
# Plugin holds a native puppet plugin (function,type...)
# It is mapped to a HTMLPuppetPlugin for display
class Plugin < Context
attr_accessor :name, :type
def initialize(name, type)
super()
@name = name
@type = type
@comment = ""
end
def <=>(other)
@name <=> other.name
end
def full_name
@name
end
def http_url(prefix)
path = full_name.split("::")
File.join(prefix, *path) + ".html"
end
def is_fact?
false
end
def to_s
res = self.class.name + ": #{@name} (#{@type})\n"
res << @comment.to_s
res
end
end
# Fact holds a custom fact
# It is mapped to a HTMLPuppetPlugin for display
class Fact < Context
attr_accessor :name, :confine
def initialize(name, confine)
super()
@name = name
@confine = confine
@comment = ""
end
def <=>(other)
@name <=> other.name
end
def is_fact?
true
end
def full_name
@name
end
def to_s
res = self.class.name + ": #{@name}\n"
res << @comment.to_s
res
end
end
# PuppetResource holds a puppet resource
# It is mapped to a HTMLPuppetResource for display
# A resource is defined by its "normal" form Type[title]
class PuppetResource < CodeObject
attr_accessor :type, :title, :params
def initialize(type, title, comment, params)
super()
@type = type
@title = title
@comment = comment
@params = params
end
def <=>(other)
full_name <=> other.full_name
end
def full_name
@type + "[#{@title}]"
end
def name
full_name
end
def to_s
res = @type + "[#{@title}]\n"
res << @comment.to_s
res
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/generators/puppet_generator.rb | lib/puppet/util/rdoc/generators/puppet_generator.rb | # frozen_string_literal: true
require 'rdoc/generators/html_generator'
require_relative '../../../../puppet/util/rdoc/code_objects'
require 'digest/md5'
module Generators
# This module holds all the classes needed to generate the HTML documentation
# of a bunch of puppet manifests.
#
# It works by traversing all the code objects defined by the Puppet RDoc::Parser
# and produces HTML counterparts objects that in turns are used by RDoc template engine
# to produce the final HTML.
#
# It is also responsible of creating the whole directory hierarchy, and various index
# files.
#
# It is to be noted that the whole system is built on top of ruby RDoc. As such there
# is an implicit mapping of puppet entities to ruby entitites:
#
# Puppet => Ruby
# ------------------------
# Module Module
# Class Class
# Definition Method
# Resource
# Node
# Plugin
# Fact
MODULE_DIR = "modules"
NODE_DIR = "nodes"
PLUGIN_DIR = "plugins"
# We're monkey patching RDoc markup to allow
# lowercase class1::class2::class3 crossref hyperlinking
module MarkUp
alias :old_markup :markup
def new_markup(str, remove_para = false)
first = @markup.nil?
res = old_markup(str, remove_para)
if first and !@markup.nil?
@markup.add_special(/\b([a-z]\w+(::\w+)*)/, :CROSSREF)
# we need to call it again, since we added a rule
res = old_markup(str, remove_para)
end
res
end
alias :markup :new_markup
end
# This is a specialized HTMLGenerator tailored to Puppet manifests
class PuppetGenerator < HTMLGenerator
def self.for(options)
AllReferences.reset
HtmlMethod.reset
if options.all_one_file
PuppetGeneratorInOne.new(options)
else
PuppetGenerator.new(options)
end
end
def initialize(options) # :not-new:
@options = options
load_html_template
end
# loads our own html template file
def load_html_template
require_relative '../../../../puppet/util/rdoc/generators/template/puppet/puppet'
extend RDoc::Page
rescue LoadError
$stderr.puts "Could not find Puppet template '#{template}'"
exit 99
end
def gen_method_index
# we don't generate an all define index
# as the presentation is per module/per class
end
# This is the central method, it generates the whole structures
# along with all the indices.
def generate_html
super
gen_into(@nodes)
gen_into(@plugins)
end
##
# Generate:
# the list of modules
# the list of classes and definitions of a specific module
# the list of all classes
# the list of nodes
# the list of resources
def build_indices
@allfiles = []
@nodes = []
@plugins = []
# contains all the seen modules
@modules = {}
@allclasses = {}
# remove unknown toplevels
# it can happen that RDoc triggers a different parser for some files (ie .c, .cc or .h)
# in this case RDoc generates a RDoc::TopLevel which we do not support in this generator
# So let's make sure we don't generate html for those.
@toplevels = @toplevels.select { |tl| tl.is_a? RDoc::PuppetTopLevel }
# build the modules, classes and per modules classes and define list
@toplevels.each do |toplevel|
next unless toplevel.document_self
file = HtmlFile.new(toplevel, @options, FILE_DIR)
classes = []
methods = []
modules = []
nodes = []
# find all classes of this toplevel
# store modules if we find one
toplevel.each_classmodule do |k|
generate_class_list(classes, modules, k, toplevel, CLASS_DIR)
end
# find all defines belonging to this toplevel
HtmlMethod.all_methods.each do |m|
# find parent module, check this method is not already
# defined.
if m.context.parent.toplevel === toplevel
methods << m
end
end
classes.each do |k|
@allclasses[k.index_name] = k unless @allclasses.has_key?(k.index_name)
end
# generate nodes and plugins found
classes.each do |k|
next unless k.context.is_module?
k.context.each_node do |_name, node|
nodes << HTMLPuppetNode.new(node, toplevel, NODE_DIR, @options)
@nodes << nodes.last
end
k.context.each_plugin do |plugin|
@plugins << HTMLPuppetPlugin.new(plugin, toplevel, PLUGIN_DIR, @options)
end
k.context.each_fact do |fact|
@plugins << HTMLPuppetPlugin.new(fact, toplevel, PLUGIN_DIR, @options)
end
end
@files << file
@allfiles << { "file" => file, "modules" => modules, "classes" => classes, "methods" => methods, "nodes" => nodes }
end
# scan all classes to create the child's references
@allclasses.values.each do |klass|
superklass = klass.context.superclass
next unless superklass
superklass = AllReferences[superklass]
if superklass && (superklass.is_a?(HTMLPuppetClass) || superklass.is_a?(HTMLPuppetNode))
superklass.context.add_child(klass.context)
end
end
@classes = @allclasses.values
end
# produce a class/module list of HTMLPuppetModule/HTMLPuppetClass
# based on the code object traversal.
def generate_class_list(classes, modules, from, html_file, class_dir)
if from.is_module? and !@modules.has_key?(from.name)
k = HTMLPuppetModule.new(from, html_file, class_dir, @options)
classes << k
@modules[from.name] = k
modules << @modules[from.name]
elsif from.is_module?
modules << @modules[from.name]
elsif !from.is_module?
k = HTMLPuppetClass.new(from, html_file, class_dir, @options)
classes << k
end
from.each_classmodule do |mod|
generate_class_list(classes, modules, mod, html_file, class_dir)
end
end
# generate all the subdirectories, modules, classes and files
def gen_sub_directories
super
File.makedirs(MODULE_DIR)
File.makedirs(NODE_DIR)
File.makedirs(PLUGIN_DIR)
rescue
$stderr.puts $ERROR_INFO.message
exit 1
end
# generate the index of modules
def gen_file_index
gen_top_index(@modules.values, 'All Modules', RDoc::Page::TOP_INDEX, "fr_modules_index.html")
end
# generate a top index
def gen_top_index(collection, title, template, filename)
template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template)
res = []
collection.sort.each do |f|
if f.document_self
res << { "classlist" => CGI.escapeHTML("#{MODULE_DIR}/fr_#{f.index_name}.html"), "module" => CGI.escapeHTML("#{CLASS_DIR}/#{f.index_name}.html"), "name" => CGI.escapeHTML(f.index_name) }
end
end
values = {
"entries" => res,
'list_title' => CGI.escapeHTML(title),
'index_url' => main_url,
'charset' => @options.charset,
'style_url' => style_url('', @options.css),
}
Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f|
template.write_html_on(f, values)
end
end
# generate the all classes index file and the combo index
def gen_class_index
gen_an_index(@classes, 'All Classes', RDoc::Page::CLASS_INDEX, "fr_class_index.html")
@allfiles.each do |file|
next if file['file'].context.file_relative_name =~ /\.rb$/
gen_composite_index(
file,
RDoc::Page::COMBO_INDEX,
"#{MODULE_DIR}/fr_#{file['file'].context.module_name}.html"
)
end
end
def gen_composite_index(collection, template, filename)
return if Puppet::FileSystem.exist?(filename)
template = TemplatePage.new(RDoc::Page::FR_INDEX_BODY, template)
res1 = []
collection['classes'].sort.each do |f|
if f.document_self
res1 << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.index_name) } unless f.context.is_module?
end
end
res2 = []
collection['methods'].sort.each do |f|
res2 << { "href" => "../#{f.path}", "name" => f.index_name.sub(/\(.*\)$/, '') } if f.document_self
end
module_name = []
res3 = []
res4 = []
collection['modules'].sort.each do |f|
module_name << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.index_name) }
unless f.facts.nil?
f.facts.each do |fact|
res3 << { "href" => "../" + CGI.escapeHTML(AllReferences["PLUGIN(#{fact.name})"].path), "name" => CGI.escapeHTML(fact.name) }
end
end
next if f.plugins.nil?
f.plugins.each do |plugin|
res4 << { "href" => "../" + CGI.escapeHTML(AllReferences["PLUGIN(#{plugin.name})"].path), "name" => CGI.escapeHTML(plugin.name) }
end
end
res5 = []
collection['nodes'].sort.each do |f|
res5 << { "href" => "../" + CGI.escapeHTML(f.path), "name" => CGI.escapeHTML(f.name) } if f.document_self
end
values = {
"module" => module_name,
"classes" => res1,
'classes_title' => CGI.escapeHTML("Classes"),
'defines_title' => CGI.escapeHTML("Defines"),
'facts_title' => CGI.escapeHTML("Custom Facts"),
'plugins_title' => CGI.escapeHTML("Plugins"),
'nodes_title' => CGI.escapeHTML("Nodes"),
'index_url' => main_url,
'charset' => @options.charset,
'style_url' => style_url('', @options.css),
}
values["defines"] = res2 if res2.size > 0
values["facts"] = res3 if res3.size > 0
values["plugins"] = res4 if res4.size > 0
values["nodes"] = res5 if res5.size > 0
Puppet::FileSystem.open(filename, nil, "w:UTF-8") do |f|
template.write_html_on(f, values)
end
end
# returns the initial_page url
def main_url
main_page = @options.main_page
ref = nil
if main_page
ref = AllReferences[main_page]
if ref
ref = ref.path
else
$stderr.puts "Could not find main page #{main_page}"
end
end
unless ref
@files.each do |file|
if file.document_self and file.context.global
ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html")
break
end
end
end
unless ref
@files.each do |file|
if file.document_self and !file.context.global
ref = CGI.escapeHTML("#{CLASS_DIR}/#{file.context.module_name}.html")
break
end
end
end
unless ref
$stderr.puts "Couldn't find anything to document"
$stderr.puts "Perhaps you've used :stopdoc: in all classes"
exit(1)
end
ref
end
end
# This module is used to generate a referenced full name list of ContextUser
module ReferencedListBuilder
def build_referenced_list(list)
res = []
list.each do |i|
ref = AllReferences[i.name] || @context.find_symbol(i.name)
ref = ref.viewer if ref and ref.respond_to?(:viewer)
name = i.respond_to?(:full_name) ? i.full_name : i.name
h_name = CGI.escapeHTML(name)
if ref and ref.document_self
path = url(ref.path)
res << { "name" => h_name, "aref" => path }
else
res << { "name" => h_name }
end
end
res
end
end
# This module is used to hold/generate a list of puppet resources
# this is used in HTMLPuppetClass and HTMLPuppetNode
module ResourceContainer
def collect_resources
list = @context.resource_list
@resources = list.collect { |m| HTMLPuppetResource.new(m, self, @options) }
end
def build_resource_summary_list(path_prefix = '')
collect_resources unless @resources
resources = @resources.sort
res = []
resources.each do |r|
res << {
"name" => CGI.escapeHTML(r.name),
"aref" => Puppet::Util.uri_encode(path_prefix) + "\#" + Puppet::Util.uri_query_encode(r.aref)
}
end
res
end
def build_resource_detail_list(section)
outer = []
resources = @resources.sort
resources.each do |r|
row = {}
next unless r.section == section and r.document_self
row["name"] = CGI.escapeHTML(r.name)
desc = r.description.strip
row["m_desc"] = desc unless desc.empty?
row["aref"] = r.aref
row["params"] = r.params
outer << row
end
outer
end
end
class HTMLPuppetClass < HtmlClass
include ResourceContainer, ReferencedListBuilder
def value_hash
super
rl = build_resource_summary_list
@values["resources"] = rl unless rl.empty?
@context.sections.each do |section|
secdata = @values["sections"].select { |s| s["secsequence"] == section.sequence }
next unless secdata.size == 1
secdata = secdata[0]
rdl = build_resource_detail_list(section)
secdata["resource_list"] = rdl unless rdl.empty?
end
rl = build_require_list(@context)
@values["requires"] = rl unless rl.empty?
rl = build_realize_list(@context)
@values["realizes"] = rl unless rl.empty?
cl = build_child_list(@context)
@values["childs"] = cl unless cl.empty?
@values
end
def build_require_list(context)
build_referenced_list(context.requires)
end
def build_realize_list(context)
build_referenced_list(context.realizes)
end
def build_child_list(context)
build_referenced_list(context.childs)
end
end
class HTMLPuppetNode < ContextUser
include ResourceContainer, ReferencedListBuilder
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@html_file = html_file
@is_module = context.is_module?
@values = {}
context.viewer = self
if options.all_one_file
@path = context.full_name
else
@path = http_url(context.full_name, prefix)
end
AllReferences.add("NODE(#{@context.full_name})", self)
end
def name
@context.name
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
path.gsub!(/<<\s*(\w*)/) { "from-#{::Regexp.last_match(1)}" } if path['<<']
File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html"
end
def parent_name
@context.parent.full_name
end
def index_name
name
end
def write_on(f)
value_hash
template = TemplatePage.new(
RDoc::Page::BODYINC,
RDoc::Page::NODE_PAGE,
RDoc::Page::METHOD_LIST
)
template.write_html_on(f, @values)
end
def value_hash
class_attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
d = markup(@context.comment)
@values["description"] = d unless d.empty?
ml = build_method_summary_list
@values["methods"] = ml unless ml.empty?
rl = build_resource_summary_list
@values["resources"] = rl unless rl.empty?
il = build_include_list(@context)
@values["includes"] = il unless il.empty?
rl = build_require_list(@context)
@values["requires"] = rl unless rl.empty?
rl = build_realize_list(@context)
@values["realizes"] = rl unless rl.empty?
cl = build_child_list(@context)
@values["childs"] = cl unless cl.empty?
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
al = build_alias_summary_list(section)
secdata["aliases"] = al unless al.empty?
co = build_constants_summary_list(section)
secdata["constants"] = co unless co.empty?
al = build_attribute_list(section)
secdata["attributes"] = al unless al.empty?
cl = build_class_list(0, @context, section)
secdata["classlist"] = cl unless cl.empty?
mdl = build_method_detail_list(section)
secdata["method_list"] = mdl unless mdl.empty?
rdl = build_resource_detail_list(section)
secdata["resource_list"] = rdl unless rdl.empty?
secdata
end
@values
end
def build_attribute_list(section)
atts = @context.attributes.sort
res = []
atts.each do |att|
next unless att.section == section
next unless att.visibility == :public || att.visibility == :protected || @options.show_all
entry = {
"name" => CGI.escapeHTML(att.name),
"rw" => att.rw,
"a_desc" => markup(att.comment, true)
}
unless att.visibility == :public || att.visibility == :protected
entry["rw"] << "-"
end
res << entry
end
res
end
def class_attribute_values
h_name = CGI.escapeHTML(name)
@values["classmod"] = "Node"
@values["title"] = CGI.escapeHTML("#{@values['classmod']}: #{h_name}")
c = @context
c = c.parent while c and !c.diagram
@values["diagram"] = diagram_reference(c.diagram) if c && c.diagram
@values["full_name"] = h_name
parent_class = @context.superclass
if parent_class
@values["parent"] = CGI.escapeHTML(parent_class)
if parent_name
lookup = parent_name + "::#{parent_class}"
else
lookup = parent_class
end
lookup = "NODE(#{lookup})"
parent_url = AllReferences[lookup] || AllReferences[parent_class]
@values["par_url"] = aref_to(parent_url.path) if parent_url and parent_url.document_self
end
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = aref_to(f.viewer.path) if f.document_self
res["cvsurl"] = cvs_url(@options.webcvs, full_path) if @options.webcvs
files << res
end
@values['infiles'] = files
end
def build_require_list(context)
build_referenced_list(context.requires)
end
def build_realize_list(context)
build_referenced_list(context.realizes)
end
def build_child_list(context)
build_referenced_list(context.childs)
end
def <=>(other)
name <=> other.name
end
end
class HTMLPuppetModule < HtmlClass
def value_hash
@values = super
fl = build_facts_summary_list
@values["facts"] = fl unless fl.empty?
pl = build_plugins_summary_list
@values["plugins"] = pl unless pl.empty?
nl = build_nodes_list(0, @context)
@values["nodelist"] = nl unless nl.empty?
@values
end
def build_nodes_list(level, context)
res = ""
prefix = " ::" * level;
context.nodes.sort.each do |node|
next unless node.document_self
res <<
prefix <<
"Node " <<
href(url(node.viewer.path), "link", node.full_name) <<
"<br />\n"
end
res
end
def build_facts_summary_list
potentially_referenced_list(context.facts) { |fn| ["PLUGIN(#{fn})"] }
end
def build_plugins_summary_list
potentially_referenced_list(context.plugins) { |fn| ["PLUGIN(#{fn})"] }
end
def facts
@context.facts
end
def plugins
@context.plugins
end
end
class HTMLPuppetPlugin < ContextUser
attr_reader :path
def initialize(context, html_file, prefix, options)
super(context, options)
@html_file = html_file
@is_module = false
@values = {}
context.viewer = self
if options.all_one_file
@path = context.full_name
else
@path = http_url(context.full_name, prefix)
end
AllReferences.add("PLUGIN(#{@context.full_name})", self)
end
def name
@context.name
end
# return the relative file name to store this class in,
# which is also its url
def http_url(full_name, prefix)
path = full_name.dup
path.gsub!(/<<\s*(\w*)/) { "from-#{::Regexp.last_match(1)}" } if path['<<']
File.join(prefix, path.split("::")) + ".html"
end
def parent_name
@context.parent.full_name
end
def index_name
name
end
def write_on(f)
value_hash
template = TemplatePage.new(
RDoc::Page::BODYINC,
RDoc::Page::PLUGIN_PAGE,
RDoc::Page::PLUGIN_LIST
)
template.write_html_on(f, @values)
end
def value_hash
attribute_values
add_table_of_sections
@values["charset"] = @options.charset
@values["style_url"] = style_url(path, @options.css)
d = markup(@context.comment)
@values["description"] = d unless d.empty?
if context.is_fact?
unless context.confine.empty?
res = {}
res["type"] = context.confine[:type]
res["value"] = context.confine[:value]
@values["confine"] = [res]
end
else
@values["type"] = context.type
end
@values["sections"] = @context.sections.map do |section|
secdata = {
"sectitle" => section.title,
"secsequence" => section.sequence,
"seccomment" => markup(section.comment)
}
secdata
end
@values
end
def attribute_values
h_name = CGI.escapeHTML(name)
if @context.is_fact?
@values["classmod"] = "Fact"
else
@values["classmod"] = "Plugin"
end
@values["title"] = "#{@values['classmod']}: #{h_name}"
@values["full_name"] = h_name
files = []
@context.in_files.each do |f|
res = {}
full_path = CGI.escapeHTML(f.file_absolute_name)
res["full_path"] = full_path
res["full_path_url"] = aref_to(f.viewer.path) if f.document_self
res["cvsurl"] = cvs_url(@options.webcvs, full_path) if @options.webcvs
files << res
end
@values['infiles'] = files
end
def <=>(other)
name <=> other.name
end
end
class HTMLPuppetResource
include MarkUp
attr_reader :context
@@seq = "R000000"
def initialize(context, html_class, options)
@context = context
@html_class = html_class
@options = options
@@seq = @@seq.succ
@seq = @@seq
context.viewer = self
AllReferences.add(name, self)
end
def as_href(from_path)
if @options.all_one_file
"##{path}"
else
HTMLGenerator.gen_url(from_path, path)
end
end
def name
@context.name
end
def section
@context.section
end
def index_name
@context.name.to_s
end
def params
@context.params
end
def parent_name
if @context.parent.parent
@context.parent.parent.full_name
else
nil
end
end
def aref
@seq
end
def path
if @options.all_one_file
aref
else
@html_class.path + "##{aref}"
end
end
def description
markup(@context.comment)
end
def <=>(other)
@context <=> other.context
end
def document_self
@context.document_self
end
def find_symbol(symbol, method = nil)
res = @context.parent.find_symbol(symbol, method)
res && res.viewer
end
end
class PuppetGeneratorInOne < HTMLGeneratorInOne
def gen_method_index
gen_an_index(HtmlMethod.all_methods, 'Defines')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/generators/template/puppet/puppet.rb | lib/puppet/util/rdoc/generators/template/puppet/puppet.rb | # frozen_string_literal: true
#
# = CSS2 RDoc HTML template
#
# This is a template for RDoc that uses XHTML 1.0 Transitional and dictates a
# bit more of the appearance of the output to cascading stylesheets than the
# default. It was designed for clean inline code display, and uses DHTMl to
# toggle the visbility of each method's source with each click on the '[source]'
# link.
#
# == Authors
#
# * Michael Granger <ged@FaerieMUD.org>
#
# Copyright (c) 2002, 2003 The FaerieMUD Consortium. Some rights reserved.
#
# This work is licensed under the Creative Commons Attribution License. To view
# a copy of this license, visit http://creativecommons.org/licenses/by/1.0/ or
# send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California
# 94305, USA.
#
module RDoc
module Page
FONTS = "Verdana,Arial,Helvetica,sans-serif"
STYLE = %(
/* Reset */
html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit;vertical-align:baseline;}
:focus{outline:0;}
body{line-height:1;color:#282828;background:#fff;}
ol,ul{list-style:none;}
table{border-collapse:separate;border-spacing:0;}
caption,th,td{text-align:left;font-weight:normal;}
blockquote:before,blockquote:after,q:before,q:after{content:"";}
blockquote,q{quotes:"""";}
body {
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 0.9em;
}
pre {
background: none repeat scroll 0 0 #F7F7F7;
border: 1px dashed #DDDDDD;
color: #555555;
font-family: courier;
margin: 10px 19px;
padding: 10px;
}
h1,h2,h3,h4 { margin: 0; color: #efefef; background: transparent; }
h1 { font-size: 1.2em; }
h2,h3,h4 { margin-top: 1em; color:#558; }
h2,h3 { font-size: 1.1em; }
a { color: #037; text-decoration: none; }
a:hover { color: #04d; }
/* Override the base stylesheet's Anchor inside a table cell */
td > a {
background: transparent;
color: #039;
text-decoration: none;
}
/* and inside a section title */
.section-title > a {
background: transparent;
color: #eee;
text-decoration: none;
}
/* === Structural elements =================================== */
div#index {
padding: 0;
}
div#index a {
display:inline-block;
padding:2px 10px;
}
div#index .section-bar {
background: #ffe;
padding:10px;
}
div#classHeader, div#fileHeader {
border-bottom: 1px solid #ddd;
padding:10px;
font-size:0.9em;
}
div#classHeader a, div#fileHeader a {
background: inherit;
color: white;
}
div#classHeader td, div#fileHeader td {
color: white;
padding:3px;
font-size:0.9em;
}
div#fileHeader {
background: #057;
}
div#classHeader {
background: #048;
}
div#nodeHeader {
background: #7f7f7f;
}
.class-name-in-header {
font-weight: bold;
}
div#bodyContent {
padding: 10px;
}
div#description {
padding: 10px;
background: #f5f5f5;
border: 1px dotted #ddd;
line-height:1.2em;
}
div#description h1,h2,h3,h4,h5,h6 {
color: #125;;
background: transparent;
}
div#validator-badges {
text-align: center;
}
div#validator-badges img { border: 0; }
div#copyright {
color: #333;
background: #efefef;
font: 0.75em sans-serif;
margin-top: 5em;
margin-bottom: 0;
padding: 0.5em 2em;
}
/* === Classes =================================== */
table.header-table {
color: white;
font-size: small;
}
.type-note {
font-size: small;
color: #DEDEDE;
}
.xxsection-bar {
background: #eee;
color: #333;
padding: 3px;
}
.section-bar {
color: #333;
border-bottom: 1px solid #ddd;
padding:10px 0;
margin:5px 0 10px 0;
}
div#class-list, div#methods, div#includes, div#resources, div#requires, div#realizes, div#attribute-list { padding:10px; }
.section-title {
background: #79a;
color: #eee;
padding: 3px;
margin-top: 2em;
border: 1px solid #999;
}
.top-aligned-row { vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }
/* --- Context section classes ----------------------- */
.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { font-size: small; color: #448; }
.context-item-desc { color: #333; padding-left: 2em; }
/* --- Method classes -------------------------- */
.method-detail {
background: #f5f5f5;
}
.method-heading {
color: #333;
font-style:italic;
background: #ddd;
padding:5px 10px;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 10px 10px 20px 10px; }
/* --- Source code sections -------------------- */
a.source-toggle { font-size: 90%; }
div.method-source-code {
background: #262626;
color: #ffdead;
margin: 1em;
padding: 0.5em;
border: 1px dashed #999;
overflow: hidden;
}
div.method-source-code pre { color: #ffdead; overflow: hidden; }
/* --- Ruby keyword styles --------------------- */
.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }
.ruby-constant { color: #7fffd4; background: transparent; }
.ruby-keyword { color: #00ffff; background: transparent; }
.ruby-ivar { color: #eedd82; background: transparent; }
.ruby-operator { color: #00ffee; background: transparent; }
.ruby-identifier { color: #ffdead; background: transparent; }
.ruby-node { color: #ffa07a; background: transparent; }
.ruby-comment { color: #b22222; font-weight: bold; background: transparent; }
.ruby-regexp { color: #ffa07a; background: transparent; }
.ruby-value { color: #7fffd4; background: transparent; }
)
#####################################################################
### H E A D E R T E M P L A T E
#####################################################################
XHTML_PREAMBLE = %(<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
)
HEADER = XHTML_PREAMBLE + %{
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\\"text/css\\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
}
#####################################################################
### C O N T E X T C O N T E N T T E M P L A T E
#####################################################################
CONTEXT_CONTENT = %(
)
#####################################################################
### F O O T E R T E M P L A T E
#####################################################################
FOOTER = %(
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
)
#####################################################################
### F I L E P A G E H E A D E R T E M P L A T E
#####################################################################
FILE_PAGE = %{
<div id="fileHeader">
<h1>%short_name%</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>%full_path%
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>%dtm_modified%</td>
</tr>
</table>
</div>
}
#####################################################################
### C L A S S P A G E H E A D E R T E M P L A T E
#####################################################################
CLASS_PAGE = %{
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
IF:par_url
<a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</div>
}
NODE_PAGE = %{
<div id="nodeHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
IF:parent
<tr class="top-aligned-row">
<td><strong>Parent:</strong></td>
<td>
IF:par_url
<a href="%par_url%">
ENDIF:par_url
%parent%
IF:par_url
</a>
ENDIF:par_url
</td>
</tr>
ENDIF:parent
</table>
</div>
}
PLUGIN_PAGE = %{
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>%classmod%</strong></td>
<td class="class-name-in-header">%full_name%</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
START:infiles
IF:full_path_url
<a href="%full_path_url%">
ENDIF:full_path_url
%full_path%
IF:full_path_url
</a>
ENDIF:full_path_url
IF:cvsurl
(<a href="%cvsurl%"><acronym title="Concurrent Versioning System">CVS</acronym></a>)
ENDIF:cvsurl
<br />
END:infiles
</td>
</tr>
</table>
</div>
}
#####################################################################
### M E T H O D L I S T T E M P L A T E
#####################################################################
PLUGIN_LIST = %(
<div id="contextContent">
IF:description
<div id="description">
%description%
</div>
ENDIF:description
IF:toc
<div id="contents-list">
<h3 class="section-bar">Contents</h3>
<ul>
START:toc
<li><a href="#%href%">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
</div>
</div>
<!-- Confine -->
IF:confine
START:confine
<div id="attribute-list">
<h3 class="section-bar">Confine</h3>
%type% %value%
<div class="name-list">
</div>
</div>
END:confine
ENDIF:confine
<!-- Type -->
IF:type
<div id="attribute-list">
<h3 class="section-bar">Type</h3>
%type%
<div class="name-list">
</div>
</div>
ENDIF:type
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
END:sections
)
METHOD_LIST = %{
<div id="contextContent">
IF:diagram
<div id="diagram">
%diagram%
</div>
ENDIF:diagram
IF:description
<div id="description">
%description%
</div>
ENDIF:description
IF:toc
<div id="contents-list">
<h3 class="section-bar">Contents</h3>
<ul>
START:toc
<li><a href="#%href%">%secname%</a></li>
END:toc
</ul>
ENDIF:toc
</div>
<!-- if childs -->
IF:childs
<div id="childs">
<h3 class="section-bar">Inherited by</h3>
<div id="childs-list">
START:childs
<span class="child-name">HREF:aref:name:</span>
END:childs
</div>
</div>
ENDIF:childs
IF:methods
<div id="method-list">
<h3 class="section-bar">Defines</h3>
<div class="name-list">
START:methods
HREF:aref:name:
END:methods
</div>
</div>
ENDIF:methods
IF:resources
<div id="method-list">
<h3 class="section-bar">Resources</h3>
<div class="name-list">
START:resources
HREF:aref:name:
END:resources
</div>
</div>
ENDIF:resources
</div>
<!-- if includes -->
IF:includes
<div id="includes">
<h3 class="section-bar">Included Classes</h3>
<div id="includes-list">
START:includes
<span class="include-name">HREF:aref:name:</span>
END:includes
</div>
</div>
ENDIF:includes
<!-- if requires -->
IF:requires
<div id="requires">
<h3 class="section-bar">Required Classes</h3>
<div id="requires-list">
START:requires
<span class="require-name">HREF:aref:name:</span>
END:requires
</div>
</div>
ENDIF:requires
<!-- if realizes -->
IF:realizes
<div id="realizes">
<h3 class="section-bar">Realized Resources</h3>
<div id="realizes-list">
START:realizes
<span class="realizes-name">HREF:aref:name:</span>
END:realizes
</div>
</div>
ENDIF:realizes
START:sections
<div id="section">
IF:sectitle
<h2 class="section-title"><a name="%secsequence%">%sectitle%</a></h2>
IF:seccomment
<div class="section-comment">
%seccomment%
</div>
ENDIF:seccomment
ENDIF:sectitle
<!-- if facts -->
IF:facts
<div id="class-list">
<h3 class="section-bar">Custom Facts</h3>
START:facts
HREF:aref:name:
END:facts
</div>
ENDIF:facts
<!-- if plugins -->
IF:plugins
<div id="class-list">
<h3 class="section-bar">Plugins</h3>
START:plugins
HREF:aref:name:
END:plugins
</div>
ENDIF:plugins
<!-- if nodes -->
IF:nodelist
<div id="class-list">
<h3 class="section-bar">Nodes</h3>
%nodelist%
</div>
ENDIF:nodelist
<!-- if class -->
IF:classlist
<div id="class-list">
<h3 class="section-bar">Classes and Modules</h3>
%classlist%
</div>
ENDIF:classlist
IF:constants
<div id="constants-list">
<h3 class="section-bar">Global Variables</h3>
<div class="name-list">
<table summary="Variables">
START:constants
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
<td>=</td>
<td class="context-item-value">%value%</td>
IF:desc
<td width="3em"> </td>
<td class="context-item-desc">%desc%</td>
ENDIF:desc
</tr>
END:constants
</table>
</div>
</div>
ENDIF:constants
IF:aliases
<div id="aliases-list">
<h3 class="section-bar">External Aliases</h3>
<div class="name-list">
<table summary="aliases">
START:aliases
<tr class="top-aligned-row context-row">
<td class="context-item-name">%old_name%</td>
<td>-></td>
<td class="context-item-value">%new_name%</td>
</tr>
IF:desc
<tr class="top-aligned-row context-row">
<td> </td>
<td colspan="2" class="context-item-desc">%desc%</td>
</tr>
ENDIF:desc
END:aliases
</table>
</div>
</div>
ENDIF:aliases
IF:attributes
<div id="attribute-list">
<h3 class="section-bar">Attributes</h3>
<div class="name-list">
<table>
START:attributes
<tr class="top-aligned-row context-row">
<td class="context-item-name">%name%</td>
IF:rw
<td class="context-item-value"> [%rw%] </td>
ENDIF:rw
IFNOT:rw
<td class="context-item-value"> </td>
ENDIF:rw
<td class="context-item-desc">%a_desc%</td>
</tr>
END:attributes
</table>
</div>
</div>
ENDIF:attributes
<!-- if method_list -->
IF:method_list
<div id="methods">
START:method_list
IF:methods
<h3 class="section-bar">Defines</h3>
START:methods
<div id="method-%aref%" class="method-detail">
<a name="%aref%"></a>
<div class="method-heading">
IF:codeurl
<a href="%codeurl%" target="Code" class="method-signature"
onclick="popupCode('%codeurl%');return false;">
ENDIF:codeurl
IF:sourcecode
<a href="#%aref%" class="method-signature">
ENDIF:sourcecode
IF:callseq
<span class="method-name">%callseq%</span>
ENDIF:callseq
IFNOT:callseq
<span class="method-name">%name%</span><span class="method-args">%params%</span>
ENDIF:callseq
IF:codeurl
</a>
ENDIF:codeurl
IF:sourcecode
</a>
ENDIF:sourcecode
</div>
<div class="method-description">
IF:m_desc
%m_desc%
ENDIF:m_desc
IF:sourcecode
<p><a class="source-toggle" href="#"
onclick="toggleCode('%aref%-source');return false;">[Source]</a></p>
<div class="method-source-code" id="%aref%-source">
<pre>
%sourcecode%
</pre>
</div>
ENDIF:sourcecode
</div>
</div>
END:methods
ENDIF:methods
END:method_list
</div>
ENDIF:method_list
<!-- if resource_list -->
IF:resource_list
<div id="resources">
<h3 class="section-bar">Resources</h3>
START:resource_list
<div id="method-%aref%" class="method-detail">
<a name="%aref%"></a>
<div class="method-heading">
<span class="method-name">%name%</span><br />
IF:params
START:params
<span class="method-args">%name% => %value%</span><br />
END:params
ENDIF:params
</div>
<div class="method-description">
IF:m_desc
%m_desc%
ENDIF:m_desc
</div>
</div>
END:resource_list
</div>
ENDIF:resource_list
END:sections
}
#####################################################################
### B O D Y T E M P L A T E
#####################################################################
BODY = HEADER + %(
!INCLUDE! <!-- banner header -->
<div id="bodyContent">
) + METHOD_LIST + %(
</div>
) + FOOTER
BODYINC = HEADER + %(
!INCLUDE! <!-- banner header -->
<div id="bodyContent">
!INCLUDE!
</div>
) + FOOTER
#####################################################################
### S O U R C E C O D E T E M P L A T E
#####################################################################
SRC_PAGE = XHTML_PREAMBLE + %(
<html>
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre>%code%</pre>
</body>
</html>
)
#####################################################################
### I N D E X F I L E T E M P L A T E S
#####################################################################
FR_INDEX_BODY = %(
!INCLUDE!
)
FILE_INDEX = XHTML_PREAMBLE + %(
<!--
%list_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%list_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" />
<base target="docwin" />
</head>
<body>
<div id="index">
<h1 class="section-bar">%list_title%</h1>
<div id="index-entries">
START:entries
<a href="%href%">%name%</a><br />
END:entries
</div>
</div>
</body>
</html>
)
TOP_INDEX = XHTML_PREAMBLE + %{
<!--
%list_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%list_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="%style_url%" type="text/css" />
<base target="classes" />
<SCRIPT LANGUAGE="JavaScript">
<!--
function load(classlist,module) {
parent.classes.location.href = classlist;
parent.docwin.location.href = module;
}
//--></SCRIPT>
</head>
<body>
<div id="index">
<h1 class="section-bar">%list_title%</h1>
<div id="index-entries">
START:entries
<a href="%classlist%" onclick="load('%classlist%','%module%'); return true;">%name%</a><br />
END:entries
</div>
</div>
</body>
</html>
}
CLASS_INDEX = FILE_INDEX
METHOD_INDEX = FILE_INDEX
COMBO_INDEX = XHTML_PREAMBLE + %{
<!--
%classes_title% & %defines_title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%classes_title% & %defines_title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
<link rel="stylesheet" href="../%style_url%" type="text/css" />
<base target="docwin" />
<SCRIPT LANGUAGE="JavaScript">
<!--
function load(url) {
parent.docwin.location.href = url;
}
//--></SCRIPT>
</head>
<body>
<div id="index">
<a href="../fr_class_index.html" target="classes">All Classes</a><br />
<h1 class="section-bar">Module</h1>
<div id="index-entries">
START:module
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:module
</div>
</div>
<div id="index">
IF:nodes
<h1 class="section-bar">%nodes_title%</h1>
<div id="index-entries">
START:nodes
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:nodes
</div>
ENDIF:nodes
IF:classes
<h1 class="section-bar">%classes_title%</h1>
<div id="index-entries">
START:classes
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:classes
</div>
ENDIF:classes
IF:defines
<h1 class="section-bar">%defines_title%</h1>
<div id="index-entries">
START:defines
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:defines
</div>
ENDIF:defines
IF:facts
<h1 class="section-bar">%facts_title%</h1>
<div id="index-entries">
START:facts
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:facts
</div>
ENDIF:facts
IF:plugins
<h1 class="section-bar">%plugins_title%</h1>
<div id="index-entries">
START:plugins
<a href="%href%" onclick="load('%href%'); return true;">%name%</a><br />
END:plugins
</div>
ENDIF:plugins
</div>
</body>
</html>
}
INDEX = %(<?xml version="1.0" encoding="%charset%"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<!--
%title%
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>%title%</title>
<meta http-equiv="Content-Type" content="text/html; charset=%charset%" />
</head>
<frameset cols="20%, 80%">
<frameset rows="30%,70%">
<frame src="fr_modules_index.html" title="All Modules" />
<frame src="fr_class_index.html" name="classes" title="Classes & Defines" />
</frameset>
<frame src="%initial_page%" name="docwin" />
</frameset>
</html>
)
end # module Page
end # class RDoc
require 'rdoc/generators/template/html/one_page_html'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/parser/puppet_parser_rdoc2.rb | lib/puppet/util/rdoc/parser/puppet_parser_rdoc2.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/rdoc/parser/puppet_parser_core'
module RDoc
PUPPET_RDOC_VERSION = 2
# @api private
class PuppetParserRDoc2 < Parser
include PuppetParserCore
def create_rdoc_preprocess
Markup::PreProcess.new(@input_file_name, @options.rdoc_include)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/rdoc/parser/puppet_parser_core.rb | lib/puppet/util/rdoc/parser/puppet_parser_core.rb | # frozen_string_literal: true
# Functionality common to both our RDoc version 1 and 2 parsers.
module RDoc::PuppetParserCore
SITE = "__site__"
def self.included(base)
base.class_eval do
attr_accessor :input_file_name, :top_level
# parser registration into RDoc
parse_files_matching(/\.(rb)$/)
end
end
# called with the top level file
def initialize(top_level, file_name, body, options, stats)
@options = options
@stats = stats
@input_file_name = file_name
@top_level = top_level
@top_level.extend(RDoc::PuppetTopLevel)
@progress = $stderr unless options.quiet
end
# main entry point
def scan
environment = Puppet.lookup(:current_environment)
scan_top_level(@top_level, environment)
@top_level
end
# Due to a bug in RDoc, we need to roll our own find_module_named
# The issue is that RDoc tries harder by asking the parent for a class/module
# of the name. But by doing so, it can mistakenly use a module of same name
# but from which we are not descendant.
def find_object_named(container, name)
return container if container.name == name
container.each_classmodule do |m|
return m if m.name == name
end
nil
end
# walk down the namespace and lookup/create container as needed
def get_class_or_module(container, name)
# class ::A -> A is in the top level
if name =~ /^::/
container = @top_level
end
names = name.split('::')
final_name = names.pop
names.each do |n|
prev_container = container
container = find_object_named(container, n)
container ||= prev_container.add_class(RDoc::PuppetClass, n, nil)
end
[container, final_name]
end
# split_module tries to find if +path+ belongs to the module path
# if it does, it returns the module name, otherwise if we are sure
# it is part of the global manifest path, "__site__" is returned.
# And finally if this path couldn't be mapped anywhere, nil is returned.
def split_module(path, environment)
# find a module
fullpath = File.expand_path(path)
Puppet.debug "rdoc: testing #{fullpath}"
if fullpath =~ %r{(.*)/([^/]+)/(?:manifests|plugins|lib)/.+\.(rb)$}
modpath = ::Regexp.last_match(1)
name = ::Regexp.last_match(2)
Puppet.debug "rdoc: module #{name} into #{modpath} ?"
environment.modulepath.each do |mp|
if File.identical?(modpath, mp)
Puppet.debug "rdoc: found module #{name}"
return name
end
end
end
if fullpath =~ /\.(rb)$/
# there can be paths we don't want to scan under modules
# imagine a ruby or manifest that would be distributed as part as a module
# but we don't want those to be hosted under <site>
environment.modulepath.each do |mp|
# check that fullpath is a descendant of mp
dirname = fullpath
previous = dirname
while (dirname = File.dirname(previous)) != previous
previous = dirname
return nil if File.identical?(dirname, mp)
end
end
end
# we are under a global manifests
Puppet.debug "rdoc: global manifests"
SITE
end
# create documentation for the top level +container+
def scan_top_level(container, environment)
# use the module README as documentation for the module
comment = ""
%w[README README.rdoc].each do |rfile|
readme = File.join(File.dirname(File.dirname(@input_file_name)), rfile)
# module README should be UTF-8, not default system encoding
comment = File.open(readme, "r:UTF-8", &:read) if FileTest.readable?(readme)
end
look_for_directives_in(container, comment) unless comment.empty?
# infer module name from directory
name = split_module(@input_file_name, environment)
if name.nil?
# skip .pp files that are not in manifests directories as we can't guarantee they're part
# of a module or the global configuration.
# PUP-3638, keeping this while it should have no effect since no .pp files are now processed
container.document_self = false
return
end
Puppet.debug "rdoc: scanning for #{name}"
container.module_name = name
container.global = true if name == SITE
container, name = get_class_or_module(container, name)
mod = container.add_module(RDoc::PuppetModule, name)
mod.record_location(@top_level)
mod.add_comment(comment, @top_level)
if @input_file_name =~ /\.rb$/
parse_plugins(mod)
end
end
# create documentation for plugins
def parse_plugins(container)
Puppet.debug "rdoc: scanning plugin or fact"
if @input_file_name =~ %r{/facter/[^/]+\.rb$}
parse_fact(container)
else
parse_puppet_plugin(container)
end
end
# this is a poor man custom fact parser :-)
def parse_fact(container)
comments = ""
current_fact = nil
parsed_facts = []
File.open(@input_file_name) do |of|
of.each do |line|
# fetch comments
case line
when /^[ \t]*# ?(.*)$/
comments += ::Regexp.last_match(1) + "\n"
when /^[ \t]*(Facter.add|Puppet\.runtime\[:facter\].add)\(['"](.*?)['"]\)/
current_fact = RDoc::Fact.new(::Regexp.last_match(1), {})
look_for_directives_in(container, comments) unless comments.empty?
current_fact.comment = comments
parsed_facts << current_fact
comments = ""
Puppet.debug "rdoc: found custom fact #{current_fact.name}"
when /^[ \t]*confine[ \t]*:(.*?)[ \t]*=>[ \t]*(.*)$/
current_fact.confine = { :type => ::Regexp.last_match(1), :value => ::Regexp.last_match(2) } unless current_fact.nil?
else # unknown line type
comments = ""
end
end
end
parsed_facts.each do |f|
container.add_fact(f)
f.record_location(@top_level)
end
end
# this is a poor man puppet plugin parser :-)
# it doesn't extract doc nor desc :-(
def parse_puppet_plugin(container)
comments = ""
current_plugin = nil
File.open(@input_file_name) do |of|
of.each do |line|
# fetch comments
case line
when /^[ \t]*# ?(.*)$/
comments += ::Regexp.last_match(1) + "\n"
when /^[ \t]*(?:Puppet::Parser::Functions::)?newfunction[ \t]*\([ \t]*:(.*?)[ \t]*,[ \t]*:type[ \t]*=>[ \t]*(:rvalue|:lvalue)/
current_plugin = RDoc::Plugin.new(::Regexp.last_match(1), "function")
look_for_directives_in(container, comments) unless comments.empty?
current_plugin.comment = comments
current_plugin.record_location(@top_level)
container.add_plugin(current_plugin)
comments = ""
Puppet.debug "rdoc: found new function plugins #{current_plugin.name}"
when /^[ \t]*Puppet::Type.newtype[ \t]*\([ \t]*:(.*?)\)/
current_plugin = RDoc::Plugin.new(::Regexp.last_match(1), "type")
look_for_directives_in(container, comments) unless comments.empty?
current_plugin.comment = comments
current_plugin.record_location(@top_level)
container.add_plugin(current_plugin)
comments = ""
Puppet.debug "rdoc: found new type plugins #{current_plugin.name}"
when /module Puppet::Parser::Functions/
# skip
else # unknown line type
comments = ""
end
end
end
end
# New instance of the appropriate PreProcess for our RDoc version.
def create_rdoc_preprocess
raise(NotImplementedError, "This method must be overwritten for whichever version of RDoc this parser is working with")
end
# look_for_directives_in scans the current +comment+ for RDoc directives
def look_for_directives_in(context, comment)
preprocess = create_rdoc_preprocess
preprocess.handle(comment) do |directive, param|
case directive
when "stopdoc"
context.stop_doc
""
when "startdoc"
context.start_doc
context.force_documentation = true
""
when "enddoc"
# context.done_documenting = true
# ""
throw :enddoc
when "main"
options = Options.instance
options.main_page = param
""
when "title"
options = Options.instance
options.title = param
""
when "section"
context.set_current_section(param, comment)
comment.replace("") # 1.8 doesn't support #clear
break
else
warn "Unrecognized directive '#{directive}'"
break
end
end
remove_private_comments(comment)
end
def remove_private_comments(comment)
comment.gsub!(/^#--.*?^#\+\+/m, '')
comment.sub!(/^#--.*/m, '')
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/security_descriptor.rb | lib/puppet/util/windows/security_descriptor.rb | # frozen_string_literal: true
# Windows Security Descriptor
#
# Represents a security descriptor that can be applied to any Windows securable
# object, e.g. file, registry key, service, etc. It consists of an owner, group,
# flags, DACL, and SACL. The SACL is not currently supported, though it has the
# same layout as a DACL.
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa379563(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::SecurityDescriptor
require_relative '../../../puppet/util/windows/security'
include Puppet::Util::Windows::SID
attr_reader :owner, :group, :dacl
attr_accessor :protect
# Construct a security descriptor
#
# @param owner [String] The SID of the owner, e.g. 'S-1-5-18'
# @param group [String] The SID of the group
# @param dacl [AccessControlList] The ACL specifying the rights granted to
# each user for accessing the object that the security descriptor refers to.
# @param protect [Boolean] If true, then inheritable access control
# entries will be blocked, and not applied to the object.
def initialize(owner, group, dacl, protect = false)
@owner = owner
@group = group
@dacl = dacl
@protect = protect
end
# Set the owner. Non-inherited access control entries assigned to the
# current owner will be assigned to the new owner.
#
# @param new_owner [String] The SID of the new owner, e.g. 'S-1-5-18'
def owner=(new_owner)
if @owner != new_owner
@dacl.reassign!(@owner, new_owner)
@owner = new_owner
end
end
# Set the group. Non-inherited access control entries assigned to the
# current group will be assigned to the new group.
#
# @param new_group [String] The SID of the new group, e.g. 'S-1-0-0'
def group=(new_group)
if @group != new_group
@dacl.reassign!(@group, new_group)
@group = new_group
end
end
def inspect
str = sid_to_name(owner)
str << "\n"
str << sid_to_name(group)
str << "\n"
str << @dacl.inspect
str
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/security.rb | lib/puppet/util/windows/security.rb | # frozen_string_literal: true
# This class maps POSIX owner, group, and modes to the Windows
# security model, and back.
#
# The primary goal of this mapping is to ensure that owner, group, and
# modes can be round-tripped in a consistent and deterministic
# way. Otherwise, Puppet might think file resources are out-of-sync
# every time it runs. A secondary goal is to provide equivalent
# permissions for common use-cases. For example, setting the owner to
# "Administrators", group to "Users", and mode to 750 (which also
# denies access to everyone else.
#
# There are some well-known problems mapping windows and POSIX
# permissions due to differences between the two security
# models. Search for "POSIX permission mapping leak". In POSIX, access
# to a file is determined solely based on the most specific class
# (user, group, other). So a mode of 460 would deny write access to
# the owner even if they are a member of the group. But in Windows,
# the entire access control list is walked until the user is
# explicitly denied or allowed (denied take precedence, and if neither
# occurs they are denied). As a result, a user could be allowed access
# based on their group membership. To solve this problem, other people
# have used deny access control entries to more closely model POSIX,
# but this introduces a lot of complexity.
#
# In general, this implementation only supports "typical" permissions,
# where group permissions are a subset of user, and other permissions
# are a subset of group, e.g. 754, but not 467. However, there are
# some Windows quirks to be aware of.
#
# * The owner can be either a user or group SID, and most system files
# are owned by the Administrators group.
# * The group can be either a user or group SID.
# * Unexpected results can occur if the owner and group are the
# same, but the user and group classes are different, e.g. 750. In
# this case, it is not possible to allow write access to the owner,
# but not the group. As a result, the actual permissions set on the
# file would be 770.
# * In general, only privileged users can set the owner, group, or
# change the mode for files they do not own. In 2003, the user must
# be a member of the Administrators group. In Vista/2008, the user
# must be running with elevated privileges.
# * A file/dir can be deleted by anyone with the DELETE access right
# OR by anyone that has the FILE_DELETE_CHILD access right for the
# parent. See https://support.microsoft.com/kb/238018. But on Unix,
# the user must have write access to the file/dir AND execute access
# to all of the parent path components.
# * Many access control entries are inherited from parent directories,
# and it is common for file/dirs to have more than 3 entries,
# e.g. Users, Power Users, Administrators, SYSTEM, etc, which cannot
# be mapped into the 3 class POSIX model. The get_mode method will
# set the S_IEXTRA bit flag indicating that an access control entry
# was found whose SID is neither the owner, group, or other. This
# enables Puppet to detect when file/dirs are out-of-sync,
# especially those that Puppet did not create, but is attempting
# to manage.
# * A special case of this is S_ISYSTEM_MISSING, which is set when the
# SYSTEM permissions are *not* present on the DACL.
# * On Unix, the owner and group can be modified without changing the
# mode. But on Windows, an access control entry specifies which SID
# it applies to. As a result, the set_owner and set_group methods
# automatically rebuild the access control list based on the new
# (and different) owner or group.
require_relative '../../../puppet/util/windows'
require 'pathname'
require 'ffi'
module Puppet::Util::Windows::Security
include Puppet::Util::Windows::String
extend Puppet::Util::Windows::Security
extend FFI::Library
# file modes
S_IRUSR = 0o000400
S_IRGRP = 0o000040
S_IROTH = 0o000004
S_IWUSR = 0o000200
S_IWGRP = 0o000020
S_IWOTH = 0o000002
S_IXUSR = 0o000100
S_IXGRP = 0o000010
S_IXOTH = 0o000001
S_IRWXU = 0o000700
S_IRWXG = 0o000070
S_IRWXO = 0o000007
S_ISVTX = 0o001000
S_IEXTRA = 0o2000000 # represents an extra ace
S_ISYSTEM_MISSING = 0o4000000
# constants that are missing from Windows::Security
PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000
NO_INHERITANCE = 0x0
SE_DACL_PROTECTED = 0x1000
FILE = Puppet::Util::Windows::File
SE_BACKUP_NAME = 'SeBackupPrivilege'
SE_DEBUG_NAME = 'SeDebugPrivilege'
SE_RESTORE_NAME = 'SeRestorePrivilege'
DELETE = 0x00010000
READ_CONTROL = 0x20000
WRITE_DAC = 0x40000
WRITE_OWNER = 0x80000
OWNER_SECURITY_INFORMATION = 1
GROUP_SECURITY_INFORMATION = 2
DACL_SECURITY_INFORMATION = 4
# Set the owner of the object referenced by +path+ to the specified
# +owner_sid+. The owner sid should be of the form "S-1-5-32-544"
# and can either be a user or group. Only a user with the
# SE_RESTORE_NAME privilege in their process token can overwrite the
# object's owner to something other than the current user.
def set_owner(owner_sid, path)
sd = get_security_descriptor(path)
if owner_sid != sd.owner
sd.owner = owner_sid
set_security_descriptor(path, sd)
end
end
# Get the owner of the object referenced by +path+. The returned
# value is a SID string, e.g. "S-1-5-32-544". Any user with read
# access to an object can get the owner. Only a user with the
# SE_BACKUP_NAME privilege in their process token can get the owner
# for objects they do not have read access to.
def get_owner(path)
return unless supports_acl?(path)
get_security_descriptor(path).owner
end
# Set the owner of the object referenced by +path+ to the specified
# +group_sid+. The group sid should be of the form "S-1-5-32-544"
# and can either be a user or group. Any user with WRITE_OWNER
# access to the object can change the group (regardless of whether
# the current user belongs to that group or not).
def set_group(group_sid, path)
sd = get_security_descriptor(path)
if group_sid != sd.group
sd.group = group_sid
set_security_descriptor(path, sd)
end
end
# Get the group of the object referenced by +path+. The returned
# value is a SID string, e.g. "S-1-5-32-544". Any user with read
# access to an object can get the group. Only a user with the
# SE_BACKUP_NAME privilege in their process token can get the group
# for objects they do not have read access to.
def get_group(path)
return unless supports_acl?(path)
get_security_descriptor(path).group
end
FILE_PERSISTENT_ACLS = 0x00000008
def supports_acl?(path)
supported = false
root = Pathname.new(path).enum_for(:ascend).to_a.last.to_s
# 'A trailing backslash is required'
root = "#{root}\\" unless root =~ %r{[/\\]$}
FFI::MemoryPointer.new(:pointer, 1) do |flags_ptr|
if GetVolumeInformationW(wide_string(root), FFI::Pointer::NULL, 0,
FFI::Pointer::NULL, FFI::Pointer::NULL,
flags_ptr, FFI::Pointer::NULL, 0) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get volume information")
end
supported = flags_ptr.read_dword & FILE_PERSISTENT_ACLS == FILE_PERSISTENT_ACLS
end
supported
end
MASK_TO_MODE = {
FILE::FILE_GENERIC_READ => S_IROTH,
FILE::FILE_GENERIC_WRITE => S_IWOTH,
(FILE::FILE_GENERIC_EXECUTE & ~FILE::FILE_READ_ATTRIBUTES) => S_IXOTH
}
def get_aces_for_path_by_sid(path, sid)
get_security_descriptor(path).dacl.select { |ace| ace.sid == sid }
end
# Get the mode of the object referenced by +path+. The returned
# integer value represents the POSIX-style read, write, and execute
# modes for the user, group, and other classes, e.g. 0640. Any user
# with read access to an object can get the mode. Only a user with
# the SE_BACKUP_NAME privilege in their process token can get the
# mode for objects they do not have read access to.
def get_mode(path)
return unless supports_acl?(path)
well_known_world_sid = Puppet::Util::Windows::SID::Everyone
well_known_nobody_sid = Puppet::Util::Windows::SID::Nobody
well_known_system_sid = Puppet::Util::Windows::SID::LocalSystem
well_known_app_packages_sid = Puppet::Util::Windows::SID::AllAppPackages
mode = S_ISYSTEM_MISSING
sd = get_security_descriptor(path)
sd.dacl.each do |ace|
next if ace.inherit_only?
case ace.sid
when sd.owner
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 6)
end
end
when sd.group
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 3)
end
end
when well_known_world_sid
MASK_TO_MODE.each_pair do |k, v|
if (ace.mask & k) == k
mode |= (v << 6) | (v << 3) | v
end
end
if File.directory?(path) &&
(ace.mask & (FILE::FILE_WRITE_DATA | FILE::FILE_EXECUTE | FILE::FILE_DELETE_CHILD)) == (FILE::FILE_WRITE_DATA | FILE::FILE_EXECUTE)
mode |= S_ISVTX;
end
when well_known_nobody_sid
if (ace.mask & FILE::FILE_APPEND_DATA).nonzero?
mode |= S_ISVTX
end
when well_known_app_packages_sid, well_known_system_sid
# do nothing
else
# puts "Warning, unable to map SID into POSIX mode: #{ace.sid}"
mode |= S_IEXTRA
end
if ace.sid == well_known_system_sid
mode &= ~S_ISYSTEM_MISSING
end
# if owner and group the same, then user and group modes are the OR of both
if sd.owner == sd.group
mode |= ((mode & S_IRWXG) << 3) | ((mode & S_IRWXU) >> 3)
# puts "owner: #{sd.group}, 0x#{ace.mask.to_s(16)}, #{mode.to_s(8)}"
end
end
# puts "get_mode: #{mode.to_s(8)}"
mode
end
MODE_TO_MASK = {
S_IROTH => FILE::FILE_GENERIC_READ,
S_IWOTH => FILE::FILE_GENERIC_WRITE,
S_IXOTH => (FILE::FILE_GENERIC_EXECUTE & ~FILE::FILE_READ_ATTRIBUTES),
}
# Set the mode of the object referenced by +path+ to the specified
# +mode+. The mode should be specified as POSIX-style read, write,
# and execute modes for the user, group, and other classes,
# e.g. 0640. The sticky bit, S_ISVTX, is supported, but is only
# meaningful for directories. If set, group and others are not
# allowed to delete child objects for which they are not the owner.
# By default, the DACL is set to protected, meaning it does not
# inherit access control entries from parent objects. This can be
# changed by setting +protected+ to false. The owner of the object
# (with READ_CONTROL and WRITE_DACL access) can always change the
# mode. Only a user with the SE_BACKUP_NAME and SE_RESTORE_NAME
# privileges in their process token can change the mode for objects
# that they do not have read and write access to.
def set_mode(mode, path, protected = true, managing_owner = false, managing_group = false)
sd = get_security_descriptor(path)
well_known_world_sid = Puppet::Util::Windows::SID::Everyone
well_known_nobody_sid = Puppet::Util::Windows::SID::Nobody
well_known_system_sid = Puppet::Util::Windows::SID::LocalSystem
owner_allow = FILE::STANDARD_RIGHTS_ALL |
FILE::FILE_READ_ATTRIBUTES |
FILE::FILE_WRITE_ATTRIBUTES
# this prevents a mode that is not 7 from taking ownership of a file based
# on group membership and rewriting it / making it executable
group_allow = FILE::STANDARD_RIGHTS_READ |
FILE::FILE_READ_ATTRIBUTES |
FILE::SYNCHRONIZE
other_allow = FILE::STANDARD_RIGHTS_READ |
FILE::FILE_READ_ATTRIBUTES |
FILE::SYNCHRONIZE
nobody_allow = 0
system_allow = 0
MODE_TO_MASK.each do |k, v|
if ((mode >> 6) & k) == k
owner_allow |= v
end
if ((mode >> 3) & k) == k
group_allow |= v
end
if (mode & k) == k
other_allow |= v
end
end
# With a mode value of '7' for group / other, the value must then include
# additional perms beyond STANDARD_RIGHTS_READ to allow DACL modification
if (mode & S_IRWXG) == S_IRWXG
group_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER
end
if (mode & S_IRWXO) == S_IRWXO
other_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER
end
if (mode & S_ISVTX).nonzero?
nobody_allow |= FILE::FILE_APPEND_DATA;
end
isownergroup = sd.owner == sd.group
# caller is NOT managing SYSTEM by using group or owner, so set to FULL
if ![sd.owner, sd.group].include? well_known_system_sid
# we don't check S_ISYSTEM_MISSING bit, but automatically carry over existing SYSTEM perms
# by default set SYSTEM perms to full
system_allow = FILE::FILE_ALL_ACCESS
else
# It is possible to set SYSTEM with a mode other than Full Control (7) however this makes no sense and in practical terms
# should not be done. We can trap these instances and correct them before being applied.
if (sd.owner == well_known_system_sid) && (owner_allow != FILE::FILE_ALL_ACCESS)
# If owner and group are both SYSTEM but group is unmanaged the control rights of system will be set to FullControl by
# the unmanaged group, so there is no need for the warning
if managing_owner && (!isownergroup || managing_group)
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.warning _("Setting control rights for %{path} owner SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file") % { path: path }
elsif managing_owner && isownergroup
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("%{path} owner and group both set to user SYSTEM, but group is not managed directly: SYSTEM user rights will be set to FullControl by group") % { path: path } }
else
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("An attempt to set mode %{mode} on item %{path} would result in the owner, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control") % { mode: mode.to_s(8), path: path } }
owner_allow = FILE::FILE_ALL_ACCESS
end
end
if (sd.group == well_known_system_sid) && (group_allow != FILE::FILE_ALL_ACCESS)
# If owner and group are both SYSTEM but owner is unmanaged the control rights of system will be set to FullControl by
# the unmanaged owner, so there is no need for the warning.
if managing_group && (!isownergroup || managing_owner)
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.warning _("Setting control rights for %{path} group SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file") % { path: path }
elsif managing_group && isownergroup
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("%{path} owner and group both set to user SYSTEM, but owner is not managed directly: SYSTEM user rights will be set to FullControl by owner") % { path: path } }
else
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("An attempt to set mode %{mode} on item %{path} would result in the group, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control") % { mode: mode.to_s(8), path: path } }
group_allow = FILE::FILE_ALL_ACCESS
end
end
end
# even though FILE_DELETE_CHILD only applies to directories, it can be set on files
# this is necessary to do to ensure a file ends up with (F) FullControl
if (mode & (S_IWUSR | S_IXUSR)) == (S_IWUSR | S_IXUSR)
owner_allow |= FILE::FILE_DELETE_CHILD
end
if (mode & (S_IWGRP | S_IXGRP)) == (S_IWGRP | S_IXGRP) && (mode & S_ISVTX) == 0
group_allow |= FILE::FILE_DELETE_CHILD
end
if (mode & (S_IWOTH | S_IXOTH)) == (S_IWOTH | S_IXOTH) && (mode & S_ISVTX) == 0
other_allow |= FILE::FILE_DELETE_CHILD
end
# if owner and group the same, then map group permissions to the one owner ACE
if isownergroup
owner_allow |= group_allow
end
# if any ACE allows write, then clear readonly bit, but do this before we overwrite
# the DACl and lose our ability to set the attribute
if ((owner_allow | group_allow | other_allow) & FILE::FILE_WRITE_DATA) == FILE::FILE_WRITE_DATA
FILE.remove_attributes(path, FILE::FILE_ATTRIBUTE_READONLY)
end
isdir = File.directory?(path)
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(sd.owner, owner_allow)
unless isownergroup
dacl.allow(sd.group, group_allow)
end
dacl.allow(well_known_world_sid, other_allow)
dacl.allow(well_known_nobody_sid, nobody_allow)
# TODO: system should be first?
flags = !isdir ? 0 :
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
dacl.allow(well_known_system_sid, system_allow, flags)
# add inherit-only aces for child dirs and files that are created within the dir
inherit_only = Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
if isdir
inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE
dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow, inherit)
dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow, inherit)
inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE
# allow any previously set bits *except* for these
perms_to_strip = ~(FILE::FILE_EXECUTE + FILE::WRITE_OWNER + FILE::WRITE_DAC)
dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow & perms_to_strip, inherit)
dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow & perms_to_strip, inherit)
end
new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, dacl, protected)
set_security_descriptor(path, new_sd)
nil
end
ACL_REVISION = 2
def add_access_allowed_ace(acl, mask, sid, inherit = nil)
inherit ||= NO_INHERITANCE
Puppet::Util::Windows::SID.string_to_sid_ptr(sid) do |sid_ptr|
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
if AddAccessAllowedAceEx(acl, ACL_REVISION, inherit, mask, sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to add access control entry")
end
end
# ensure this method is void if it doesn't raise
nil
end
def add_access_denied_ace(acl, mask, sid, inherit = nil)
inherit ||= NO_INHERITANCE
Puppet::Util::Windows::SID.string_to_sid_ptr(sid) do |sid_ptr|
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
if AddAccessDeniedAceEx(acl, ACL_REVISION, inherit, mask, sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to add access control entry")
end
end
# ensure this method is void if it doesn't raise
nil
end
def parse_dacl(dacl_ptr)
# REMIND: need to handle NULL DACL
if IsValidAcl(dacl_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid DACL")
end
dacl_struct = ACL.new(dacl_ptr)
ace_count = dacl_struct[:AceCount]
dacl = Puppet::Util::Windows::AccessControlList.new
# deny all
return dacl if ace_count == 0
0.upto(ace_count - 1) do |i|
FFI::MemoryPointer.new(:pointer, 1) do |ace_ptr|
next if GetAce(dacl_ptr, i, ace_ptr) == FFI::WIN32_FALSE
# ACE structures vary depending on the type. We are only concerned with
# ACCESS_ALLOWED_ACE and ACCESS_DENIED_ACEs, which have the same layout
ace = GENERIC_ACCESS_ACE.new(ace_ptr.get_pointer(0)) # deref LPVOID *
ace_type = ace[:Header][:AceType]
if ace_type != Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE &&
ace_type != Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
Puppet.warning _("Unsupported access control entry type: 0x%{type}") % { type: ace_type.to_s(16) }
next
end
# using pointer addition gives the FFI::Pointer a size, but that's OK here
sid = Puppet::Util::Windows::SID.sid_ptr_to_string(ace.pointer + GENERIC_ACCESS_ACE.offset_of(:SidStart))
mask = ace[:Mask]
ace_flags = ace[:Header][:AceFlags]
case ace_type
when Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE
dacl.allow(sid, mask, ace_flags)
when Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
dacl.deny(sid, mask, ace_flags)
end
end
end
dacl
end
# Open an existing file with the specified access mode, and execute a
# block with the opened file HANDLE.
def open_file(path, access, &block)
handle = CreateFileW(
wide_string(path),
access,
FILE::FILE_SHARE_READ | FILE::FILE_SHARE_WRITE,
FFI::Pointer::NULL, # security_attributes
FILE::OPEN_EXISTING,
FILE::FILE_FLAG_OPEN_REPARSE_POINT | FILE::FILE_FLAG_BACKUP_SEMANTICS,
FFI::Pointer::NULL_HANDLE
) # template
if handle == Puppet::Util::Windows::File::INVALID_HANDLE_VALUE
raise Puppet::Util::Windows::Error, _("Failed to open '%{path}'") % { path: path }
end
begin
yield handle
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
# handle has already had CloseHandle called against it, nothing to return
nil
end
# Execute a block with the specified privilege enabled
def with_privilege(privilege, &block)
set_privilege(privilege, true)
yield
ensure
set_privilege(privilege, false)
end
SE_PRIVILEGE_ENABLED = 0x00000002
TOKEN_ADJUST_PRIVILEGES = 0x0020
# Enable or disable a privilege. Note this doesn't add any privileges the
# user doesn't already has, it just enables privileges that are disabled.
def set_privilege(privilege, enable)
return unless Puppet.features.root?
Puppet::Util::Windows::Process.with_process_token(TOKEN_ADJUST_PRIVILEGES) do |token|
Puppet::Util::Windows::Process.lookup_privilege_value(privilege) do |luid|
FFI::MemoryPointer.new(Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.size) do |luid_and_attributes_ptr|
# allocate unmanaged memory for structs that we clean up afterwards
luid_and_attributes = Puppet::Util::Windows::Process::LUID_AND_ATTRIBUTES.new(luid_and_attributes_ptr)
luid_and_attributes[:Luid] = luid
luid_and_attributes[:Attributes] = enable ? SE_PRIVILEGE_ENABLED : 0
FFI::MemoryPointer.new(Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.size) do |token_privileges_ptr|
token_privileges = Puppet::Util::Windows::Process::TOKEN_PRIVILEGES.new(token_privileges_ptr)
token_privileges[:PrivilegeCount] = 1
token_privileges[:Privileges][0] = luid_and_attributes
# size is correct given we only have 1 LUID, otherwise would be:
# [:PrivilegeCount].size + [:PrivilegeCount] * LUID_AND_ATTRIBUTES.size
if AdjustTokenPrivileges(token, FFI::WIN32_FALSE,
token_privileges, token_privileges.size,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to adjust process privileges")
end
end
end
end
end
# token / luid structs freed by this point, so return true as nothing raised
true
end
def get_security_descriptor(path)
sd = nil
with_privilege(SE_BACKUP_NAME) do
open_file(path, READ_CONTROL) do |handle|
FFI::MemoryPointer.new(:pointer, 1) do |owner_sid_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |group_sid_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |dacl_ptr_ptr|
FFI::MemoryPointer.new(:pointer, 1) do |sd_ptr_ptr|
rv = GetSecurityInfo(
handle,
:SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
owner_sid_ptr_ptr,
group_sid_ptr_ptr,
dacl_ptr_ptr,
FFI::Pointer::NULL, # sacl
sd_ptr_ptr
) # sec desc
raise Puppet::Util::Windows::Error, _("Failed to get security information") if rv != FFI::ERROR_SUCCESS
# these 2 convenience params are not freed since they point inside sd_ptr
owner = Puppet::Util::Windows::SID.sid_ptr_to_string(owner_sid_ptr_ptr.get_pointer(0))
group = Puppet::Util::Windows::SID.sid_ptr_to_string(group_sid_ptr_ptr.get_pointer(0))
FFI::MemoryPointer.new(:word, 1) do |control|
FFI::MemoryPointer.new(:dword, 1) do |revision|
sd_ptr_ptr.read_win32_local_pointer do |sd_ptr|
if GetSecurityDescriptorControl(sd_ptr, control, revision) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get security descriptor control")
end
protect = (control.read_word & SE_DACL_PROTECTED) == SE_DACL_PROTECTED
dacl = parse_dacl(dacl_ptr_ptr.get_pointer(0))
sd = Puppet::Util::Windows::SecurityDescriptor.new(owner, group, dacl, protect)
end
end
end
end
end
end
end
end
end
sd
end
def get_max_generic_acl_size(ace_count)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa378853(v=vs.85).aspx
# To calculate the initial size of an ACL, add the following together, and then align the result to the nearest DWORD:
# * Size of the ACL structure.
# * Size of each ACE structure that the ACL is to contain minus the SidStart member (DWORD) of the ACE.
# * Length of the SID that each ACE is to contain.
ACL.size + ace_count * MAXIMUM_GENERIC_ACE_SIZE
end
# setting DACL requires both READ_CONTROL and WRITE_DACL access rights,
# and their respective privileges, SE_BACKUP_NAME and SE_RESTORE_NAME.
def set_security_descriptor(path, sd)
FFI::MemoryPointer.new(:byte, get_max_generic_acl_size(sd.dacl.count)) do |acl_ptr|
if InitializeAcl(acl_ptr, acl_ptr.size, ACL_REVISION) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to initialize ACL")
end
if IsValidAcl(acl_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid DACL")
end
with_privilege(SE_BACKUP_NAME) do
with_privilege(SE_RESTORE_NAME) do
open_file(path, READ_CONTROL | WRITE_DAC | WRITE_OWNER) do |handle|
Puppet::Util::Windows::SID.string_to_sid_ptr(sd.owner) do |owner_sid_ptr|
Puppet::Util::Windows::SID.string_to_sid_ptr(sd.group) do |group_sid_ptr|
sd.dacl.each do |ace|
case ace.type
when Puppet::Util::Windows::AccessControlEntry::ACCESS_ALLOWED_ACE_TYPE
# puts "ace: allow, sid #{Puppet::Util::Windows::SID.sid_to_name(ace.sid)}, mask 0x#{ace.mask.to_s(16)}"
add_access_allowed_ace(acl_ptr, ace.mask, ace.sid, ace.flags)
when Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE
# puts "ace: deny, sid #{Puppet::Util::Windows::SID.sid_to_name(ace.sid)}, mask 0x#{ace.mask.to_s(16)}"
add_access_denied_ace(acl_ptr, ace.mask, ace.sid, ace.flags)
else
raise "We should never get here"
# TODO: this should have been a warning in an earlier commit
end
end
# protected means the object does not inherit aces from its parent
flags = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
flags |= sd.protect ? PROTECTED_DACL_SECURITY_INFORMATION : UNPROTECTED_DACL_SECURITY_INFORMATION
rv = SetSecurityInfo(handle,
:SE_FILE_OBJECT,
flags,
owner_sid_ptr,
group_sid_ptr,
acl_ptr,
FFI::MemoryPointer::NULL)
if rv != FFI::ERROR_SUCCESS
raise Puppet::Util::Windows::Error, _("Failed to set security information")
end
end
end
end
end
end
end
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
# 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://msdn.microsoft.com/en-us/library/windows/desktop/aa364993(v=vs.85).aspx
# BOOL WINAPI GetVolumeInformation(
# _In_opt_ LPCTSTR lpRootPathName,
# _Out_opt_ LPTSTR lpVolumeNameBuffer,
# _In_ DWORD nVolumeNameSize,
# _Out_opt_ LPDWORD lpVolumeSerialNumber,
# _Out_opt_ LPDWORD lpMaximumComponentLength,
# _Out_opt_ LPDWORD lpFileSystemFlags,
# _Out_opt_ LPTSTR lpFileSystemNameBuffer,
# _In_ DWORD nFileSystemNameSize
# );
ffi_lib :kernel32
attach_function_private :GetVolumeInformationW,
[:lpcwstr, :lpwstr, :dword, :lpdword, :lpdword, :lpdword, :lpwstr, :dword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374951(v=vs.85).aspx
# BOOL WINAPI AddAccessAllowedAceEx(
# _Inout_ PACL pAcl,
# _In_ DWORD dwAceRevision,
# _In_ DWORD AceFlags,
# _In_ DWORD AccessMask,
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :AddAccessAllowedAceEx,
[:pointer, :dword, :dword, :dword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374964(v=vs.85).aspx
# BOOL WINAPI AddAccessDeniedAceEx(
# _Inout_ PACL pAcl,
# _In_ DWORD dwAceRevision,
# _In_ DWORD AceFlags,
# _In_ DWORD AccessMask,
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :AddAccessDeniedAceEx,
[:pointer, :dword, :dword, :dword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374931(v=vs.85).aspx
# typedef struct _ACL {
# BYTE AclRevision;
# BYTE Sbz1;
# WORD AclSize;
# WORD AceCount;
# WORD Sbz2;
# } ACL, *PACL;
class ACL < FFI::Struct
layout :AclRevision, :byte,
:Sbz1, :byte,
:AclSize, :word,
:AceCount, :word,
:Sbz2, :word
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374912(v=vs.85).aspx
# ACE types
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa374919(v=vs.85).aspx
# typedef struct _ACE_HEADER {
# BYTE AceType;
# BYTE AceFlags;
# WORD AceSize;
# } ACE_HEADER, *PACE_HEADER;
class ACE_HEADER < FFI::Struct
layout :AceType, :byte,
:AceFlags, :byte,
:AceSize, :word
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/eventlog.rb | lib/puppet/util/windows/eventlog.rb | # frozen_string_literal: true
require 'ffi'
# Puppet::Util::Windows::EventLog needs to be requirable without having loaded
# any other parts of Puppet so it can be leveraged independently by the code
# that runs Puppet as a service on Windows.
#
# For this reason we:
# - Define Puppet::Util::Windows
# - Replicate logic that exists elsewhere in puppet/util/windows
# - Raise generic RuntimeError instead of Puppet::Util::Windows::Error if its not defined
module Puppet; module Util; module Windows; end; end; end
class Puppet::Util::Windows::EventLog
extend FFI::Library
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
EVENTLOG_ERROR_TYPE = 0x0001
EVENTLOG_WARNING_TYPE = 0x0002
EVENTLOG_INFORMATION_TYPE = 0x0004
# These are duplicate definitions from Puppet::Util::Windows::ApiTypes,
# established here so this class can be standalone from Puppet, and public so
# we can reference them in tests.
NULL_HANDLE = 0
WIN32_FALSE = 0
# Register an event log handle for the application
# @param source_name [String] the name of the event source to retrieve a handle for
# @return [void]
# @api public
def initialize(source_name = 'Puppet')
@eventlog_handle = RegisterEventSourceW(FFI::Pointer::NULL, wide_string(source_name))
if @eventlog_handle == NULL_HANDLE
# TRANSLATORS 'Windows' is the operating system and 'RegisterEventSourceW' is a API call and should not be translated
raise EventLogError.new(_("RegisterEventSourceW failed to open Windows eventlog"), FFI.errno)
end
end
# Close this instance's event log handle
# @return [void]
# @api public
def close
DeregisterEventSource(@eventlog_handle)
ensure
@eventlog_handle = nil
end
# Report an event to this instance's event log handle. Accepts a string to
# report (:data => <string>) and event type (:event_type => Integer) and id
# (:event_id => Integer) as returned by #to_native. The additional arguments to
# ReportEventW seen in this method aren't exposed - though ReportEventW
# technically can accept multiple strings as well as raw binary data to log,
# we accept a single string from Puppet::Util::Log
#
# @param args [Hash{Symbol=>Object}] options to the associated log event
# @return [void]
# @api public
def report_event(args = {})
unless args[:data].is_a?(String)
raise ArgumentError, _("data must be a string, not %{class_name}") % { class_name: args[:data].class }
end
from_string_to_wide_string(args[:data]) do |message_ptr|
FFI::MemoryPointer.new(:pointer) do |message_array_ptr|
message_array_ptr.write_pointer(message_ptr)
user_sid = FFI::Pointer::NULL
raw_data = FFI::Pointer::NULL
raw_data_size = 0
num_strings = 1
eventlog_category = 0
report_result = ReportEventW(@eventlog_handle, args[:event_type],
eventlog_category, args[:event_id], user_sid,
num_strings, raw_data_size, message_array_ptr, raw_data)
if report_result == WIN32_FALSE
# TRANSLATORS 'Windows' is the operating system and 'ReportEventW' is a API call and should not be translated
raise EventLogError.new(_("ReportEventW failed to report event to Windows eventlog"), FFI.errno)
end
end
end
end
class << self
# Feels more natural to do Puppet::Util::Window::EventLog.open("MyApplication")
alias :open :new
# Query event identifier info for a given log level
# @param level [Symbol] an event log level
# @return [Array] Win API Event ID, Puppet Event ID
# @api public
def to_native(level)
case level
when :debug, :info, :notice
[EVENTLOG_INFORMATION_TYPE, 0x01]
when :warning
[EVENTLOG_WARNING_TYPE, 0x02]
when :err, :alert, :emerg, :crit
[EVENTLOG_ERROR_TYPE, 0x03]
else
raise ArgumentError, _("Invalid log level %{level}") % { level: level }
end
end
end
private
# For the purposes of allowing this class to be standalone, the following are
# duplicate definitions from elsewhere in Puppet:
# If we're loaded via Puppet we should keep the previous behavior of raising
# Puppet::Util::Windows::Error on errors. If we aren't, at least concatenate
# the error code to the exception message to pass this information on to the
# user
if defined?(Puppet::Util::Windows::Error)
EventLogError = Puppet::Util::Windows::Error
else
class EventLogError < RuntimeError
def initialize(msg, code)
# TRANSLATORS 'Win32' is the Windows API and should not be translated
super(msg + ' ' + _("(Win32 error: %{detail})") % { detail: code })
end
end
end
# Private duplicate of Puppet::Util::Windows::String::wide_string
# Not for use outside of EventLog! - use Puppet::Util::Windows instead
# @api private
def wide_string(str)
# if given a nil string, assume caller wants to pass a nil pointer to win32
return nil if str.nil?
str.encode('UTF-16LE')
end
# Private duplicate of Puppet::Util::Windows::ApiTypes::from_string_to_wide_string
# Not for use outside of EventLog! - Use Puppet::Util::Windows instead
# @api private
def from_string_to_wide_string(str, &block)
str = wide_string(str)
FFI::MemoryPointer.from_wide_string(str) { |ptr| yield ptr }
# ptr has already had free called, so nothing to return
nil
end
ffi_convention :stdcall
# The following are typedefs in Puppet::Util::Winodws::ApiTypes, but here we
# use their original FFI counterparts:
# :uintptr_t for :handle
# :int32 for :win32_bool
# :uint16 for :word
# :uint32 for :dword
# :pointer for :lpvoid
# :uchar for :byte
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363678(v=vs.85).aspx
# HANDLE RegisterEventSource(
# _In_ LPCTSTR lpUNCServerName,
# _In_ LPCTSTR lpSourceName
# );
ffi_lib :advapi32
attach_function :RegisterEventSourceW, [:buffer_in, :buffer_in], :uintptr_t
private :RegisterEventSourceW
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363642(v=vs.85).aspx
# BOOL DeregisterEventSource(
# _Inout_ HANDLE hEventLog
# );
ffi_lib :advapi32
attach_function :DeregisterEventSource, [:uintptr_t], :int32
private :DeregisterEventSource
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx
# BOOL ReportEvent(
# _In_ HANDLE hEventLog,
# _In_ WORD wType,
# _In_ WORD wCategory,
# _In_ DWORD dwEventID,
# _In_ PSID lpUserSid,
# _In_ WORD wNumStrings,
# _In_ DWORD dwDataSize,
# _In_ LPCTSTR *lpStrings,
# _In_ LPVOID lpRawData
# );
ffi_lib :advapi32
attach_function :ReportEventW, [:uintptr_t, :uint16, :uint16, :uint32, :pointer, :uint16, :uint32, :pointer, :pointer], :int32
private :ReportEventW
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/daemon.rb | lib/puppet/util/windows/daemon.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows
# The Daemon class, based on the chef/win32-service implementation
class Daemon
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
# Service is not running
STOPPED = SERVICE_STOPPED
# Service has received a start signal but is not yet running
START_PENDING = SERVICE_START_PENDING
# Service has received a stop signal but is not yet stopped
STOP_PENDING = SERVICE_STOP_PENDING
# Service is running
RUNNING = SERVICE_RUNNING
# Service has received a signal to resume but is not yet running
CONTINUE_PENDING = SERVICE_CONTINUE_PENDING
# Service has received a signal to pause but is not yet paused
PAUSE_PENDING = SERVICE_PAUSE_PENDING
# Service is paused
PAUSED = SERVICE_PAUSED
# Service controls
# Notifies service that it should stop
CONTROL_STOP = SERVICE_CONTROL_STOP
# Notifies service that it should pause
CONTROL_PAUSE = SERVICE_CONTROL_PAUSE
# Notifies service that it should resume
CONTROL_CONTINUE = SERVICE_CONTROL_CONTINUE
# Notifies service that it should return its current status information
CONTROL_INTERROGATE = SERVICE_CONTROL_INTERROGATE
# Notifies a service that its parameters have changed
CONTROL_PARAMCHANGE = SERVICE_CONTROL_PARAMCHANGE
# Notifies a service that there is a new component for binding
CONTROL_NETBINDADD = SERVICE_CONTROL_NETBINDADD
# Notifies a service that a component for binding has been removed
CONTROL_NETBINDREMOVE = SERVICE_CONTROL_NETBINDREMOVE
# Notifies a service that a component for binding has been enabled
CONTROL_NETBINDENABLE = SERVICE_CONTROL_NETBINDENABLE
# Notifies a service that a component for binding has been disabled
CONTROL_NETBINDDISABLE = SERVICE_CONTROL_NETBINDDISABLE
IDLE = 0
# Misc
IDLE_CONTROL_CODE = 0
WAIT_OBJECT_0 = 0
WAIT_TIMEOUT = 0x00000102
WAIT_FAILED = 0xFFFFFFFF
NO_ERROR = 0
# Wraps SetServiceStatus.
SetTheServiceStatus = proc do |dwCurrentState, dwWin32ExitCode, dwCheckPoint, dwWaitHint|
ss = SERVICE_STATUS.new # Current status of the service.
# Disable control requests until the service is started.
if dwCurrentState == SERVICE_START_PENDING
ss[:dwControlsAccepted] = 0
else
ss[:dwControlsAccepted] =
SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN |
SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_PARAMCHANGE
end
# Initialize ss structure.
ss[:dwServiceType] = SERVICE_WIN32_OWN_PROCESS
ss[:dwServiceSpecificExitCode] = 0
ss[:dwCurrentState] = dwCurrentState
ss[:dwWin32ExitCode] = dwWin32ExitCode
ss[:dwCheckPoint] = dwCheckPoint
ss[:dwWaitHint] = dwWaitHint
@@dwServiceState = dwCurrentState
# Send status of the service to the Service Controller.
unless SetServiceStatus(@@ssh, ss)
SetEvent(@@hStopEvent)
end
end
ERROR_CALL_NOT_IMPLEMENTED = 0x78
# Handles control signals from the service control manager.
Service_Ctrl_ex = proc do |dwCtrlCode, _dwEventType, _lpEventData, _lpContext|
@@waiting_control_code = dwCtrlCode;
return_value = NO_ERROR
begin
dwState = SERVICE_RUNNING
case dwCtrlCode
when SERVICE_CONTROL_STOP
dwState = SERVICE_STOP_PENDING
when SERVICE_CONTROL_SHUTDOWN
dwState = SERVICE_STOP_PENDING
when SERVICE_CONTROL_PAUSE
dwState = SERVICE_PAUSED
when SERVICE_CONTROL_CONTINUE
dwState = SERVICE_RUNNING
# else
# TODO: Handle other control codes? Retain the current state?
end
# Set the status of the service except on interrogation.
unless dwCtrlCode == SERVICE_CONTROL_INTERROGATE
SetTheServiceStatus.call(dwState, NO_ERROR, 0, 0)
end
# Tell service_main thread to stop.
if dwCtrlCode == SERVICE_CONTROL_STOP || dwCtrlCode == SERVICE_CONTROL_SHUTDOWN
if SetEvent(@@hStopEvent) == 0
SetTheServiceStatus.call(SERVICE_STOPPED, FFI.errno, 0, 0)
end
end
rescue
return_value = ERROR_CALL_NOT_IMPLEMENTED
end
return_value
end
# Called by the service control manager after the call to StartServiceCtrlDispatcher.
Service_Main = FFI::Function.new(:void, [:ulong, :pointer], :blocking => false) do |dwArgc, lpszArgv|
# Obtain the name of the service.
if lpszArgv.address != 0
argv = lpszArgv.get_array_of_string(0, dwArgc)
lpszServiceName = argv[0]
else
lpszServiceName = ''
end
# Args passed to Service.start
if dwArgc > 1
@@Argv = argv[1..]
else
@@Argv = nil
end
# Register the service ctrl handler.
@@ssh = RegisterServiceCtrlHandlerExW(
lpszServiceName,
Service_Ctrl_ex,
nil
)
# No service to stop, no service handle to notify, nothing to do but exit.
break if @@ssh == 0
# The service has started.
SetTheServiceStatus.call(SERVICE_RUNNING, NO_ERROR, 0, 0)
SetEvent(@@hStartEvent)
# Main loop for the service.
while WaitForSingleObject(@@hStopEvent, 1000) != WAIT_OBJECT_0
end
# Main loop for the service.
while WaitForSingleObject(@@hStopCompletedEvent, 1000) != WAIT_OBJECT_0
end
ensure
# Stop the service.
SetTheServiceStatus.call(SERVICE_STOPPED, NO_ERROR, 0, 0)
end
# This is a shortcut for Daemon.new + Daemon#mainloop.
#
def self.mainloop
new.mainloop
end
# This is the method that actually puts your code into a loop and allows it
# to run as a service. The code that is actually run while in the mainloop
# is what you defined in your own Daemon#service_main method.
#
def mainloop
@@waiting_control_code = IDLE_CONTROL_CODE
@@dwServiceState = 0
# Redirect STDIN, STDOUT and STDERR to the NUL device if they're still
# associated with a tty. This helps newbs avoid Errno::EBADF errors.
STDIN.reopen('NUL') if STDIN.isatty
STDOUT.reopen('NUL') if STDOUT.isatty
STDERR.reopen('NUL') if STDERR.isatty
# Calling init here so that init failures never even tries to start the
# service. Of course that means that init methods must be very quick
# because the SCM will be receiving no START_PENDING messages while
# init's running.
#
# TODO: Fix?
service_init() if respond_to?('service_init')
# Create the event to signal the service to start.
@@hStartEvent = CreateEventW(nil, 1, 0, nil)
if @@hStartEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
# Create the event to signal the service to stop.
@@hStopEvent = CreateEventW(nil, 1, 0, nil)
if @@hStopEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
# Create the event to signal the service that stop has completed
@@hStopCompletedEvent = CreateEventW(nil, 1, 0, nil)
if @@hStopCompletedEvent == 0
raise SystemCallError.new('CreateEvent', FFI.errno)
end
hThread = Thread.new do
ste = FFI::MemoryPointer.new(SERVICE_TABLE_ENTRYW, 2)
s = SERVICE_TABLE_ENTRYW.new(ste[0])
s[:lpServiceName] = FFI::MemoryPointer.from_string("")
s[:lpServiceProc] = Service_Main
s = SERVICE_TABLE_ENTRYW.new(ste[1])
s[:lpServiceName] = nil
s[:lpServiceProc] = nil
# No service to step, no service handle, no ruby exceptions, just terminate the thread..
StartServiceCtrlDispatcherW(ste)
end
while (index = WaitForSingleObject(@@hStartEvent, 1000)) == WAIT_TIMEOUT
# The thread exited, so the show is off.
raise "Service_Main thread exited abnormally" unless hThread.alive?
end
if index == WAIT_FAILED
raise SystemCallError.new("WaitForSingleObject", FFI.errno)
end
thr = Thread.new do
while WaitForSingleObject(@@hStopEvent, 1000) == WAIT_TIMEOUT
# Check to see if anything interesting has been signaled
case @@waiting_control_code
when SERVICE_CONTROL_PAUSE
service_pause() if respond_to?('service_pause')
when SERVICE_CONTROL_CONTINUE
service_resume() if respond_to?('service_resume')
when SERVICE_CONTROL_INTERROGATE
service_interrogate() if respond_to?('service_interrogate')
when SERVICE_CONTROL_SHUTDOWN
service_shutdown() if respond_to?('service_shutdown')
when SERVICE_CONTROL_PARAMCHANGE
service_paramchange() if respond_to?('service_paramchange')
when SERVICE_CONTROL_NETBINDADD
service_netbindadd() if respond_to?('service_netbindadd')
when SERVICE_CONTROL_NETBINDREMOVE
service_netbindremove() if respond_to?('service_netbindremove')
when SERVICE_CONTROL_NETBINDENABLE
service_netbindenable() if respond_to?('service_netbindenable')
when SERVICE_CONTROL_NETBINDDISABLE
service_netbinddisable() if respond_to?('service_netbinddisable')
end
@@waiting_control_code = IDLE_CONTROL_CODE
end
service_stop() if respond_to?('service_stop')
ensure
SetEvent(@@hStopCompletedEvent)
end
if respond_to?('service_main')
service_main(*@@Argv)
end
thr.join
end
# Returns the state of the service (as an constant integer) which can be any
# of the service status constants, e.g. RUNNING, PAUSED, etc.
#
# This method is typically used within your service_main method to setup the
# loop. For example:
#
# class MyDaemon < Daemon
# def service_main
# while state == RUNNING || state == PAUSED || state == IDLE
# # Your main loop here
# end
# end
# end
#
# See the Daemon#running? method for an abstraction of the above code.
#
def state
@@dwServiceState
end
#
# Returns whether or not the service is in a running state, i.e. the service
# status is either RUNNING, PAUSED or IDLE.
#
# This is typically used within your service_main method to setup the main
# loop. For example:
#
# class MyDaemon < Daemon
# def service_main
# while running?
# # Your main loop here
# end
# end
# end
#
def running?
[SERVICE_RUNNING, SERVICE_PAUSED, 0].include?(@@dwServiceState)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/file.rb | lib/puppet/util/windows/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows::File
extend Puppet::Util::Windows::String
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
def replace_file(target, source)
target_encoded = wide_string(target.to_s)
source_encoded = wide_string(source.to_s)
flags = REPLACEFILE_IGNORE_MERGE_ERRORS
backup_file = nil
result = ReplaceFileW(
target_encoded,
source_encoded,
backup_file,
flags,
FFI::Pointer::NULL,
FFI::Pointer::NULL
)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "ReplaceFile(#{target}, #{source})"
end
module_function :replace_file
def move_file_ex(source, target, flags = 0)
result = MoveFileExW(wide_string(source.to_s),
wide_string(target.to_s),
flags)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "MoveFileEx(#{source}, #{target}, #{flags.to_s(8)})"
end
module_function :move_file_ex
def symlink(target, symlink)
flags = File.directory?(target) ? 0x1 : 0x0
result = CreateSymbolicLinkW(wide_string(symlink.to_s),
wide_string(target.to_s), flags)
return true if result != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "CreateSymbolicLink(#{symlink}, #{target}, #{flags.to_s(8)})"
end
module_function :symlink
def exist?(path)
path = path.to_str if path.respond_to?(:to_str) # support WatchedFile
path = path.to_s # support String and Pathname
seen_paths = []
# follow up to 64 symlinks before giving up
0.upto(64) do |_depth|
# return false if this path has been seen before. This is protection against circular symlinks
return false if seen_paths.include?(path.downcase)
result = get_attributes(path, false)
# return false for path not found
return false if result == INVALID_FILE_ATTRIBUTES
# return true if path exists and it's not a symlink
# Other file attributes are ignored. https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx
reparse_point = (result & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
if reparse_point && symlink_reparse_point?(path)
# walk the symlink and try again...
seen_paths << path.downcase
path = readlink(path)
else
# file was found and its not a symlink
return true
end
end
false
end
module_function :exist?
def get_attributes(file_name, raise_on_invalid = true)
result = GetFileAttributesW(wide_string(file_name.to_s))
if raise_on_invalid && result == INVALID_FILE_ATTRIBUTES
raise Puppet::Util::Windows::Error, "GetFileAttributes(#{file_name})"
end
result
end
module_function :get_attributes
def add_attributes(path, flags)
oldattrs = get_attributes(path)
if (oldattrs | flags) != oldattrs
set_attributes(path, oldattrs | flags)
end
end
module_function :add_attributes
def remove_attributes(path, flags)
oldattrs = get_attributes(path)
if (oldattrs & ~flags) != oldattrs
set_attributes(path, oldattrs & ~flags)
end
end
module_function :remove_attributes
def set_attributes(path, flags)
success = SetFileAttributesW(wide_string(path), flags) != FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to set file attributes") unless success
success
end
module_function :set_attributes
# define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)
INVALID_HANDLE_VALUE = FFI::Pointer.new(-1).address
def self.create_file(file_name, desired_access, share_mode, security_attributes,
creation_disposition, flags_and_attributes, template_file_handle)
result = CreateFileW(wide_string(file_name.to_s),
desired_access, share_mode, security_attributes, creation_disposition,
flags_and_attributes, template_file_handle)
return result unless result == INVALID_HANDLE_VALUE
raise Puppet::Util::Windows::Error, "CreateFile(#{file_name}, #{desired_access.to_s(8)}, #{share_mode.to_s(8)}, " \
"#{security_attributes}, #{creation_disposition.to_s(8)}, " \
"#{flags_and_attributes.to_s(8)}, #{template_file_handle})"
end
def self.get_reparse_point_data(handle, &block)
# must be multiple of 1024, min 10240
FFI::MemoryPointer.new(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) do |reparse_data_buffer_ptr|
device_io_control(handle, FSCTL_GET_REPARSE_POINT, nil, reparse_data_buffer_ptr)
reparse_tag = reparse_data_buffer_ptr.read_win32_ulong
buffer_type = case reparse_tag
when IO_REPARSE_TAG_SYMLINK
SYMLINK_REPARSE_DATA_BUFFER
when IO_REPARSE_TAG_MOUNT_POINT
MOUNT_POINT_REPARSE_DATA_BUFFER
when IO_REPARSE_TAG_NFS
raise Puppet::Util::Windows::Error, "Retrieving NFS reparse point data is unsupported"
else
raise Puppet::Util::Windows::Error, "DeviceIoControl(#{handle}, " \
"FSCTL_GET_REPARSE_POINT) returned unknown tag 0x#{reparse_tag.to_s(16).upcase}"
end
yield buffer_type.new(reparse_data_buffer_ptr)
end
# underlying struct MemoryPointer has been cleaned up by this point, nothing to return
nil
end
def self.get_reparse_point_tag(handle)
reparse_tag = nil
# must be multiple of 1024, min 10240
FFI::MemoryPointer.new(MAXIMUM_REPARSE_DATA_BUFFER_SIZE) do |reparse_data_buffer_ptr|
device_io_control(handle, FSCTL_GET_REPARSE_POINT, nil, reparse_data_buffer_ptr)
# DWORD ReparseTag is the first member of the struct
reparse_tag = reparse_data_buffer_ptr.read_win32_ulong
end
reparse_tag
end
def self.device_io_control(handle, io_control_code, in_buffer = nil, out_buffer = nil)
if out_buffer.nil?
raise Puppet::Util::Windows::Error, _("out_buffer is required")
end
FFI::MemoryPointer.new(:dword, 1) do |bytes_returned_ptr|
result = DeviceIoControl(
handle,
io_control_code,
in_buffer, in_buffer.nil? ? 0 : in_buffer.size,
out_buffer, out_buffer.size,
bytes_returned_ptr,
nil
)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "DeviceIoControl(#{handle}, #{io_control_code}, " \
"#{in_buffer}, #{in_buffer ? in_buffer.size : ''}, " \
"#{out_buffer}, #{out_buffer ? out_buffer.size : ''}"
end
end
out_buffer
end
def reparse_point?(file_name)
attributes = get_attributes(file_name, false)
return false if attributes == INVALID_FILE_ATTRIBUTES
(attributes & FILE_ATTRIBUTE_REPARSE_POINT) == FILE_ATTRIBUTE_REPARSE_POINT
end
module_function :reparse_point?
def symlink?(file_name)
# Puppet currently only handles mount point and symlink reparse points, ignores others
reparse_point?(file_name) && symlink_reparse_point?(file_name)
end
module_function :symlink?
def self.open_symlink(link_name)
begin
yield handle = create_file(
link_name,
GENERIC_READ,
FILE_SHARE_READ,
nil, # security_attributes
OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
0
) # template_file
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
# handle has had CloseHandle called against it, so nothing to return
nil
end
def readlink(link_name)
link = nil
open_symlink(link_name) do |handle|
link = resolve_symlink(handle)
end
link
end
module_function :readlink
def get_long_pathname(path)
converted = ''.dup
FFI::Pointer.from_string_to_wide_string(path) do |path_ptr|
# includes terminating NULL
buffer_size = GetLongPathNameW(path_ptr, FFI::Pointer::NULL, 0)
FFI::MemoryPointer.new(:wchar, buffer_size) do |converted_ptr|
if GetLongPathNameW(path_ptr, converted_ptr, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to call GetLongPathName")
end
converted = converted_ptr.read_wide_string(buffer_size - 1)
end
end
converted
end
module_function :get_long_pathname
def get_short_pathname(path)
converted = ''.dup
FFI::Pointer.from_string_to_wide_string(path) do |path_ptr|
# includes terminating NULL
buffer_size = GetShortPathNameW(path_ptr, FFI::Pointer::NULL, 0)
FFI::MemoryPointer.new(:wchar, buffer_size) do |converted_ptr|
if GetShortPathNameW(path_ptr, converted_ptr, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "Failed to call GetShortPathName"
end
converted = converted_ptr.read_wide_string(buffer_size - 1)
end
end
converted
end
module_function :get_short_pathname
def stat(file_name)
file_name = file_name.to_s # accommodate PathName or String
stat = File.stat(file_name)
singleton_class = class << stat; self; end
target_path = file_name
if symlink?(file_name)
target_path = readlink(file_name)
link_ftype = File.stat(target_path).ftype
# sigh, monkey patch instance method for instance, and close over link_ftype
singleton_class.send(:define_method, :ftype) do
link_ftype
end
end
singleton_class.send(:define_method, :mode) do
Puppet::Util::Windows::Security.get_mode(target_path)
end
stat
end
module_function :stat
def lstat(file_name)
file_name = file_name.to_s # accommodate PathName or String
# monkey'ing around!
stat = File.lstat(file_name)
singleton_class = class << stat; self; end
singleton_class.send(:define_method, :mode) do
Puppet::Util::Windows::Security.get_mode(file_name)
end
if symlink?(file_name)
def stat.ftype
"link"
end
end
stat
end
module_function :lstat
def self.resolve_symlink(handle)
path = nil
get_reparse_point_data(handle) do |reparse_data|
offset = reparse_data[:PrintNameOffset]
length = reparse_data[:PrintNameLength]
ptr = reparse_data.pointer + reparse_data.offset_of(:PathBuffer) + offset
path = ptr.read_wide_string(length / 2) # length is bytes, need UTF-16 wchars
end
path
end
private_class_method :resolve_symlink
# these reparse point types are the only ones Puppet currently understands
# so rather than raising an exception in readlink, prefer to not consider
# the path a symlink when stat'ing later
def self.symlink_reparse_point?(path)
symlink = false
open_symlink(path) do |handle|
symlink = [
IO_REPARSE_TAG_SYMLINK,
IO_REPARSE_TAG_MOUNT_POINT
].include?(get_reparse_point_tag(handle))
end
symlink
end
private_class_method :symlink_reparse_point?
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/registry.rb | lib/puppet/util/windows/registry.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows
module Registry
require 'ffi'
extend FFI::Library
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa384129(v=vs.85).aspx
KEY64 = 0x100
KEY32 = 0x200
KEY_READ = 0x20019
KEY_WRITE = 0x20006
KEY_ALL_ACCESS = 0x2003f
ERROR_NO_MORE_ITEMS = 259
WCHAR_SIZE = FFI.type_size(:wchar)
def root(name)
Win32::Registry.const_get(name)
rescue NameError => e
raise Puppet::Error, _("Invalid registry key '%{name}'") % { name: name }, e.backtrace
end
def open(name, path, mode = KEY_READ | KEY64, &block)
hkey = root(name)
begin
hkey.open(path, mode) do |subkey|
return yield subkey
end
rescue Win32::Registry::Error => error
raise Puppet::Util::Windows::Error.new(_("Failed to open registry key '%{key}\\%{path}'") % { key: hkey.keyname, path: path }, error.code, error)
end
end
def keys(key)
keys = {}
each_key(key) { |subkey, filetime| keys[subkey] = filetime }
keys
end
# subkey is String which contains name of subkey.
# wtime is last write time as FILETIME (64-bit integer). (see Registry.wtime2time)
def each_key(key, &block)
index = 0
subkey = nil
subkey_max_len, _ = reg_query_info_key_max_lengths(key)
loop do
subkey, filetime = reg_enum_key(key, index, subkey_max_len)
yield subkey, filetime unless subkey.nil?
index += 1
break if subkey.nil?
end
index
end
def delete_key(key, subkey_name, mode = KEY64)
reg_delete_key_ex(key, subkey_name, mode)
end
def values(key)
vals = {}
each_value(key) { |subkey, _type, data| vals[subkey] = data }
vals
end
# Retrieve a set of values from a registry key given their names
# Value names listed but not found in the registry will not be added to the
# resultant Hashtable
#
# @param key [RegistryKey] An open handle to a Registry Key
# @param names [String[]] An array of names of registry values to return if they exist
# @return [Hashtable<String, Object>] A hashtable of all of the found values in the registry key
def values_by_name(key, names)
vals = {}
names.each do |name|
FFI::Pointer.from_string_to_wide_string(name) do |subkeyname_ptr|
_, vals[name] = read(key, subkeyname_ptr)
rescue Puppet::Util::Windows::Error => e
# ignore missing names, but raise other errors
raise e unless e.code == Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND
end
end
vals
end
def each_value(key, &block)
index = 0
subkey = nil
_, value_max_len = reg_query_info_key_max_lengths(key)
loop do
subkey, type, data = reg_enum_value(key, index, value_max_len)
yield subkey, type, data unless subkey.nil?
index += 1
break if subkey.nil?
end
index
end
def delete_value(key, subkey_name)
reg_delete_value(key, subkey_name)
end
private
# max number of wide characters including NULL terminator
MAX_KEY_CHAR_LENGTH = 255 + 1
def reg_enum_key(key, index, max_key_char_length = MAX_KEY_CHAR_LENGTH)
subkey = nil
filetime = nil
FFI::MemoryPointer.new(:dword) do |subkey_length_ptr|
FFI::MemoryPointer.new(FFI::WIN32::FILETIME.size) do |filetime_ptr|
FFI::MemoryPointer.new(:wchar, max_key_char_length) do |subkey_ptr|
subkey_length_ptr.write_dword(max_key_char_length)
# RegEnumKeyEx cannot be called twice to properly size the buffer
result = RegEnumKeyExW(key.hkey, index,
subkey_ptr, subkey_length_ptr,
FFI::Pointer::NULL, FFI::Pointer::NULL,
FFI::Pointer::NULL, filetime_ptr)
break if result == ERROR_NO_MORE_ITEMS
if result != FFI::ERROR_SUCCESS
msg = _("Failed to enumerate %{key} registry keys at index %{index}") % { key: key.keyname, index: index }
raise Puppet::Util::Windows::Error.new(msg, result)
end
filetime = FFI::WIN32::FILETIME.new(filetime_ptr)
subkey_length = subkey_length_ptr.read_dword
subkey = subkey_ptr.read_wide_string(subkey_length)
end
end
end
[subkey, filetime]
end
# max number of wide characters including NULL terminator
MAX_VALUE_CHAR_LENGTH = 16_383 + 1
def reg_enum_value(key, index, max_value_length = MAX_VALUE_CHAR_LENGTH)
subkey = nil
type = nil
data = nil
FFI::MemoryPointer.new(:dword) do |subkey_length_ptr|
FFI::MemoryPointer.new(:wchar, max_value_length) do |subkey_ptr|
# RegEnumValueW cannot be called twice to properly size the buffer
subkey_length_ptr.write_dword(max_value_length)
result = RegEnumValueW(key.hkey, index,
subkey_ptr, subkey_length_ptr,
FFI::Pointer::NULL, FFI::Pointer::NULL,
FFI::Pointer::NULL, FFI::Pointer::NULL)
break if result == ERROR_NO_MORE_ITEMS
if result != FFI::ERROR_SUCCESS
msg = _("Failed to enumerate %{key} registry values at index %{index}") % { key: key.keyname, index: index }
raise Puppet::Util::Windows::Error.new(msg, result)
end
subkey_length = subkey_length_ptr.read_dword
subkey = subkey_ptr.read_wide_string(subkey_length)
type, data = read(key, subkey_ptr)
end
end
[subkey, type, data]
end
def reg_query_info_key_max_lengths(key)
result = nil
FFI::MemoryPointer.new(:dword) do |max_subkey_name_length_ptr|
FFI::MemoryPointer.new(:dword) do |max_value_name_length_ptr|
status = RegQueryInfoKeyW(key.hkey,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
max_subkey_name_length_ptr, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL, max_value_name_length_ptr,
FFI::MemoryPointer::NULL, FFI::MemoryPointer::NULL,
FFI::MemoryPointer::NULL)
if status != FFI::ERROR_SUCCESS
msg = _("Failed to query registry %{key} for sizes") % { key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, status)
end
result = [
# Unicode characters *not* including trailing NULL
max_subkey_name_length_ptr.read_dword + 1,
max_value_name_length_ptr.read_dword + 1
]
end
end
result
end
# Read a registry value named name and return array of
# [ type, data ].
# When name is nil, the `default' value is read.
# type is value type. (see Win32::Registry::Constants module)
# data is value data, its class is:
# :REG_SZ, REG_EXPAND_SZ
# String
# :REG_MULTI_SZ
# Array of String
# :REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD
# Integer
# :REG_BINARY
# String (contains binary data)
#
# When rtype is specified, the value type must be included by
# rtype array, or TypeError is raised.
def read(key, name_ptr, *rtype)
result = nil
query_value_ex(key, name_ptr) do |type, data_ptr, byte_length|
unless rtype.empty? or rtype.include?(type)
raise TypeError, _("Type mismatch (expect %{rtype} but %{type} present)") % { rtype: rtype.inspect, type: type }
end
string_length = 0
# buffer is raw bytes, *not* chars - less a NULL terminator
string_length = (byte_length / WCHAR_SIZE) - 1 if byte_length > 0
begin
result = case type
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
[type, data_ptr.read_wide_string(string_length, Encoding::UTF_8, true)]
when Win32::Registry::REG_MULTI_SZ
[type, data_ptr.read_wide_string(string_length).split(/\0/)]
when Win32::Registry::REG_BINARY
[type, data_ptr.read_bytes(byte_length)]
when Win32::Registry::REG_DWORD
[type, data_ptr.read_dword]
when Win32::Registry::REG_DWORD_BIG_ENDIAN
[type, data_ptr.order(:big).read_dword]
when Win32::Registry::REG_QWORD
[type, data_ptr.read_qword]
else
raise TypeError, _("Type %{type} is not supported.") % { type: type }
end
rescue IndexError => ex
raise if ex.message !~ /^Memory access .* is out of bounds$/i
parent_key_name = key.parent ? "#{key.parent.keyname}\\" : ""
Puppet.warning _("A value in the registry key %{parent_key_name}%{key} is corrupt or invalid") % { parent_key_name: parent_key_name, key: key.keyname }
end
end
result
end
def query_value_ex(key, name_ptr, &block)
FFI::MemoryPointer.new(:dword) do |type_ptr|
FFI::MemoryPointer.new(:dword) do |length_ptr|
result = RegQueryValueExW(key.hkey, name_ptr,
FFI::Pointer::NULL, type_ptr,
FFI::Pointer::NULL, length_ptr)
# The call to RegQueryValueExW below is potentially unsafe:
# https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvalueexw
#
# "If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type,
# the string may not have been stored with the proper terminating
# null characters. Therefore, even if the function returns
# ERROR_SUCCESS, the application should ensure that the string is
# properly terminated before using it; otherwise, it may overwrite a
# buffer. (Note that REG_MULTI_SZ strings should have two
# terminating null characters.)"
#
# Since we don't know if the values will be properly null terminated,
# extend the buffer to guarantee we can append one or two wide null
# characters, without overwriting any data.
base_bytes_len = length_ptr.read_dword
pad_bytes_len = case type_ptr.read_dword
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
WCHAR_SIZE
when Win32::Registry::REG_MULTI_SZ
WCHAR_SIZE * 2
else
0
end
FFI::MemoryPointer.new(:byte, base_bytes_len + pad_bytes_len) do |buffer_ptr|
result = RegQueryValueExW(key.hkey, name_ptr,
FFI::Pointer::NULL, type_ptr,
buffer_ptr, length_ptr)
# Ensure buffer is null terminated with 1 or 2 wchar nulls, depending on the type
if result == FFI::ERROR_SUCCESS
case type_ptr.read_dword
when Win32::Registry::REG_SZ, Win32::Registry::REG_EXPAND_SZ
buffer_ptr.put_uint16(base_bytes_len, 0)
when Win32::Registry::REG_MULTI_SZ
buffer_ptr.put_uint16(base_bytes_len, 0)
buffer_ptr.put_uint16(base_bytes_len + WCHAR_SIZE, 0)
end
else
# buffer is raw bytes, *not* chars - less a NULL terminator
name_length = (name_ptr.size / WCHAR_SIZE) - 1 if name_ptr.size > 0
msg = _("Failed to read registry value %{value} at %{key}") % { value: name_ptr.read_wide_string(name_length), key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
# allows caller to use FFI MemoryPointer helpers to read / shape
yield [type_ptr.read_dword, buffer_ptr, length_ptr.read_dword]
end
end
end
end
def reg_delete_value(key, name)
result = 0
FFI::Pointer.from_string_to_wide_string(name) do |name_ptr|
result = RegDeleteValueW(key.hkey, name_ptr)
if result != FFI::ERROR_SUCCESS
msg = _("Failed to delete registry value %{name} at %{key}") % { name: name, key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
end
result
end
def reg_delete_key_ex(key, name, regsam = KEY64)
result = 0
FFI::Pointer.from_string_to_wide_string(name) do |name_ptr|
result = RegDeleteKeyExW(key.hkey, name_ptr, regsam, 0)
if result != FFI::ERROR_SUCCESS
msg = _("Failed to delete registry key %{name} at %{key}") % { name: name, key: key.keyname }
raise Puppet::Util::Windows::Error.new(msg, result)
end
end
result
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724862(v=vs.85).aspx
# LONG WINAPI RegEnumKeyEx(
# _In_ HKEY hKey,
# _In_ DWORD dwIndex,
# _Out_ LPTSTR lpName,
# _Inout_ LPDWORD lpcName,
# _Reserved_ LPDWORD lpReserved,
# _Inout_ LPTSTR lpClass,
# _Inout_opt_ LPDWORD lpcClass,
# _Out_opt_ PFILETIME lpftLastWriteTime
# );
ffi_lib :advapi32
attach_function_private :RegEnumKeyExW,
[:handle, :dword, :lpwstr, :lpdword, :lpdword, :lpwstr, :lpdword, :pointer], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724865(v=vs.85).aspx
# LONG WINAPI RegEnumValue(
# _In_ HKEY hKey,
# _In_ DWORD dwIndex,
# _Out_ LPTSTR lpValueName,
# _Inout_ LPDWORD lpcchValueName,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpType,
# _Out_opt_ LPBYTE lpData,
# _Inout_opt_ LPDWORD lpcbData
# );
ffi_lib :advapi32
attach_function_private :RegEnumValueW,
[:handle, :dword, :lpwstr, :lpdword, :lpdword, :lpdword, :lpbyte, :lpdword], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724911(v=vs.85).aspx
# LONG WINAPI RegQueryValueExW(
# _In_ HKEY hKey,
# _In_opt_ LPCTSTR lpValueName,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpType,
# _Out_opt_ LPBYTE lpData,
# _Inout_opt_ LPDWORD lpcbData
# );
ffi_lib :advapi32
attach_function_private :RegQueryValueExW,
[:handle, :lpcwstr, :lpdword, :lpdword, :lpbyte, :lpdword], :win32_long
# LONG WINAPI RegDeleteValue(
# _In_ HKEY hKey,
# _In_opt_ LPCTSTR lpValueName
# );
ffi_lib :advapi32
attach_function_private :RegDeleteValueW,
[:handle, :lpcwstr], :win32_long
# LONG WINAPI RegDeleteKeyEx(
# _In_ HKEY hKey,
# _In_ LPCTSTR lpSubKey,
# _In_ REGSAM samDesired,
# _Reserved_ DWORD Reserved
# );
ffi_lib :advapi32
attach_function_private :RegDeleteKeyExW,
[:handle, :lpcwstr, :win32_ulong, :dword], :win32_long
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724902(v=vs.85).aspx
# LONG WINAPI RegQueryInfoKey(
# _In_ HKEY hKey,
# _Out_opt_ LPTSTR lpClass,
# _Inout_opt_ LPDWORD lpcClass,
# _Reserved_ LPDWORD lpReserved,
# _Out_opt_ LPDWORD lpcSubKeys,
# _Out_opt_ LPDWORD lpcMaxSubKeyLen,
# _Out_opt_ LPDWORD lpcMaxClassLen,
# _Out_opt_ LPDWORD lpcValues,
# _Out_opt_ LPDWORD lpcMaxValueNameLen,
# _Out_opt_ LPDWORD lpcMaxValueLen,
# _Out_opt_ LPDWORD lpcbSecurityDescriptor,
# _Out_opt_ PFILETIME lpftLastWriteTime
# );
ffi_lib :advapi32
attach_function_private :RegQueryInfoKeyW,
[:handle, :lpwstr, :lpdword, :lpdword, :lpdword,
:lpdword, :lpdword, :lpdword, :lpdword, :lpdword,
:lpdword, :pointer], :win32_long
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/root_certs.rb | lib/puppet/util/windows/root_certs.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require_relative '../../../puppet/ssl/openssl_loader'
require 'ffi'
# Represents a collection of trusted root certificates.
#
# @api public
class Puppet::Util::Windows::RootCerts
include Enumerable
extend FFI::Library
def initialize(roots)
@roots = roots
end
# Enumerates each root certificate.
# @yieldparam cert [OpenSSL::X509::Certificate] each root certificate
# @api public
def each
@roots.each { |cert| yield cert }
end
# Returns a new instance.
# @return [Puppet::Util::Windows::RootCerts] object constructed from current root certificates
def self.instance
new(load_certs)
end
# Returns an array of root certificates.
#
# @return [Array<[OpenSSL::X509::Certificate]>] an array of root certificates
# @api private
def self.load_certs
certs = []
# This is based on a patch submitted to openssl:
# https://www.mail-archive.com/openssl-dev@openssl.org/msg26958.html
ptr = FFI::Pointer::NULL
store = CertOpenSystemStoreA(nil, "ROOT")
begin
while (ptr = CertEnumCertificatesInStore(store, ptr)) and !ptr.null?
context = CERT_CONTEXT.new(ptr)
cert_buf = context[:pbCertEncoded].read_bytes(context[:cbCertEncoded])
begin
certs << OpenSSL::X509::Certificate.new(cert_buf)
rescue => detail
Puppet.warning(_("Failed to import root certificate: %{detail}") % { detail: detail.inspect })
end
end
ensure
CertCloseStore(store, 0)
end
certs
end
ffi_convention :stdcall
# typedef void *HCERTSTORE;
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa377189(v=vs.85).aspx
# typedef struct _CERT_CONTEXT {
# DWORD dwCertEncodingType;
# BYTE *pbCertEncoded;
# DWORD cbCertEncoded;
# PCERT_INFO pCertInfo;
# HCERTSTORE hCertStore;
# } CERT_CONTEXT, *PCERT_CONTEXT;typedef const CERT_CONTEXT *PCCERT_CONTEXT;
class CERT_CONTEXT < FFI::Struct
layout(
:dwCertEncodingType, :dword,
:pbCertEncoded, :pointer,
:cbCertEncoded, :dword,
:pCertInfo, :pointer,
:hCertStore, :handle
)
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376560(v=vs.85).aspx
# HCERTSTORE
# WINAPI
# CertOpenSystemStoreA(
# __in_opt HCRYPTPROV_LEGACY hProv,
# __in LPCSTR szSubsystemProtocol
# );
# typedef ULONG_PTR HCRYPTPROV_LEGACY;
ffi_lib :crypt32
attach_function_private :CertOpenSystemStoreA, [:ulong_ptr, :lpcstr], :handle
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376050(v=vs.85).aspx
# PCCERT_CONTEXT
# WINAPI
# CertEnumCertificatesInStore(
# __in HCERTSTORE hCertStore,
# __in_opt PCCERT_CONTEXT pPrevCertContext
# );
ffi_lib :crypt32
attach_function_private :CertEnumCertificatesInStore, [:handle, :pointer], :pointer
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376026(v=vs.85).aspx
# BOOL
# WINAPI
# CertCloseStore(
# __in_opt HCERTSTORE hCertStore,
# __in DWORD dwFlags
# );
ffi_lib :crypt32
attach_function_private :CertCloseStore, [:handle, :dword], :win32_bool
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/principal.rb | lib/puppet/util/windows/principal.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows::SID
class Principal
extend FFI::Library
attr_reader :account, :sid_bytes, :sid, :domain, :domain_account, :account_type
def initialize(account, sid_bytes, sid, domain, account_type)
# This is only ever called from lookup_account_sid which has already
# removed the potential for passing in an account like host\user
@account = account
@sid_bytes = sid_bytes
@sid = sid
@domain = domain
@account_type = account_type
# When domain is available and it is a Domain principal, use domain only
# otherwise if domain is available then combine it with parsed account
# otherwise when the domain is not available, use the account value directly
# WinNT naming standard https://msdn.microsoft.com/en-us/library/windows/desktop/aa746534(v=vs.85).aspx
if domain && !domain.empty? && @account_type == :SidTypeDomain
@domain_account = @domain
elsif domain && !domain.empty?
@domain_account = "#{domain}\\#{@account}"
else
@domain_account = account
end
end
# added for backward compatibility
def ==(compare)
compare.is_a?(Puppet::Util::Windows::SID::Principal) &&
@sid_bytes == compare.sid_bytes
end
# returns authority qualified account name
# prefer to compare Principal instances with == operator or by #sid
def to_s
@domain_account
end
# = 8 + max sub identifiers (15) * 4
MAXIMUM_SID_BYTE_LENGTH = 68
ERROR_INVALID_PARAMETER = 87
ERROR_INSUFFICIENT_BUFFER = 122
def self.lookup_account_name(system_name = nil, sanitize = true, account_name)
account_name = sanitize_account_name(account_name) if sanitize
system_name_ptr = FFI::Pointer::NULL
begin
if system_name
system_name_wide = Puppet::Util::Windows::String.wide_string(system_name)
system_name_ptr = FFI::MemoryPointer.from_wide_string(system_name_wide)
end
FFI::MemoryPointer.from_string_to_wide_string(account_name) do |account_name_ptr|
FFI::MemoryPointer.new(:byte, MAXIMUM_SID_BYTE_LENGTH) do |sid_ptr|
FFI::MemoryPointer.new(:dword, 1) do |sid_length_ptr|
FFI::MemoryPointer.new(:dword, 1) do |domain_length_ptr|
FFI::MemoryPointer.new(:uint32, 1) do |name_use_enum_ptr|
sid_length_ptr.write_dword(MAXIMUM_SID_BYTE_LENGTH)
success = LookupAccountNameW(system_name_ptr, account_name_ptr, sid_ptr, sid_length_ptr,
FFI::Pointer::NULL, domain_length_ptr, name_use_enum_ptr)
last_error = FFI.errno
if success == FFI::WIN32_FALSE && last_error != ERROR_INSUFFICIENT_BUFFER
raise Puppet::Util::Windows::Error.new(_('Failed to call LookupAccountNameW with account: %{account_name}') % { account_name: account_name }, last_error)
end
FFI::MemoryPointer.new(:lpwstr, domain_length_ptr.read_dword) do |domain_ptr|
if LookupAccountNameW(system_name_ptr, account_name_ptr,
sid_ptr, sid_length_ptr,
domain_ptr, domain_length_ptr, name_use_enum_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _('Failed to call LookupAccountNameW with account: %{account_name}') % { account_name: account_name }
end
# with a SID returned, loop back through lookup_account_sid to retrieve official name
# necessary when accounts like . or '' are passed in
return lookup_account_sid(
system_name,
sid_ptr.read_bytes(sid_length_ptr.read_dword).unpack('C*')
)
end
end
end
end
end
end
ensure
system_name_ptr.free if system_name_ptr != FFI::Pointer::NULL
end
end
def self.lookup_account_sid(system_name = nil, sid_bytes)
system_name_ptr = FFI::Pointer::NULL
if sid_bytes.nil? || (!sid_bytes.is_a? Array) || (sid_bytes.length == 0)
# TRANSLATORS `lookup_account_sid` is a variable name and should not be translated
raise Puppet::Util::Windows::Error, _('Byte array for lookup_account_sid must not be nil and must be at least 1 byte long')
end
begin
if system_name
system_name_wide = Puppet::Util::Windows::String.wide_string(system_name)
system_name_ptr = FFI::MemoryPointer.from_wide_string(system_name_wide)
end
FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_ptr|
FFI::MemoryPointer.new(:dword, 1) do |name_length_ptr|
FFI::MemoryPointer.new(:dword, 1) do |domain_length_ptr|
FFI::MemoryPointer.new(:uint32, 1) do |name_use_enum_ptr|
sid_ptr.write_array_of_uchar(sid_bytes)
if Puppet::Util::Windows::SID.IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error.new(_('Byte array for lookup_account_sid is invalid: %{sid_bytes}') % { sid_bytes: sid_bytes }, ERROR_INVALID_PARAMETER)
end
success = LookupAccountSidW(system_name_ptr, sid_ptr, FFI::Pointer::NULL, name_length_ptr,
FFI::Pointer::NULL, domain_length_ptr, name_use_enum_ptr)
last_error = FFI.errno
if success == FFI::WIN32_FALSE && last_error != ERROR_INSUFFICIENT_BUFFER
raise Puppet::Util::Windows::Error.new(_('Failed to call LookupAccountSidW with bytes: %{sid_bytes}') % { sid_bytes: sid_bytes }, last_error)
end
FFI::MemoryPointer.new(:lpwstr, name_length_ptr.read_dword) do |name_ptr|
FFI::MemoryPointer.new(:lpwstr, domain_length_ptr.read_dword) do |domain_ptr|
if LookupAccountSidW(system_name_ptr, sid_ptr, name_ptr, name_length_ptr,
domain_ptr, domain_length_ptr, name_use_enum_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _('Failed to call LookupAccountSidW with bytes: %{sid_bytes}') % { sid_bytes: sid_bytes }
end
return new(
name_ptr.read_wide_string(name_length_ptr.read_dword),
sid_bytes,
Puppet::Util::Windows::SID.sid_ptr_to_string(sid_ptr),
domain_ptr.read_wide_string(domain_length_ptr.read_dword),
SID_NAME_USE[name_use_enum_ptr.read_uint32]
)
end
end
end
end
end
end
ensure
system_name_ptr.free if system_name_ptr != FFI::Pointer::NULL
end
end
# Sanitize the given account name for lookup to avoid known issues
def self.sanitize_account_name(account_name)
return account_name unless account_name.start_with?('APPLICATION PACKAGE AUTHORITY\\')
account_name.split('\\').last
end
private_class_method :sanitize_account_name
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379601(v=vs.85).aspx
SID_NAME_USE = enum(
:SidTypeUser, 1,
:SidTypeGroup, 2,
:SidTypeDomain, 3,
:SidTypeAlias, 4,
:SidTypeWellKnownGroup, 5,
:SidTypeDeletedAccount, 6,
:SidTypeInvalid, 7,
:SidTypeUnknown, 8,
:SidTypeComputer, 9,
:SidTypeLabel, 10
)
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379159(v=vs.85).aspx
# BOOL WINAPI LookupAccountName(
# _In_opt_ LPCTSTR lpSystemName,
# _In_ LPCTSTR lpAccountName,
# _Out_opt_ PSID Sid,
# _Inout_ LPDWORD cbSid,
# _Out_opt_ LPTSTR ReferencedDomainName,
# _Inout_ LPDWORD cchReferencedDomainName,
# _Out_ PSID_NAME_USE peUse
# );
ffi_lib :advapi32
attach_function_private :LookupAccountNameW,
[:lpcwstr, :lpcwstr, :pointer, :lpdword, :lpwstr, :lpdword, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379166(v=vs.85).aspx
# BOOL WINAPI LookupAccountSid(
# _In_opt_ LPCTSTR lpSystemName,
# _In_ PSID lpSid,
# _Out_opt_ LPTSTR lpName,
# _Inout_ LPDWORD cchName,
# _Out_opt_ LPTSTR lpReferencedDomainName,
# _Inout_ LPDWORD cchReferencedDomainName,
# _Out_ PSID_NAME_USE peUse
# );
ffi_lib :advapi32
attach_function_private :LookupAccountSidW,
[:lpcwstr, :pointer, :lpwstr, :lpdword, :lpwstr, :lpdword, :pointer], :win32_bool
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/string.rb | lib/puppet/util/windows/string.rb | # frozen_string_literal: true
module Puppet
module Util
module Windows
module String
def wide_string(str)
# if given a nil string, assume caller wants to pass a nil pointer to win32
return nil if str.nil?
str.encode('UTF-16LE')
end
module_function :wide_string
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/process.rb | lib/puppet/util/windows/process.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows/monkey_patches/process'
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows::Process
extend Puppet::FFI::Windows::Functions
include Puppet::FFI::Windows::Structs
extend Puppet::Util::Windows::String
WAIT_TIMEOUT = 0x102
WAIT_INTERVAL = 200
# https://docs.microsoft.com/en-us/windows/desktop/ProcThread/process-creation-flags
CREATE_NO_WINDOW = 0x08000000
# https://docs.microsoft.com/en-us/windows/desktop/ProcThread/process-security-and-access-rights
PROCESS_QUERY_INFORMATION = 0x0400
# https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
MAX_PATH_LENGTH = 32_767
def execute(command, arguments, stdin, stdout, stderr)
create_args = {
:command_line => command,
:startup_info => {
:stdin => stdin,
:stdout => stdout,
:stderr => stderr
},
:close_handles => false,
}
if arguments[:suppress_window]
create_args[:creation_flags] = CREATE_NO_WINDOW
end
if arguments[:cwd]
create_args[:cwd] = arguments[:cwd]
end
Process.create(create_args)
end
module_function :execute
def wait_process(handle)
while WaitForSingleObject(handle, WAIT_INTERVAL) == WAIT_TIMEOUT
sleep(0)
end
exit_status = -1
FFI::MemoryPointer.new(:dword, 1) do |exit_status_ptr|
if GetExitCodeProcess(handle, exit_status_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get child process exit code")
end
exit_status = exit_status_ptr.read_dword
# $CHILD_STATUS is not set when calling win32/process Process.create
# and since it's read-only, we can't set it. But we can execute a
# a shell that simply returns the desired exit status, which has the
# desired effect.
%x(#{ENV.fetch('COMSPEC', nil)} /c exit #{exit_status})
end
exit_status
end
module_function :wait_process
def get_current_process
# this pseudo-handle does not require closing per MSDN docs
GetCurrentProcess()
end
module_function :get_current_process
def open_process(desired_access, inherit_handle, process_id, &block)
phandle = nil
inherit = inherit_handle ? FFI::WIN32_TRUE : FFI::WIN32_FALSE
begin
phandle = OpenProcess(desired_access, inherit, process_id)
if phandle == FFI::Pointer::NULL_HANDLE
raise Puppet::Util::Windows::Error, "OpenProcess(#{desired_access.to_s(8)}, #{inherit}, #{process_id})"
end
yield phandle
ensure
FFI::WIN32.CloseHandle(phandle) if phandle
end
# phandle has had CloseHandle called against it, so nothing to return
nil
end
module_function :open_process
def open_process_token(handle, desired_access, &block)
token_handle = nil
begin
FFI::MemoryPointer.new(:handle, 1) do |token_handle_ptr|
result = OpenProcessToken(handle, desired_access, token_handle_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "OpenProcessToken(#{handle}, #{desired_access.to_s(8)}, #{token_handle_ptr})"
end
yield token_handle = token_handle_ptr.read_handle
end
token_handle
ensure
FFI::WIN32.CloseHandle(token_handle) if token_handle
end
# token_handle has had CloseHandle called against it, so nothing to return
nil
end
module_function :open_process_token
# Execute a block with the current process token
def with_process_token(access, &block)
handle = get_current_process
open_process_token(handle, access) do |token_handle|
yield token_handle
end
# all handles have been closed, so nothing to safely return
nil
end
module_function :with_process_token
def get_process_image_name_by_pid(pid)
image_name = ''.dup
Puppet::Util::Windows::Security.with_privilege(Puppet::Util::Windows::Security::SE_DEBUG_NAME) do
open_process(PROCESS_QUERY_INFORMATION, false, pid) do |phandle|
FFI::MemoryPointer.new(:dword, 1) do |exe_name_length_ptr|
# UTF is 2 bytes/char:
max_chars = MAX_PATH_LENGTH + 1
exe_name_length_ptr.write_dword(max_chars)
FFI::MemoryPointer.new(:wchar, max_chars) do |exe_name_ptr|
use_win32_path_format = 0
result = QueryFullProcessImageNameW(phandle, use_win32_path_format, exe_name_ptr, exe_name_length_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "QueryFullProcessImageNameW(phandle, #{use_win32_path_format}, " \
"exe_name_ptr, #{max_chars}"
end
image_name = exe_name_ptr.read_wide_string(exe_name_length_ptr.read_dword)
end
end
end
end
image_name
end
module_function :get_process_image_name_by_pid
def lookup_privilege_value(name, system_name = '', &block)
FFI::MemoryPointer.new(LUID.size) do |luid_ptr|
result = LookupPrivilegeValueW(
wide_string(system_name),
wide_string(name.to_s),
luid_ptr
)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "LookupPrivilegeValue(#{system_name}, #{name}, #{luid_ptr})"
end
yield LUID.new(luid_ptr)
end
# the underlying MemoryPointer for LUID is cleaned up by this point
nil
end
module_function :lookup_privilege_value
def get_token_information(token_handle, token_information, &block)
# to determine buffer size
FFI::MemoryPointer.new(:dword, 1) do |return_length_ptr|
result = GetTokenInformation(token_handle, token_information, nil, 0, return_length_ptr)
return_length = return_length_ptr.read_dword
if return_length <= 0
raise Puppet::Util::Windows::Error, "GetTokenInformation(#{token_handle}, #{token_information}, nil, 0, #{return_length_ptr})"
end
# re-call API with properly sized buffer for all results
FFI::MemoryPointer.new(return_length) do |token_information_buf|
result = GetTokenInformation(token_handle, token_information,
token_information_buf, return_length, return_length_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, "GetTokenInformation(#{token_handle}, #{token_information}, #{token_information_buf}, " \
"#{return_length}, #{return_length_ptr})"
end
yield token_information_buf
end
end
# GetTokenInformation buffer has been cleaned up by this point, nothing to return
nil
end
module_function :get_token_information
def parse_token_information_as_token_privileges(token_information_buf)
raw_privileges = TOKEN_PRIVILEGES.new(token_information_buf)
privileges = { :count => raw_privileges[:PrivilegeCount], :privileges => [] }
offset = token_information_buf + TOKEN_PRIVILEGES.offset_of(:Privileges)
privilege_ptr = FFI::Pointer.new(LUID_AND_ATTRIBUTES, offset)
# extract each instance of LUID_AND_ATTRIBUTES
0.upto(privileges[:count] - 1) do |i|
privileges[:privileges] << LUID_AND_ATTRIBUTES.new(privilege_ptr[i])
end
privileges
end
module_function :parse_token_information_as_token_privileges
def parse_token_information_as_token_elevation(token_information_buf)
TOKEN_ELEVATION.new(token_information_buf)
end
module_function :parse_token_information_as_token_elevation
TOKEN_ALL_ACCESS = 0xF01FF
ERROR_NO_SUCH_PRIVILEGE = 1313
def process_privilege_symlink?
privilege_symlink = false
handle = get_current_process
open_process_token(handle, TOKEN_ALL_ACCESS) do |token_handle|
lookup_privilege_value('SeCreateSymbolicLinkPrivilege') do |luid|
get_token_information(token_handle, :TokenPrivileges) do |token_info|
token_privileges = parse_token_information_as_token_privileges(token_info)
privilege_symlink = token_privileges[:privileges].any? { |p| p[:Luid].values == luid.values }
end
end
end
privilege_symlink
rescue Puppet::Util::Windows::Error => e
if e.code == ERROR_NO_SUCH_PRIVILEGE
false # pre-Vista
else
raise e
end
end
module_function :process_privilege_symlink?
TOKEN_QUERY = 0x0008
# Returns whether or not the owner of the current process is running
# with elevated security privileges.
#
# Only supported on Windows Vista or later.
#
def elevated_security?
# default / pre-Vista
elevated = false
handle = nil
begin
handle = get_current_process
open_process_token(handle, TOKEN_QUERY) do |token_handle|
get_token_information(token_handle, :TokenElevation) do |token_info|
token_elevation = parse_token_information_as_token_elevation(token_info)
# TokenIsElevated member of the TOKEN_ELEVATION struct
elevated = token_elevation[:TokenIsElevated] != 0
end
end
elevated
rescue Puppet::Util::Windows::Error => e
raise e if e.code != ERROR_NO_SUCH_PRIVILEGE
ensure
FFI::WIN32.CloseHandle(handle) if handle
end
end
module_function :elevated_security?
def windows_major_version
ver = 0
FFI::MemoryPointer.new(OSVERSIONINFO.size) do |os_version_ptr|
os_version = OSVERSIONINFO.new(os_version_ptr)
os_version[:dwOSVersionInfoSize] = OSVERSIONINFO.size
result = GetVersionExW(os_version_ptr)
if result == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("GetVersionEx failed")
end
ver = os_version[:dwMajorVersion]
end
ver
end
module_function :windows_major_version
# Returns a hash of the current environment variables encoded as UTF-8
# The memory block returned from GetEnvironmentStringsW is double-null terminated and the vars are paired as below;
# Var1=Value1\0
# Var2=Value2\0
# VarX=ValueX\0\0
# Note - Some env variable names start with '=' and are excluded from the return value
# Note - The env_ptr MUST be freed using the FreeEnvironmentStringsW function
# Note - There is no technical limitation to the size of the environment block returned.
# However a practical limit of 64K is used as no single environment variable can exceed 32KB
def get_environment_strings
env_ptr = GetEnvironmentStringsW()
# pass :invalid => :replace to the Ruby String#encode to use replacement characters
pairs = env_ptr.read_arbitrary_wide_string_up_to(65_534, :double_null, { :invalid => :replace })
.split(?\x00)
.reject { |env_str| env_str.nil? || env_str.empty? || env_str[0] == '=' }
.reject do |env_str|
# reject any string containing the Unicode replacement character
if env_str.include?("\uFFFD")
Puppet.warning(_("Discarding environment variable %{string} which contains invalid bytes") % { string: env_str })
true
end
end
.map { |env_pair| env_pair.split('=', 2) }
pairs.to_h
ensure
if env_ptr && !env_ptr.null?
if FreeEnvironmentStringsW(env_ptr) == FFI::WIN32_FALSE
Puppet.debug "FreeEnvironmentStringsW memory leak"
end
end
end
module_function :get_environment_strings
def set_environment_variable(name, val)
raise Puppet::Util::Windows::Error(_('environment variable name must not be nil or empty')) if !name || name.empty?
FFI::MemoryPointer.from_string_to_wide_string(name) do |name_ptr|
if val.nil?
if SetEnvironmentVariableW(name_ptr, FFI::MemoryPointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to remove environment variable: %{name}") % { name: name }
end
else
FFI::MemoryPointer.from_string_to_wide_string(val) do |val_ptr|
if SetEnvironmentVariableW(name_ptr, val_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to set environment variable: %{name}") % { name: name }
end
end
end
end
end
module_function :set_environment_variable
def get_system_default_ui_language
GetSystemDefaultUILanguage()
end
module_function :get_system_default_ui_language
# Returns whether or not the OS has the ability to set elevated
# token information.
#
# Returns true on Windows Vista or later, otherwise false
#
def supports_elevated_security?
windows_major_version >= 6
end
module_function :supports_elevated_security?
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/access_control_list.rb | lib/puppet/util/windows/access_control_list.rb | # frozen_string_literal: true
# Windows Access Control List
#
# Represents a list of access control entries (ACEs).
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa374872(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::AccessControlList
include Enumerable
ACCESS_ALLOWED_ACE_TYPE = 0x0
ACCESS_DENIED_ACE_TYPE = 0x1
# Construct an ACL.
#
# @param acl [Enumerable] A list of aces to copy from.
def initialize(acl = nil)
if acl
@aces = acl.map(&:dup)
else
@aces = []
end
end
# Enumerate each ACE in the list.
#
# @yieldparam ace [Hash] the ace
def each
@aces.each { |ace| yield ace }
end
# Allow the +sid+ to access a resource with the specified access +mask+.
#
# @param sid [String] The SID that the ACE is granting access to
# @param mask [int] The access mask granted to the SID
# @param flags [int] The flags assigned to the ACE, e.g. +INHERIT_ONLY_ACE+
def allow(sid, mask, flags = 0)
@aces << Puppet::Util::Windows::AccessControlEntry.new(sid, mask, flags, ACCESS_ALLOWED_ACE_TYPE)
end
# Deny the +sid+ access to a resource with the specified access +mask+.
#
# @param sid [String] The SID that the ACE is denying access to
# @param mask [int] The access mask denied to the SID
# @param flags [int] The flags assigned to the ACE, e.g. +INHERIT_ONLY_ACE+
def deny(sid, mask, flags = 0)
@aces << Puppet::Util::Windows::AccessControlEntry.new(sid, mask, flags, ACCESS_DENIED_ACE_TYPE)
end
# Reassign all ACEs currently assigned to +old_sid+ to +new_sid+ instead.
# If an ACE is inherited or is not assigned to +old_sid+, then it will
# be copied as-is to the new ACL, preserving its order within the ACL.
#
# @param old_sid [String] The old SID, e.g. 'S-1-5-18'
# @param new_sid [String] The new SID
# @return [AccessControlList] The copied ACL.
def reassign!(old_sid, new_sid)
new_aces = []
prepend_needed = false
aces_to_prepend = []
@aces.each do |ace|
new_ace = ace.dup
if ace.sid == old_sid
if ace.inherited?
# create an explicit ACE granting or denying the
# new_sid the rights that the inherited ACE
# granted or denied the old_sid. We mask off all
# flags except those affecting inheritance of the
# ACE we're creating.
inherit_mask = Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
explicit_ace = Puppet::Util::Windows::AccessControlEntry.new(new_sid, ace.mask, ace.flags & inherit_mask, ace.type)
aces_to_prepend << explicit_ace
else
new_ace.sid = new_sid
prepend_needed = old_sid == Puppet::Util::Windows::SID::LocalSystem
end
end
new_aces << new_ace
end
@aces = []
if prepend_needed
mask = Puppet::Util::Windows::File::STANDARD_RIGHTS_ALL | Puppet::Util::Windows::File::SPECIFIC_RIGHTS_ALL
ace = Puppet::Util::Windows::AccessControlEntry.new(
Puppet::Util::Windows::SID::LocalSystem,
mask
)
@aces << ace
end
@aces.concat(aces_to_prepend)
@aces.concat(new_aces)
end
def inspect
str = ''.dup
@aces.each do |ace|
str << " #{ace.inspect}\n"
end
str
end
def ==(other)
self.class == other.class &&
to_a == other.to_a
end
alias eql? ==
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/service.rb | lib/puppet/util/windows/service.rb | # coding: utf-8
# frozen_string_literal: true
require_relative '../../../puppet/ffi/windows'
module Puppet::Util::Windows
# This module is designed to provide an API between the windows system and puppet for
# service management.
#
# for an overview of the service state transitions see: https://docs.microsoft.com/en-us/windows/desktop/Services/service-status-transitions
module Service
extend Puppet::Util::Windows::String
include Puppet::FFI::Windows::Constants
extend Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Functions
# Returns true if the service exists, false otherwise.
#
# @param [String] service_name name of the service
def exists?(service_name)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |_|
true
end
rescue Puppet::Util::Windows::Error => e
return false if e.code == ERROR_SERVICE_DOES_NOT_EXIST
raise e
end
module_function :exists?
# Start a windows service
#
# @param [String] service_name name of the service to start
# @param optional [Integer] timeout the minumum number of seconds to wait before timing out
def start(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Starting the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = [
SERVICE_STOP_PENDING,
SERVICE_STOPPED,
SERVICE_START_PENDING
]
transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service|
if StartServiceW(service, 0, FFI::Pointer::NULL) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to start the service")
end
end
Puppet.debug _("Successfully started the %{service_name} service") % { service_name: service_name }
end
module_function :start
# Stop a windows service
#
# @param [String] service_name name of the service to stop
# @param optional [Integer] timeout the minumum number of seconds to wait before timing out
def stop(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Stopping the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = SERVICE_STATES.keys - [SERVICE_STOPPED]
transition_service_state(service_name, valid_initial_states, SERVICE_STOPPED, timeout) do |service|
send_service_control_signal(service, SERVICE_CONTROL_STOP)
end
Puppet.debug _("Successfully stopped the %{service_name} service") % { service_name: service_name }
end
module_function :stop
# Resume a paused windows service
#
# @param [String] service_name name of the service to resume
# @param optional [Integer] :timeout the minumum number of seconds to wait before timing out
def resume(service_name, timeout: DEFAULT_TIMEOUT)
Puppet.debug _("Resuming the %{service_name} service. Timeout set to: %{timeout} seconds") % { service_name: service_name, timeout: timeout }
valid_initial_states = [
SERVICE_PAUSE_PENDING,
SERVICE_PAUSED,
SERVICE_CONTINUE_PENDING
]
transition_service_state(service_name, valid_initial_states, SERVICE_RUNNING, timeout) do |service|
# The SERVICE_CONTROL_CONTINUE signal can only be sent when
# the service is in the SERVICE_PAUSED state
wait_on_pending_state(service, SERVICE_PAUSE_PENDING, timeout)
send_service_control_signal(service, SERVICE_CONTROL_CONTINUE)
end
Puppet.debug _("Successfully resumed the %{service_name} service") % { service_name: service_name }
end
module_function :resume
# Query the state of a service using QueryServiceStatusEx
#
# @param [string] service_name name of the service to query
# @return [string] the status of the service
def service_state(service_name)
state = nil
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_STATUS) do |service|
query_status(service) do |status|
state = SERVICE_STATES[status[:dwCurrentState]]
end
end
if state.nil?
raise Puppet::Error, _("Unknown Service state '%{current_state}' for '%{service_name}'") % { current_state: state.to_s, service_name: service_name }
end
state
end
module_function :service_state
# Query the configuration of a service using QueryServiceConfigW
# or QueryServiceConfig2W
#
# @param [String] service_name name of the service to query
# @return [QUERY_SERVICE_CONFIGW.struct] the configuration of the service
def service_start_type(service_name)
start_type = nil
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config(service) do |config|
start_type = SERVICE_START_TYPES[config[:dwStartType]]
end
end
# if the service has type AUTO_START, check if it's a delayed service
if start_type == :SERVICE_AUTO_START
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config2(service, SERVICE_CONFIG_DELAYED_AUTO_START_INFO) do |config|
return :SERVICE_DELAYED_AUTO_START if config[:fDelayedAutostart] == 1
end
end
end
if start_type.nil?
raise Puppet::Error, _("Unknown start type '%{start_type}' for '%{service_name}'") % { start_type: start_type.to_s, service_name: service_name }
end
start_type
end
module_function :service_start_type
# Query the configuration of a service using QueryServiceConfigW
# to find its current logon account
#
# @return [String] logon_account account currently set for the service's logon
# in the format "DOMAIN\Account" or ".\Account" if it's a local account
def logon_account(service_name)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_QUERY_CONFIG) do |service|
query_config(service) do |config|
return config[:lpServiceStartName].read_arbitrary_wide_string_up_to(Puppet::Util::Windows::ADSI::User::MAX_USERNAME_LENGTH)
end
end
end
module_function :logon_account
# Set the startup configuration of a windows service
#
# @param [String] service_name the name of the service to modify
# @param [Hash] options the configuration to be applied. Expected option keys:
# - [Integer] startup_type a code corresponding to a start type for
# windows service, see the "Service start type codes" section in the
# Puppet::Util::Windows::Service file for the list of available codes
# - [String] logon_account the account to be used by the service for logon
# - [String] logon_password the provided logon_account's password to be used by the service for logon
# - [Bool] delayed whether the service should be started with a delay
def set_startup_configuration(service_name, options: {})
options[:startup_type] = SERVICE_START_TYPES.key(options[:startup_type]) || SERVICE_NO_CHANGE
options[:logon_account] = wide_string(options[:logon_account]) || FFI::Pointer::NULL
options[:logon_password] = wide_string(options[:logon_password]) || FFI::Pointer::NULL
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service|
success = ChangeServiceConfigW(
service,
SERVICE_NO_CHANGE, # dwServiceType
options[:startup_type], # dwStartType
SERVICE_NO_CHANGE, # dwErrorControl
FFI::Pointer::NULL, # lpBinaryPathName
FFI::Pointer::NULL, # lpLoadOrderGroup
FFI::Pointer::NULL, # lpdwTagId
FFI::Pointer::NULL, # lpDependencies
options[:logon_account], # lpServiceStartName
options[:logon_password], # lpPassword
FFI::Pointer::NULL # lpDisplayName
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to update service configuration")
end
end
if options[:startup_type]
options[:delayed] ||= false
set_startup_mode_delayed(service_name, options[:delayed])
end
end
module_function :set_startup_configuration
# enumerate over all services in all states and return them as a hash
#
# @return [Hash] a hash containing services:
# { 'service name' => {
# 'display_name' => 'display name',
# 'service_status_process' => SERVICE_STATUS_PROCESS struct
# }
# }
def services
services = {}
open_scm(SC_MANAGER_ENUMERATE_SERVICE) do |scm|
size_required = 0
services_returned = 0
FFI::MemoryPointer.new(:dword) do |bytes_pointer|
FFI::MemoryPointer.new(:dword) do |svcs_ret_ptr|
FFI::MemoryPointer.new(:dword) do |resume_ptr|
resume_ptr.write_dword(0)
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
#
# return value will be false from this call, since it's designed
# to fail. Just ignore it
EnumServicesStatusExW(
scm,
:SC_ENUM_PROCESS_INFO,
ALL_SERVICE_TYPES,
SERVICE_STATE_ALL,
FFI::Pointer::NULL,
0,
bytes_pointer,
svcs_ret_ptr,
resume_ptr,
FFI::Pointer::NULL
)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |buffer_ptr|
resume_ptr.write_dword(0)
svcs_ret_ptr.write_dword(0)
success = EnumServicesStatusExW(
scm,
:SC_ENUM_PROCESS_INFO,
ALL_SERVICE_TYPES,
SERVICE_STATE_ALL,
buffer_ptr,
buffer_ptr.size,
bytes_pointer,
svcs_ret_ptr,
resume_ptr,
FFI::Pointer::NULL
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to fetch services")
end
# Now that the buffer is populated with services
# we pull the data from memory using pointer arithmetic:
# the number of services returned by the function is
# available to be read from svcs_ret_ptr, and we iterate
# that many times moving the cursor pointer the length of
# ENUM_SERVICE_STATUS_PROCESSW.size. This should iterate
# over the buffer and extract each struct.
services_returned = svcs_ret_ptr.read_dword
cursor_ptr = FFI::Pointer.new(ENUM_SERVICE_STATUS_PROCESSW, buffer_ptr)
0.upto(services_returned - 1) do |index|
service = ENUM_SERVICE_STATUS_PROCESSW.new(cursor_ptr[index])
services[service[:lpServiceName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX)] = {
:display_name => service[:lpDisplayName].read_arbitrary_wide_string_up_to(SERVICENAME_MAX),
:service_status_process => service[:ServiceStatusProcess]
}
end
end # buffer_ptr
end # resume_ptr
end # scvs_ret_ptr
end # bytes_ptr
end # open_scm
services
end
module_function :services
class << self
# @api private
# Opens a connection to the SCManager on windows then uses that
# handle to create a handle to a specific service in windows
# corresponding to service_name
#
# this function takes a block that executes within the context of
# the open service handler, and will close the service and SCManager
# handles once the block finishes
#
# @param [string] service_name the name of the service to open
# @param [Integer] scm_access code corresponding to the access type requested for the scm
# @param [Integer] service_access code corresponding to the access type requested for the service
# @yieldparam [:handle] service the windows native handle used to access
# the service
# @return the result of the block
def open_service(service_name, scm_access, service_access, &block)
service = FFI::Pointer::NULL_HANDLE
result = nil
open_scm(scm_access) do |scm|
service = OpenServiceW(scm, wide_string(service_name), service_access)
raise Puppet::Util::Windows::Error, _("Failed to open a handle to the service") if service == FFI::Pointer::NULL_HANDLE
result = yield service
end
result
ensure
CloseServiceHandle(service)
end
private :open_service
# @api private
#
# Opens a handle to the service control manager
#
# @param [Integer] scm_access code corresponding to the access type requested for the scm
def open_scm(scm_access, &block)
scm = OpenSCManagerW(FFI::Pointer::NULL, FFI::Pointer::NULL, scm_access)
raise Puppet::Util::Windows::Error, _("Failed to open a handle to the service control manager") if scm == FFI::Pointer::NULL_HANDLE
yield scm
ensure
CloseServiceHandle(scm)
end
private :open_scm
# @api private
# Transition the service to the specified state. The block should perform
# the actual transition.
#
# @param [String] service_name the name of the service to transition
# @param [[Integer]] valid_initial_states an array of valid states that the service can transition from
# @param [Integer] final_state the state that the service will transition to
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def transition_service_state(service_name, valid_initial_states, final_state, timeout, &block)
service_access = SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_QUERY_STATUS
open_service(service_name, SC_MANAGER_CONNECT, service_access) do |service|
query_status(service) do |status|
initial_state = status[:dwCurrentState]
# If the service is already in the final_state, then
# no further work needs to be done
if initial_state == final_state
Puppet.debug _("The service is already in the %{final_state} state. No further work needs to be done.") % { final_state: SERVICE_STATES[final_state] }
next
end
# Check that initial_state corresponds to a valid
# initial state
unless valid_initial_states.include?(initial_state)
valid_initial_states_str = valid_initial_states.map do |state|
SERVICE_STATES[state]
end.join(", ")
raise Puppet::Error, _("The service must be in one of the %{valid_initial_states} states to perform this transition. It is currently in the %{current_state} state.") % { valid_initial_states: valid_initial_states_str, current_state: SERVICE_STATES[initial_state] }
end
# Check if there's a pending transition to the final_state. If so, then wait for
# that transition to finish.
possible_pending_states = FINAL_STATES.keys.select do |pending_state|
# SERVICE_RUNNING has two pending states, SERVICE_START_PENDING and
# SERVICE_CONTINUE_PENDING. That is why we need the #select here
FINAL_STATES[pending_state] == final_state
end
if possible_pending_states.include?(initial_state)
Puppet.debug _("There is already a pending transition to the %{final_state} state for the %{service_name} service.") % { final_state: SERVICE_STATES[final_state], service_name: service_name }
wait_on_pending_state(service, initial_state, timeout)
next
end
# If we are in an unsafe pending state like SERVICE_START_PENDING
# or SERVICE_STOP_PENDING, then we want to wait for that pending
# transition to finish before transitioning the service state.
# The reason we do this is because SERVICE_START_PENDING is when
# the service thread is being created and initialized, while
# SERVICE_STOP_PENDING is when the service thread is being cleaned
# up and destroyed. Thus there is a chance that when the service is
# in either of these states, its service thread may not yet be ready
# to perform the state transition (it may not even exist).
if UNSAFE_PENDING_STATES.include?(initial_state)
Puppet.debug _("The service is in the %{pending_state} state, which is an unsafe pending state.") % { pending_state: SERVICE_STATES[initial_state] }
wait_on_pending_state(service, initial_state, timeout)
initial_state = FINAL_STATES[initial_state]
end
Puppet.debug _("Transitioning the %{service_name} service from %{initial_state} to %{final_state}") % { service_name: service_name, initial_state: SERVICE_STATES[initial_state], final_state: SERVICE_STATES[final_state] }
yield service
Puppet.debug _("Waiting for the transition to finish")
wait_on_state_transition(service, initial_state, final_state, timeout)
end
end
rescue => detail
raise Puppet::Error, _("Failed to transition the %{service_name} service to the %{final_state} state. Detail: %{detail}") % { service_name: service_name, final_state: SERVICE_STATES[final_state], detail: detail }, detail.backtrace
end
private :transition_service_state
# @api private
# perform QueryServiceStatusEx on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @return [SERVICE_STATUS_PROCESS struct] the result of the query
def query_status(service)
size_required = nil
status = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceStatusEx(
service,
:SC_STATUS_PROCESS_INFO,
FFI::Pointer::NULL,
0,
bytes_pointer
)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
status = SERVICE_STATUS_PROCESS.new(ssp_ptr)
success = QueryServiceStatusEx(
service,
:SC_STATUS_PROCESS_INFO,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query failed")
end
yield status
end
end
end
private :query_status
# @api private
# perform QueryServiceConfigW on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @return [QUERY_SERVICE_CONFIGW struct] the result of the query
def query_config(service, &block)
config = nil
size_required = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfigW to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceConfigW(service, FFI::Pointer::NULL, 0, bytes_pointer)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
config = QUERY_SERVICE_CONFIGW.new(ssp_ptr)
success = QueryServiceConfigW(
service,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query failed")
end
yield config
end
end
end
private :query_config
# @api private
# perform QueryServiceConfig2W on a windows service and return the
# result
#
# @param [:handle] service handle of the service to query
# @param [Integer] info_level the configuration information to be queried
# @return [QUERY_SERVICE_CONFIG2W struct] the result of the query
def query_config2(service, info_level, &block)
config = nil
size_required = nil
# Fetch the bytes of memory required to be allocated
# for QueryServiceConfig2W to return succesfully. This
# is done by sending NULL and 0 for the pointer and size
# respectively, letting the command fail, then reading the
# value of pcbBytesNeeded
FFI::MemoryPointer.new(:lpword) do |bytes_pointer|
# return value will be false from this call, since it's designed
# to fail. Just ignore it
QueryServiceConfig2W(service, info_level, FFI::Pointer::NULL, 0, bytes_pointer)
size_required = bytes_pointer.read_dword
FFI::MemoryPointer.new(size_required) do |ssp_ptr|
# We need to supply the appropriate struct to be created based on
# the info_level
case info_level
when SERVICE_CONFIG_DELAYED_AUTO_START_INFO
config = SERVICE_DELAYED_AUTO_START_INFO.new(ssp_ptr)
end
success = QueryServiceConfig2W(
service,
info_level,
ssp_ptr,
size_required,
bytes_pointer
)
if success == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Service query for %{parameter_name} failed") % { parameter_name: SERVICE_CONFIG_TYPES[info_level] }
end
yield config
end
end
end
private :query_config2
# @api private
# Sets an optional parameter on a service by calling
# ChangeServiceConfig2W
#
# @param [String] service_name name of service
# @param [Integer] change parameter to change
# @param [struct] value appropriate struct based on the parameter to change
def set_optional_parameter(service_name, change, value)
open_service(service_name, SC_MANAGER_CONNECT, SERVICE_CHANGE_CONFIG) do |service|
success = ChangeServiceConfig2W(
service,
change, # dwInfoLevel
value # lpInfo
)
if success == FFI::WIN32_FALSE
raise Puppet::Util.windows::Error, _("Failed to update service %{change} configuration") % { change: change }
end
end
end
private :set_optional_parameter
# @api private
# Controls the delayed auto-start setting of a service
#
# @param [String] service_name name of service
# @param [Bool] delayed whether the service should be started with a delay or not
def set_startup_mode_delayed(service_name, delayed)
delayed_start = SERVICE_DELAYED_AUTO_START_INFO.new
delayed_start[:fDelayedAutostart] = delayed
set_optional_parameter(service_name, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, delayed_start)
end
private :set_startup_mode_delayed
# @api private
# Sends a service control signal to a service
#
# @param [:handle] service handle to the service
# @param [Integer] signal the service control signal to send
def send_service_control_signal(service, signal)
FFI::MemoryPointer.new(SERVICE_STATUS.size) do |status_ptr|
status = SERVICE_STATUS.new(status_ptr)
if ControlService(service, signal, status) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to send the %{control_signal} signal to the service. Its current state is %{current_state}. Reason for failure:") % { control_signal: SERVICE_CONTROL_SIGNALS[signal], current_state: SERVICE_STATES[status[:dwCurrentState]] }
end
end
end
# @api private
# Waits for a service to transition from one state to
# another state.
#
# @param [:handle] service handle to the service to wait on
# @param [Integer] initial_state the state that the service is transitioning from.
# @param [Integer] final_state the state that the service is transitioning to
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def wait_on_state_transition(service, initial_state, final_state, timeout)
# Get the pending state for this transition. Note that SERVICE_RUNNING
# has two possible pending states, which is why we need this logic.
if final_state != SERVICE_RUNNING
pending_state = FINAL_STATES.key(final_state)
elsif initial_state == SERVICE_STOPPED
# SERVICE_STOPPED => SERVICE_RUNNING
pending_state = SERVICE_START_PENDING
else
# SERVICE_PAUSED => SERVICE_RUNNING
pending_state = SERVICE_CONTINUE_PENDING
end
# Wait for the transition to finish
state = nil
elapsed_time = 0
while elapsed_time <= timeout
query_status(service) do |status|
state = status[:dwCurrentState]
return if state == final_state
if state == pending_state
Puppet.debug _("The service transitioned to the %{pending_state} state.") % { pending_state: SERVICE_STATES[pending_state] }
wait_on_pending_state(service, pending_state, timeout)
return
end
sleep(1)
elapsed_time += 1
end
end
# Timed out while waiting for the transition to finish. Raise an error
# We can still use the state variable read from the FFI struct because
# FFI creates new Integer objects during an assignment of an integer value
# stored in an FFI struct. We verified that the '=' operater is safe
# from the freed memory since the new ruby object created during the
# assignment will remain in ruby memory and remain immutable and constant.
raise Puppet::Error, _("Timed out while waiting for the service to transition from %{initial_state} to %{final_state} OR from %{initial_state} to %{pending_state} to %{final_state}. The service's current state is %{current_state}.") % { initial_state: SERVICE_STATES[initial_state], final_state: SERVICE_STATES[final_state], pending_state: SERVICE_STATES[pending_state], current_state: SERVICE_STATES[state] }
end
private :wait_on_state_transition
# @api private
# Waits for a service to finish transitioning from
# a pending state. The service must be in the pending state
# before invoking this routine.
#
# @param [:handle] service handle to the service to wait on
# @param [Integer] pending_state the pending state
# @param [Integer] timeout the minumum number of seconds to wait before timing out
def wait_on_pending_state(service, pending_state, timeout)
final_state = FINAL_STATES[pending_state]
Puppet.debug _("Waiting for the pending transition to the %{final_state} state to finish.") % { final_state: SERVICE_STATES[final_state] }
elapsed_time = 0
last_checkpoint = -1
loop do
query_status(service) do |status|
state = status[:dwCurrentState]
checkpoint = status[:dwCheckPoint]
wait_hint = status[:dwWaitHint]
# Check if our service has finished transitioning to
# the final_state OR if an unexpected transition
# has occurred
return if state == final_state
unless state == pending_state
raise Puppet::Error, _("Unexpected transition to the %{current_state} state while waiting for the pending transition from %{pending_state} to %{final_state} to finish.") % { current_state: SERVICE_STATES[state], pending_state: SERVICE_STATES[pending_state], final_state: SERVICE_STATES[final_state] }
end
# Check if any progress has been made since our last sleep
# using the dwCheckPoint. If no progress has been made then
# check if we've timed out, and raise an error if so
if checkpoint > last_checkpoint
elapsed_time = 0
last_checkpoint = checkpoint
else
wait_hint = milliseconds_to_seconds(status[:dwWaitHint])
timeout = wait_hint < timeout ? timeout : wait_hint
if elapsed_time >= timeout
raise Puppet::Error, _("Timed out while waiting for the pending transition from %{pending_state} to %{final_state} to finish. The current state is %{current_state}.") % { pending_state: SERVICE_STATES[pending_state], final_state: SERVICE_STATES[final_state], current_state: SERVICE_STATES[state] }
end
end
wait_time = wait_hint_to_wait_time(wait_hint)
# Wait a bit before rechecking the service's state
sleep(wait_time)
elapsed_time += wait_time
end
end
end
private :wait_on_pending_state
# @api private
#
# create a usable wait time to wait between querying the service.
#
# @param [Integer] wait_hint the wait hint of a service in milliseconds
# @return [Integer] the time to wait in seconds between querying the service
def wait_hint_to_wait_time(wait_hint)
# Wait 1/10th the wait_hint, but no less than 1 and
# no more than 10 seconds
wait_time = milliseconds_to_seconds(wait_hint) / 10;
wait_time = 1 if wait_time < 1
wait_time = 10 if wait_time > 10
wait_time
end
private :wait_hint_to_wait_time
# @api private
#
# process the wait hint listed by a service to something
# usable by ruby sleep
#
# @param [Integer] wait_hint the wait hint of a service in milliseconds
# @return [Integer] wait_hint in seconds
def milliseconds_to_seconds(wait_hint)
wait_hint / 1000;
end
private :milliseconds_to_seconds
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/access_control_entry.rb | lib/puppet/util/windows/access_control_entry.rb | # frozen_string_literal: true
# Windows Access Control Entry
#
# Represents an access control entry, which grants or denies a subject,
# identified by a SID, rights to a securable object.
#
# @see https://msdn.microsoft.com/en-us/library/windows/desktop/aa374868(v=vs.85).aspx
# @api private
class Puppet::Util::Windows::AccessControlEntry
require_relative '../../../puppet/util/windows/security'
include Puppet::Util::Windows::SID
attr_accessor :sid
attr_reader :mask, :flags, :type
OBJECT_INHERIT_ACE = 0x1
CONTAINER_INHERIT_ACE = 0x2
NO_PROPAGATE_INHERIT_ACE = 0x4
INHERIT_ONLY_ACE = 0x8
INHERITED_ACE = 0x10
ACCESS_ALLOWED_ACE_TYPE = 0x0
ACCESS_DENIED_ACE_TYPE = 0x1
def initialize(sid, mask, flags = 0, type = ACCESS_ALLOWED_ACE_TYPE)
@sid = sid
@mask = mask
@flags = flags
@type = type
end
# Returns true if this ACE is inherited from a parent. If false,
# then the ACE is set directly on the object to which it refers.
#
# @return [Boolean] true if the ACE is inherited
def inherited?
(@flags & INHERITED_ACE) == INHERITED_ACE
end
# Returns true if this ACE only applies to children of the object.
# If false, it applies to the object.
#
# @return [Boolean] true if the ACE only applies to children and
# not the object itself.
def inherit_only?
(@flags & INHERIT_ONLY_ACE) == INHERIT_ONLY_ACE
end
# Returns true if this ACE applies to child directories.
#
# @return [Boolean] true if the ACE applies to child directories
def container_inherit?
(@flags & CONTAINER_INHERIT_ACE) == CONTAINER_INHERIT_ACE
end
# Returns true if this ACE applies to child files.
#
# @return [Boolean] true if the ACE applies to child files.
def object_inherit?
(@flags & OBJECT_INHERIT_ACE) == OBJECT_INHERIT_ACE
end
def inspect
inheritance = ''.dup
inheritance << '(I)' if inherited?
inheritance << '(OI)' if object_inherit?
inheritance << '(CI)' if container_inherit?
inheritance << '(IO)' if inherit_only?
left = "#{sid_to_name(sid)}:#{inheritance}"
left = left.ljust(45)
"#{left} 0x#{mask.to_s(16)}"
end
# Returns true if this ACE is equal to +other+
def ==(other)
self.class == other.class &&
sid == other.sid &&
mask == other.mask &&
flags == other.flags &&
type == other.type
end
alias eql? ==
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/error.rb | lib/puppet/util/windows/error.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require_relative '../../../puppet/error'
# represents an error resulting from a Win32 error code
class Puppet::Util::Windows::Error < Puppet::Error
require 'ffi'
extend FFI::Library
attr_reader :code
# NOTE: FFI.errno only works properly when prior Win32 calls have been made
# through FFI bindings. Calls made through Win32API do not have their error
# codes captured by FFI.errno
def initialize(message, code = FFI.errno, original = nil)
super(message + ": #{self.class.format_error_code(code)}", original)
@code = code
end
# Helper method that wraps FormatMessage that returns a human readable string.
def self.format_error_code(code)
# specifying 0 will look for LANGID in the following order
# 1.Language neutral
# 2.Thread LANGID, based on the thread's locale value
# 3.User default LANGID, based on the user's default locale value
# 4.System default LANGID, based on the system default locale value
# 5.US English
dwLanguageId = 0
flags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ARGUMENT_ARRAY |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_MAX_WIDTH_MASK
error_string = ''.dup
# this pointer actually points to a :lpwstr (pointer) since we're letting Windows allocate for us
FFI::MemoryPointer.new(:pointer, 1) do |buffer_ptr|
length = FormatMessageW(flags, FFI::Pointer::NULL, code, dwLanguageId,
buffer_ptr, 0, FFI::Pointer::NULL)
if length == FFI::WIN32_FALSE
# can't raise same error type here or potentially recurse infinitely
raise Puppet::Error, _("FormatMessageW could not format code %{code}") % { code: code }
end
# returns an FFI::Pointer with autorelease set to false, which is what we want
buffer_ptr.read_win32_local_pointer do |wide_string_ptr|
if wide_string_ptr.null?
raise Puppet::Error, _("FormatMessageW failed to allocate buffer for code %{code}") % { code: code }
end
error_string = wide_string_ptr.read_wide_string(length)
end
end
error_string
end
ERROR_FILE_NOT_FOUND = 2
ERROR_ACCESS_DENIED = 5
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000
FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms679351(v=vs.85).aspx
# DWORD WINAPI FormatMessage(
# _In_ DWORD dwFlags,
# _In_opt_ LPCVOID lpSource,
# _In_ DWORD dwMessageId,
# _In_ DWORD dwLanguageId,
# _Out_ LPTSTR lpBuffer,
# _In_ DWORD nSize,
# _In_opt_ va_list *Arguments
# );
# NOTE: since we're not preallocating the buffer, use a :pointer for lpBuffer
ffi_lib :kernel32
attach_function_private :FormatMessageW,
[:dword, :lpcvoid, :dword, :dword, :pointer, :dword, :pointer], :dword
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/adsi.rb | lib/puppet/util/windows/adsi.rb | # frozen_string_literal: true
module Puppet::Util::Windows::ADSI
require 'ffi'
# https://docs.microsoft.com/en-us/windows/win32/api/dsrole/ne-dsrole-dsrole_machine_role
STANDALONE_WORKSTATION = 0
MEMBER_WORKSTATION = 1
STANDALONE_SERVER = 2
MEMBER_SERVER = 3
BACKUP_DOMAIN_CONTROLLER = 4
PRIMARY_DOMAIN_CONTROLLER = 5
DOMAIN_ROLES = {
STANDALONE_WORKSTATION => :STANDALONE_WORKSTATION,
MEMBER_WORKSTATION => :MEMBER_WORKSTATION,
STANDALONE_SERVER => :STANDALONE_SERVER,
MEMBER_SERVER => :MEMBER_SERVER,
BACKUP_DOMAIN_CONTROLLER => :BACKUP_DOMAIN_CONTROLLER,
PRIMARY_DOMAIN_CONTROLLER => :PRIMARY_DOMAIN_CONTROLLER,
}
class << self
extend FFI::Library
def connectable?(uri)
!!connect(uri)
rescue
false
end
def connect(uri)
WIN32OLE.connect(uri)
rescue WIN32OLERuntimeError => e
raise Puppet::Error.new(_("ADSI connection error: %{e}") % { e: e }, e)
end
def create(name, resource_type)
Puppet::Util::Windows::ADSI.connect(computer_uri).Create(resource_type, name)
end
def delete(name, resource_type)
Puppet::Util::Windows::ADSI.connect(computer_uri).Delete(resource_type, name)
end
# taken from winbase.h
MAX_COMPUTERNAME_LENGTH = 31
def computer_name
unless @computer_name
max_length = MAX_COMPUTERNAME_LENGTH + 1 # NULL terminated
FFI::MemoryPointer.new(max_length * 2) do |buffer| # wide string
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length) # length in TCHARs
if GetComputerNameW(buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get computer name")
end
@computer_name = buffer.read_wide_string(buffer_size.read_dword)
end
end
end
@computer_name
end
def computer_uri(host = '.')
"WinNT://#{host}"
end
def wmi_resource_uri(host = '.')
"winmgmts:{impersonationLevel=impersonate}!//#{host}/root/cimv2"
end
# This method should *only* be used to generate WinNT://<SID> style monikers
# used for IAdsGroup::Add / IAdsGroup::Remove. These URIs are not usable
# to resolve an account with WIN32OLE.connect
# Valid input is a SID::Principal, S-X-X style SID string or any valid
# account name with or without domain prefix
# @api private
def sid_uri_safe(sid)
return sid_uri(sid) if sid.is_a?(Puppet::Util::Windows::SID::Principal)
begin
sid = Puppet::Util::Windows::SID.name_to_principal(sid)
sid_uri(sid)
rescue Puppet::Util::Windows::Error, Puppet::Error
nil
end
end
# This method should *only* be used to generate WinNT://<SID> style monikers
# used for IAdsGroup::Add / IAdsGroup::Remove. These URIs are not useable
# to resolve an account with WIN32OLE.connect
def sid_uri(sid)
raise Puppet::Error, _("Must use a valid SID::Principal") unless sid.is_a?(Puppet::Util::Windows::SID::Principal)
"WinNT://#{sid.sid}"
end
def uri(resource_name, resource_type, host = '.')
"#{computer_uri(host)}/#{resource_name},#{resource_type}"
end
def wmi_connection
connect(wmi_resource_uri)
end
def execquery(query)
wmi_connection.execquery(query)
end
def domain_role
unless @domain_role
query_result = Puppet::Util::Windows::ADSI.execquery('select DomainRole from Win32_ComputerSystem').to_enum.first
@domain_role = DOMAIN_ROLES[query_result.DomainRole] if query_result
end
@domain_role
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724295(v=vs.85).aspx
# BOOL WINAPI GetComputerName(
# _Out_ LPTSTR lpBuffer,
# _Inout_ LPDWORD lpnSize
# );
ffi_lib :kernel32
attach_function_private :GetComputerNameW,
[:lpwstr, :lpdword], :win32_bool
end
# Common base class shared by the User and Group
# classes below.
class ADSIObject
extend Enumerable
# Define some useful class-level methods
class << self
# Is either 'user' or 'group'
attr_reader :object_class
def localized_domains
@localized_domains ||= [
# localized version of BUILTIN
# for instance VORDEFINIERT on German Windows
Puppet::Util::Windows::SID.sid_to_name('S-1-5-32').upcase,
# localized version of NT AUTHORITY (can't use S-1-5)
# for instance AUTORITE NT on French Windows
Puppet::Util::Windows::SID.name_to_principal('SYSTEM').domain.upcase
]
end
def uri(name, host = '.')
host = '.' if (localized_domains << Socket.gethostname.upcase).include?(host.upcase)
Puppet::Util::Windows::ADSI.uri(name, @object_class, host)
end
def parse_name(name)
if name =~ %r{/}
raise Puppet::Error, _("Value must be in DOMAIN\\%{object_class} style syntax") % { object_class: @object_class }
end
matches = name.scan(/((.*)\\)?(.*)/)
domain = matches[0][1] || '.'
account = matches[0][2]
[account, domain]
end
# returns Puppet::Util::Windows::SID::Principal[]
# may contain objects that represent unresolvable SIDs
def get_sids(adsi_child_collection)
sids = []
adsi_child_collection.each do |m|
sids << Puppet::Util::Windows::SID.ads_to_principal(m)
rescue Puppet::Util::Windows::Error => e
case e.code
when Puppet::Util::Windows::SID::ERROR_TRUSTED_RELATIONSHIP_FAILURE, Puppet::Util::Windows::SID::ERROR_TRUSTED_DOMAIN_FAILURE
sids << Puppet::Util::Windows::SID.unresolved_principal(m.name, m.sid)
else
raise e
end
end
sids
end
def name_sid_hash(names, allow_unresolved = false)
return {} if names.nil? || names.empty?
sids = names.map do |name|
sid = Puppet::Util::Windows::SID.name_to_principal(name, allow_unresolved)
raise Puppet::Error, _("Could not resolve name: %{name}") % { name: name } unless sid
[sid.sid, sid]
end
sids.to_h
end
def delete(name)
Puppet::Util::Windows::ADSI.delete(name, @object_class)
end
def exists?(name_or_sid)
well_known = false
if (sid = Puppet::Util::Windows::SID.name_to_principal(name_or_sid))
# Examples of SidType include SidTypeUser, SidTypeGroup
if sid.account_type == "SidType#{@object_class.capitalize}".to_sym
# Check if we're getting back a local user when domain-joined
return true unless [:MEMBER_WORKSTATION, :MEMBER_SERVER].include?(Puppet::Util::Windows::ADSI.domain_role)
# The resource domain and the computer name are not always case-matching
return sid.domain.casecmp(Puppet::Util::Windows::ADSI.computer_name) == 0
end
# 'well known group' is special as it can be a group like Everyone OR a user like SYSTEM
# so try to resolve it
# https://msdn.microsoft.com/en-us/library/cc234477.aspx
well_known = sid.account_type == :SidTypeWellKnownGroup
return false if sid.account_type != :SidTypeAlias && !well_known
name_or_sid = "#{sid.domain}\\#{sid.account}"
end
object = Puppet::Util::Windows::ADSI.connect(uri(*parse_name(name_or_sid)))
object.Class.downcase == @object_class
rescue
# special accounts like SYSTEM or special groups like Authenticated Users cannot
# resolve via monikers like WinNT://./SYSTEM,user or WinNT://./Authenticated Users,group
# -- they'll fail to connect. thus, given a validly resolved SID, this failure is
# ambiguous as it may indicate either a group like Service or an account like SYSTEM
well_known
end
def list_all
raise NotImplementedError, _("Subclass must implement class-level method 'list_all'!")
end
def each(&block)
objects = []
list_all.each do |o|
# Setting WIN32OLE.codepage in the microsoft_windows feature ensures
# values are returned as UTF-8
objects << new(o.name)
end
objects.each(&block)
end
end
attr_reader :name
def initialize(name, native_object = nil)
@name = name
@native_object = native_object
end
def object_class
self.class.object_class
end
def uri
self.class.uri(sid.account, sid.domain)
end
def native_object
@native_object ||= Puppet::Util::Windows::ADSI.connect(self.class.uri(*self.class.parse_name(name)))
end
def sid
@sid ||= Puppet::Util::Windows::SID.octet_string_to_principal(native_object.objectSID)
end
def [](attribute)
# Setting WIN32OLE.codepage ensures values are returned as UTF-8
native_object.Get(attribute)
end
def []=(attribute, value)
native_object.Put(attribute, value)
end
def commit
begin
native_object.SetInfo
rescue WIN32OLERuntimeError => e
# ERROR_BAD_USERNAME 2202L from winerror.h
if e.message =~ /8007089A/m
raise Puppet::Error, _("Puppet is not able to create/delete domain %{object_class} objects with the %{object_class} resource.") % { object_class: object_class }
end
raise Puppet::Error.new(_("%{object_class} update failed: %{error}") % { object_class: object_class.capitalize, error: e }, e)
end
self
end
end
class User < ADSIObject
extend FFI::Library
require_relative '../../../puppet/util/windows/sid'
# https://msdn.microsoft.com/en-us/library/aa746340.aspx
# IADsUser interface
@object_class = 'user'
class << self
def list_all
Puppet::Util::Windows::ADSI.execquery('select name from win32_useraccount where localaccount = "TRUE"')
end
def logon(name, password)
Puppet::Util::Windows::User.password_is?(name, password)
end
def create(name)
# Windows error 1379: The specified local group already exists.
raise Puppet::Error, _("Cannot create user if group '%{name}' exists.") % { name: name } if Puppet::Util::Windows::ADSI::Group.exists? name
new(name, Puppet::Util::Windows::ADSI.create(name, @object_class))
end
end
def password_is?(password)
self.class.logon(name, password)
end
def add_flag(flag_name, value)
flag = begin
native_object.Get(flag_name)
rescue
0
end
native_object.Put(flag_name, flag | value)
commit
end
def password=(password)
unless password.nil?
native_object.SetPassword(password)
commit
end
fADS_UF_DONT_EXPIRE_PASSWD = 0x10000
add_flag("UserFlags", fADS_UF_DONT_EXPIRE_PASSWD)
end
def groups
# https://msdn.microsoft.com/en-us/library/aa746342.aspx
# WIN32OLE objects aren't enumerable, so no map
groups = []
# Setting WIN32OLE.codepage ensures values are returned as UTF-8
begin
native_object.Groups.each { |g| groups << g.Name }
rescue
nil
end
groups
end
def add_to_groups(*group_names)
group_names.each do |group_name|
Puppet::Util::Windows::ADSI::Group.new(group_name).add_member_sids(sid)
end
end
alias add_to_group add_to_groups
def remove_from_groups(*group_names)
group_names.each do |group_name|
Puppet::Util::Windows::ADSI::Group.new(group_name).remove_member_sids(sid)
end
end
alias remove_from_group remove_from_groups
def add_group_sids(*sids)
group_names = sids.map(&:domain_account)
add_to_groups(*group_names)
end
def remove_group_sids(*sids)
group_names = sids.map(&:domain_account)
remove_from_groups(*group_names)
end
def group_sids
self.class.get_sids(native_object.Groups)
end
# TODO: This code's pretty similar to set_members in the Group class. Would be nice
# to refactor them into the ADSIObject class at some point. This was not done originally
# because these use different methods to do stuff that are also aliased to other methods,
# so the shared code isn't exactly a 1:1 mapping.
def set_groups(desired_groups, minimum = true)
return if desired_groups.nil?
desired_groups = desired_groups.split(',').map(&:strip)
current_hash = group_sids.to_h { |sid| [sid.sid, sid] }
desired_hash = self.class.name_sid_hash(desired_groups)
# First we add the user to all the groups it should be in but isn't
unless desired_groups.empty?
groups_to_add = (desired_hash.keys - current_hash.keys).map { |sid| desired_hash[sid] }
add_group_sids(*groups_to_add)
end
# Then we remove the user from all groups it is in but shouldn't be, if
# that's been requested
unless minimum
if desired_hash.empty?
groups_to_remove = current_hash.values
else
groups_to_remove = (current_hash.keys - desired_hash.keys).map { |sid| current_hash[sid] }
end
remove_group_sids(*groups_to_remove)
end
end
# Declare all of the available user flags on the system. Note that
# ADS_UF is read as ADS_UserFlag
# https://docs.microsoft.com/en-us/windows/desktop/api/iads/ne-iads-ads_user_flag
# and
# https://support.microsoft.com/en-us/help/305144/how-to-use-the-useraccountcontrol-flags-to-manipulate-user-account-pro
# for the flag values.
ADS_USERFLAGS = {
ADS_UF_SCRIPT: 0x0001,
ADS_UF_ACCOUNTDISABLE: 0x0002,
ADS_UF_HOMEDIR_REQUIRED: 0x0008,
ADS_UF_LOCKOUT: 0x0010,
ADS_UF_PASSWD_NOTREQD: 0x0020,
ADS_UF_PASSWD_CANT_CHANGE: 0x0040,
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: 0x0080,
ADS_UF_TEMP_DUPLICATE_ACCOUNT: 0x0100,
ADS_UF_NORMAL_ACCOUNT: 0x0200,
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: 0x0800,
ADS_UF_WORKSTATION_TRUST_ACCOUNT: 0x1000,
ADS_UF_SERVER_TRUST_ACCOUNT: 0x2000,
ADS_UF_DONT_EXPIRE_PASSWD: 0x10000,
ADS_UF_MNS_LOGON_ACCOUNT: 0x20000,
ADS_UF_SMARTCARD_REQUIRED: 0x40000,
ADS_UF_TRUSTED_FOR_DELEGATION: 0x80000,
ADS_UF_NOT_DELEGATED: 0x100000,
ADS_UF_USE_DES_KEY_ONLY: 0x200000,
ADS_UF_DONT_REQUIRE_PREAUTH: 0x400000,
ADS_UF_PASSWORD_EXPIRED: 0x800000,
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: 0x1000000
}
def userflag_set?(flag)
flag_value = ADS_USERFLAGS[flag] || 0
!(self['UserFlags'] & flag_value).zero?
end
# Common helper for set_userflags and unset_userflags.
#
# @api private
def op_userflags(*flags, &block)
# Avoid an unnecessary set + commit operation.
return if flags.empty?
unrecognized_flags = flags.reject { |flag| ADS_USERFLAGS.keys.include?(flag) }
unless unrecognized_flags.empty?
raise ArgumentError, _("Unrecognized ADS UserFlags: %{unrecognized_flags}") % { unrecognized_flags: unrecognized_flags.join(', ') }
end
self['UserFlags'] = flags.inject(self['UserFlags'], &block)
end
def set_userflags(*flags)
op_userflags(*flags) { |userflags, flag| userflags | ADS_USERFLAGS[flag] }
end
def unset_userflags(*flags)
op_userflags(*flags) { |userflags, flag| userflags & ~ADS_USERFLAGS[flag] }
end
def disabled?
userflag_set?(:ADS_UF_ACCOUNTDISABLE)
end
def locked_out?
# Note that the LOCKOUT flag is known to be inaccurate when using the
# LDAP IADsUser provider, but this class consistently uses the WinNT
# provider, which is expected to be accurate.
userflag_set?(:ADS_UF_LOCKOUT)
end
def expired?
expires = native_object.Get('AccountExpirationDate')
expires && expires < Time.now
rescue WIN32OLERuntimeError => e
# This OLE error code indicates the property can't be found in the cache
raise e unless e.message =~ /8000500D/m
false
end
# UNLEN from lmcons.h - https://stackoverflow.com/a/2155176
MAX_USERNAME_LENGTH = 256
def self.current_user_name
user_name = ''.dup
max_length = MAX_USERNAME_LENGTH + 1 # NULL terminated
FFI::MemoryPointer.new(max_length * 2) do |buffer| # wide string
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length) # length in TCHARs
if GetUserNameW(buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to get user name")
end
# buffer_size includes trailing NULL
user_name = buffer.read_wide_string(buffer_size.read_dword - 1)
end
end
user_name
end
# https://docs.microsoft.com/en-us/windows/win32/api/secext/ne-secext-extended_name_format
NameUnknown = 0
NameFullyQualifiedDN = 1
NameSamCompatible = 2
NameDisplay = 3
NameUniqueId = 6
NameCanonical = 7
NameUserPrincipal = 8
NameCanonicalEx = 9
NameServicePrincipal = 10
NameDnsDomain = 12
NameGivenName = 13
NameSurname = 14
def self.current_user_name_with_format(format)
user_name = ''.dup
max_length = 1024
FFI::MemoryPointer.new(:lpwstr, max_length * 2 + 1) do |buffer|
FFI::MemoryPointer.new(:dword, 1) do |buffer_size|
buffer_size.write_dword(max_length + 1)
if GetUserNameExW(format.to_i, buffer, buffer_size) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error.new(_("Failed to get user name"), FFI.errno)
end
user_name = buffer.read_wide_string(buffer_size.read_dword).chomp
end
end
user_name
end
def self.current_sam_compatible_user_name
current_user_name_with_format(NameSamCompatible)
end
def self.current_user_sid
Puppet::Util::Windows::SID.name_to_principal(current_user_name)
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).aspx
# BOOL WINAPI GetUserName(
# _Out_ LPTSTR lpBuffer,
# _Inout_ LPDWORD lpnSize
# );
ffi_lib :advapi32
attach_function_private :GetUserNameW,
[:lpwstr, :lpdword], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/secext/nf-secext-getusernameexa
# BOOLEAN SEC_ENTRY GetUserNameExA(
# EXTENDED_NAME_FORMAT NameFormat,
# LPSTR lpNameBuffer,
# PULONG nSize
# );type
ffi_lib :secur32
attach_function_private :GetUserNameExW, [:uint16, :lpwstr, :pointer], :win32_bool
end
class UserProfile
def self.delete(sid)
Puppet::Util::Windows::ADSI.wmi_connection.Delete("Win32_UserProfile.SID='#{sid}'")
rescue WIN32OLERuntimeError => e
# https://social.technet.microsoft.com/Forums/en/ITCG/thread/0f190051-ac96-4bf1-a47f-6b864bfacee5
# Prior to Vista SP1, there's no built-in way to programmatically
# delete user profiles (except for delprof.exe). So try to delete
# but warn if we fail
raise e unless e.message.include?('80041010')
Puppet.warning _("Cannot delete user profile for '%{sid}' prior to Vista SP1") % { sid: sid }
end
end
class Group < ADSIObject
# https://msdn.microsoft.com/en-us/library/aa706021.aspx
# IADsGroup interface
@object_class = 'group'
class << self
def list_all
Puppet::Util::Windows::ADSI.execquery('select name from win32_group where localaccount = "TRUE"')
end
def create(name)
# Windows error 2224: The account already exists.
raise Puppet::Error, _("Cannot create group if user '%{name}' exists.") % { name: name } if Puppet::Util::Windows::ADSI::User.exists?(name)
new(name, Puppet::Util::Windows::ADSI.create(name, @object_class))
end
end
def add_member_sids(*sids)
sids.each do |sid|
native_object.Add(Puppet::Util::Windows::ADSI.sid_uri(sid))
end
end
def remove_member_sids(*sids)
sids.each do |sid|
native_object.Remove(Puppet::Util::Windows::ADSI.sid_uri(sid))
end
end
# returns Puppet::Util::Windows::SID::Principal[]
# may contain objects that represent unresolvable SIDs
# qualified account names are returned by calling #domain_account
def members
self.class.get_sids(native_object.Members)
end
alias member_sids members
def set_members(desired_members, inclusive = true)
return if desired_members.nil?
current_hash = member_sids.to_h { |sid| [sid.sid, sid] }
desired_hash = self.class.name_sid_hash(desired_members)
# First we add all missing members
unless desired_hash.empty?
members_to_add = (desired_hash.keys - current_hash.keys).map { |sid| desired_hash[sid] }
add_member_sids(*members_to_add)
end
# Then we remove all extra members if inclusive
if inclusive
if desired_hash.empty?
members_to_remove = current_hash.values
else
members_to_remove = (current_hash.keys - desired_hash.keys).map { |sid| current_hash[sid] }
end
remove_member_sids(*members_to_remove)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/sid.rb | lib/puppet/util/windows/sid.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
module Puppet::Util::Windows
module SID
require 'ffi'
extend FFI::Library
# missing from Windows::Error
ERROR_NONE_MAPPED = 1332
ERROR_INVALID_SID_STRUCTURE = 1337
ERROR_TRUSTED_DOMAIN_FAILURE = 1788
ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789
# Well Known SIDs
Null = 'S-1-0'
Nobody = 'S-1-0-0'
World = 'S-1-1'
Everyone = 'S-1-1-0'
Local = 'S-1-2'
Creator = 'S-1-3'
CreatorOwner = 'S-1-3-0'
CreatorGroup = 'S-1-3-1'
CreatorOwnerServer = 'S-1-3-2'
CreatorGroupServer = 'S-1-3-3'
NonUnique = 'S-1-4'
Nt = 'S-1-5'
Dialup = 'S-1-5-1'
Network = 'S-1-5-2'
Batch = 'S-1-5-3'
Interactive = 'S-1-5-4'
Service = 'S-1-5-6'
Anonymous = 'S-1-5-7'
Proxy = 'S-1-5-8'
EnterpriseDomainControllers = 'S-1-5-9'
PrincipalSelf = 'S-1-5-10'
AuthenticatedUsers = 'S-1-5-11'
RestrictedCode = 'S-1-5-12'
TerminalServerUsers = 'S-1-5-13'
LocalSystem = 'S-1-5-18'
NtLocal = 'S-1-5-19'
NtNetwork = 'S-1-5-20'
BuiltinAdministrators = 'S-1-5-32-544'
BuiltinUsers = 'S-1-5-32-545'
Guests = 'S-1-5-32-546'
PowerUsers = 'S-1-5-32-547'
AccountOperators = 'S-1-5-32-548'
ServerOperators = 'S-1-5-32-549'
PrintOperators = 'S-1-5-32-550'
BackupOperators = 'S-1-5-32-551'
Replicators = 'S-1-5-32-552'
AllAppPackages = 'S-1-15-2-1'
# Convert an account name, e.g. 'Administrators' into a SID string,
# e.g. 'S-1-5-32-544'. The name can be specified as 'Administrators',
# 'BUILTIN\Administrators', or 'S-1-5-32-544', and will return the
# SID. Returns nil if the account doesn't exist.
def name_to_sid(name)
sid = name_to_principal(name)
sid ? sid.sid : nil
end
module_function :name_to_sid
# Convert an account name, e.g. 'Administrators' into a Principal::SID object,
# e.g. 'S-1-5-32-544'. The name can be specified as 'Administrators',
# 'BUILTIN\Administrators', or 'S-1-5-32-544', and will return the
# SID object. Returns nil if the account doesn't exist.
# This method returns a SID::Principal with the account, domain, SID, etc
def name_to_principal(name, allow_unresolved = false)
# Apparently, we accept a symbol..
name = name.to_s.strip if name
# if name is a SID string, convert it to raw bytes for use with lookup_account_sid
raw_sid_bytes = nil
begin
string_to_sid_ptr(name) do |sid_ptr|
raw_sid_bytes = sid_ptr.read_array_of_uchar(get_length_sid(sid_ptr))
end
rescue => e
# Avoid debug logs pollution with valid account names
# https://docs.microsoft.com/en-us/windows/win32/api/sddl/nf-sddl-convertstringsidtosidw#return-value
Puppet.debug("Could not retrieve raw SID bytes from '#{name}': #{e.message}") unless e.code == ERROR_INVALID_SID_STRUCTURE
end
raw_sid_bytes ? Principal.lookup_account_sid(raw_sid_bytes) : Principal.lookup_account_name(name)
rescue => e
Puppet.debug(e.message.to_s)
(allow_unresolved && raw_sid_bytes) ? unresolved_principal(name, raw_sid_bytes) : nil
end
module_function :name_to_principal
class << self; alias name_to_sid_object name_to_principal; end
# Converts an octet string array of bytes to a SID::Principal object,
# e.g. [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0] is the representation for
# S-1-5-18, the local 'SYSTEM' account.
# Raises an Error for nil or non-array input.
# This method returns a SID::Principal with the account, domain, SID, etc
def octet_string_to_principal(bytes)
if !bytes || !bytes.respond_to?('pack') || bytes.empty?
raise Puppet::Util::Windows::Error, _("Octet string must be an array of bytes")
end
Principal.lookup_account_sid(bytes)
end
module_function :octet_string_to_principal
class << self; alias octet_string_to_sid_object octet_string_to_principal; end
# Converts a COM instance of IAdsUser or IAdsGroup to a SID::Principal object,
# Raises an Error for nil or an object without an objectSID / Name property.
# This method returns a SID::Principal with the account, domain, SID, etc
# This method will return instances even when the SID is unresolvable, as
# may be the case when domain users have been added to local groups, but
# removed from the domain
def ads_to_principal(ads_object)
if !ads_object || !ads_object.respond_to?(:ole_respond_to?) ||
!ads_object.ole_respond_to?(:objectSID) || !ads_object.ole_respond_to?(:Name)
raise Puppet::Error, "ads_object must be an IAdsUser or IAdsGroup instance"
end
octet_string_to_principal(ads_object.objectSID)
rescue Puppet::Util::Windows::Error => e
# if the error is not a lookup / mapping problem, immediately re-raise
raise if e.code != ERROR_NONE_MAPPED
# if the Name property isn't formatted like a SID, OR
if !valid_sid?(ads_object.Name) ||
# if the objectSID doesn't match the Name property, also raise
((converted = octet_string_to_sid_string(ads_object.objectSID)) != ads_object.Name)
raise Puppet::Error.new("ads_object Name: #{ads_object.Name} invalid or does not match objectSID: #{ads_object.objectSID} (#{converted})", e)
end
unresolved_principal(ads_object.Name, ads_object.objectSID)
end
module_function :ads_to_principal
# Convert a SID string, e.g. "S-1-5-32-544" to a name,
# e.g. 'BUILTIN\Administrators'. Returns nil if an account
# for that SID does not exist.
def sid_to_name(value)
sid_bytes = []
begin
string_to_sid_ptr(value) do |ptr|
sid_bytes = ptr.read_array_of_uchar(get_length_sid(ptr))
end
rescue Puppet::Util::Windows::Error => e
raise if e.code != ERROR_INVALID_SID_STRUCTURE
end
Principal.lookup_account_sid(sid_bytes).domain_account
rescue
nil
end
module_function :sid_to_name
# https://stackoverflow.com/a/1792930 - 68 bytes, 184 characters in a string
MAXIMUM_SID_STRING_LENGTH = 184
# Convert a SID pointer to a SID string, e.g. "S-1-5-32-544".
def sid_ptr_to_string(psid)
if !psid.is_a?(FFI::Pointer) || IsValidSid(psid) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
sid_string = nil
FFI::MemoryPointer.new(:pointer, 1) do |buffer_ptr|
if ConvertSidToStringSidW(psid, buffer_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to convert binary SID")
end
buffer_ptr.read_win32_local_pointer do |wide_string_ptr|
if wide_string_ptr.null?
raise Puppet::Error, _("ConvertSidToStringSidW failed to allocate buffer for sid")
end
sid_string = wide_string_ptr.read_arbitrary_wide_string_up_to(MAXIMUM_SID_STRING_LENGTH)
end
end
sid_string
end
module_function :sid_ptr_to_string
# Convert a SID string, e.g. "S-1-5-32-544" to a pointer (containing the
# address of the binary SID structure). The returned value can be used in
# Win32 APIs that expect a PSID, e.g. IsValidSid. The account for this
# SID may or may not exist.
def string_to_sid_ptr(string_sid, &block)
FFI::MemoryPointer.from_string_to_wide_string(string_sid) do |lpcwstr|
FFI::MemoryPointer.new(:pointer, 1) do |sid_ptr_ptr|
if ConvertStringSidToSidW(lpcwstr, sid_ptr_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to convert string SID: %{string_sid}") % { string_sid: string_sid }
end
sid_ptr_ptr.read_win32_local_pointer do |sid_ptr|
yield sid_ptr
end
end
end
# yielded sid_ptr has already had LocalFree called, nothing to return
nil
end
module_function :string_to_sid_ptr
# Return true if the string is a valid SID, e.g. "S-1-5-32-544", false otherwise.
def valid_sid?(string_sid)
valid = false
begin
string_to_sid_ptr(string_sid) { |ptr| valid = !ptr.nil? && !ptr.null? }
rescue Puppet::Util::Windows::Error => e
raise if e.code != ERROR_INVALID_SID_STRUCTURE
end
valid
end
module_function :valid_sid?
def get_length_sid(sid_ptr)
# MSDN states IsValidSid should be called on pointer first
if !sid_ptr.is_a?(FFI::Pointer) || IsValidSid(sid_ptr) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
GetLengthSid(sid_ptr)
end
module_function :get_length_sid
def octet_string_to_sid_string(sid_bytes)
sid_string = nil
FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_ptr|
sid_ptr.write_array_of_uchar(sid_bytes)
sid_string = Puppet::Util::Windows::SID.sid_ptr_to_string(sid_ptr)
end
sid_string
end
module_function :octet_string_to_sid_string
# @api private
def self.unresolved_principal(name, sid_bytes)
Principal.new(
name, # account
sid_bytes, # sid_bytes
name, # sid string
nil, # domain
# https://msdn.microsoft.com/en-us/library/cc245534.aspx?f=255&MSPPError=-2147217396
# Indicates that the type of object could not be determined. For example, no object with that SID exists.
:SidTypeUnknown
)
end
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379151(v=vs.85).aspx
# BOOL WINAPI IsValidSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :IsValidSid,
[:pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376399(v=vs.85).aspx
# BOOL ConvertSidToStringSid(
# _In_ PSID Sid,
# _Out_ LPTSTR *StringSid
# );
ffi_lib :advapi32
attach_function_private :ConvertSidToStringSidW,
[:pointer, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376402(v=vs.85).aspx
# BOOL WINAPI ConvertStringSidToSid(
# _In_ LPCTSTR StringSid,
# _Out_ PSID *Sid
# );
ffi_lib :advapi32
attach_function_private :ConvertStringSidToSidW,
[:lpcwstr, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa446642(v=vs.85).aspx
# DWORD WINAPI GetLengthSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :GetLengthSid, [:pointer], :dword
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/com.rb | lib/puppet/util/windows/com.rb | # frozen_string_literal: true
require 'ffi'
module Puppet::Util::Windows::COM
extend FFI::Library
ffi_convention :stdcall
S_OK = 0
S_FALSE = 1
def SUCCEEDED(hr) hr >= 0 end
def FAILED(hr) hr < 0 end
module_function :SUCCEEDED, :FAILED
def raise_if_hresult_failed(name, *args)
failed = FAILED(result = send(name, *args)) and raise _("%{name} failed (hresult %{result}).") % { name: name, result: format('%#08x', result) }
result
ensure
yield failed if block_given?
end
module_function :raise_if_hresult_failed
CLSCTX_INPROC_SERVER = 0x1
CLSCTX_INPROC_HANDLER = 0x2
CLSCTX_LOCAL_SERVER = 0x4
CLSCTX_INPROC_SERVER16 = 0x8
CLSCTX_REMOTE_SERVER = 0x10
CLSCTX_INPROC_HANDLER16 = 0x20
CLSCTX_RESERVED1 = 0x40
CLSCTX_RESERVED2 = 0x80
CLSCTX_RESERVED3 = 0x100
CLSCTX_RESERVED4 = 0x200
CLSCTX_NO_CODE_DOWNLOAD = 0x400
CLSCTX_RESERVED5 = 0x800
CLSCTX_NO_CUSTOM_MARSHAL = 0x1000
CLSCTX_ENABLE_CODE_DOWNLOAD = 0x2000
CLSCTX_NO_FAILURE_LOG = 0x4000
CLSCTX_DISABLE_AAA = 0x8000
CLSCTX_ENABLE_AAA = 0x10000
CLSCTX_FROM_DEFAULT_CONTEXT = 0x20000
CLSCTX_ACTIVATE_32_BIT_SERVER = 0x40000
CLSCTX_ACTIVATE_64_BIT_SERVER = 0x80000
CLSCTX_ENABLE_CLOAKING = 0x100000
CLSCTX_PS_DLL = -0x80000000
CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER
CLSCTX_ALL = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms686615(v=vs.85).aspx
# HRESULT CoCreateInstance(
# _In_ REFCLSID rclsid,
# _In_ LPUNKNOWN pUnkOuter,
# _In_ DWORD dwClsContext,
# _In_ REFIID riid,
# _Out_ LPVOID *ppv
# );
ffi_lib :ole32
attach_function_private :CoCreateInstance,
[:pointer, :lpunknown, :dword, :pointer, :lpvoid], :hresult
# code modified from Unknownr project https://github.com/rpeev/Unknownr
# licensed under MIT
module Interface
def self.[](*args)
spec, iid, *ifaces = args.reverse
spec.each { |_name, signature| signature[0].unshift(:pointer) }
Class.new(FFI::Struct) do
const_set(:IID, iid)
vtable = Class.new(FFI::Struct) do
vtable_hash = (ifaces.map { |iface| iface::VTBL::SPEC.to_a } << spec.to_a).flatten(1).to_h
const_set(:SPEC, vtable_hash)
layout(
*self::SPEC.map { |name, signature| [name, callback(*signature)] }.flatten
)
end
const_set(:VTBL, vtable)
layout \
:lpVtbl, :pointer
end
end
end
module Helpers
def QueryInstance(klass)
instance = nil
FFI::MemoryPointer.new(:pointer) do |ppv|
QueryInterface(klass::IID, ppv)
instance = klass.new(ppv.read_pointer)
end
begin
yield instance
return self
ensure
instance.Release
end if block_given?
instance
end
def UseInstance(klass, name, *args)
instance = nil
FFI::MemoryPointer.new(:pointer) do |ppv|
send(name, *args, ppv)
yield instance = klass.new(ppv.read_pointer)
end
self
ensure
instance.Release if instance && !instance.null?
end
end
module Instance
def self.[](iface)
Class.new(iface) do
send(:include, Helpers)
def initialize(pointer)
self.pointer = pointer
@vtbl = self.class::VTBL.new(self[:lpVtbl])
end
attr_reader :vtbl
self::VTBL.members.each do |name|
define_method(name) do |*args|
if Puppet::Util::Windows::COM.FAILED((result = @vtbl[name].call(self, *args)))
raise Puppet::Util::Windows::Error.new(_("Failed to call %{klass}::%{name} with HRESULT: %{result}.") % { klass: self, name: name, result: result }, result)
end
result
end
end
layout \
:lpVtbl, :pointer
end
end
end
module Factory
def self.[](iface, clsid)
Class.new(iface) do
send(:include, Helpers)
const_set(:CLSID, clsid)
def initialize(opts = {})
@opts = opts
@opts[:clsctx] ||= CLSCTX_INPROC_SERVER
FFI::MemoryPointer.new(:pointer) do |ppv|
hr = Puppet::Util::Windows::COM.CoCreateInstance(self.class::CLSID, FFI::Pointer::NULL, @opts[:clsctx], self.class::IID, ppv)
if Puppet::Util::Windows::COM.FAILED(hr)
raise _("CoCreateInstance failed (%{klass}).") % { klass: self.class }
end
self.pointer = ppv.read_pointer
end
@vtbl = self.class::VTBL.new(self[:lpVtbl])
end
attr_reader :vtbl
self::VTBL.members.each do |name|
define_method(name) do |*args|
if Puppet::Util::Windows::COM.FAILED((result = @vtbl[name].call(self, *args)))
raise Puppet::Util::Windows::Error.new(_("Failed to call %{klass}::%{name} with HRESULT: %{result}.") % { klass: self, name: name, result: result }, result)
end
result
end
end
layout \
:lpVtbl, :pointer
end
end
end
IUnknown = Interface[
FFI::WIN32::GUID['00000000-0000-0000-C000-000000000046'],
QueryInterface: [[:pointer, :pointer], :hresult],
AddRef: [[], :win32_ulong],
Release: [[], :win32_ulong]
]
Unknown = Instance[IUnknown]
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms678543(v=vs.85).aspx
# HRESULT CoInitialize(
# _In_opt_ LPVOID pvReserved
# );
ffi_lib :ole32
attach_function_private :CoInitialize, [:lpvoid], :hresult
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms688715(v=vs.85).aspx
# void CoUninitialize(void);
ffi_lib :ole32
attach_function_private :CoUninitialize, [], :void
def InitializeCom
raise_if_hresult_failed(:CoInitialize, FFI::Pointer::NULL)
at_exit { CoUninitialize() }
end
module_function :InitializeCom
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/user.rb | lib/puppet/util/windows/user.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
require 'ffi'
module Puppet::Util::Windows::User
extend Puppet::Util::Windows::String
extend FFI::Library
def admin?
return false unless check_token_membership
# if Vista or later, check for unrestricted process token
elevated_supported = Puppet::Util::Windows::Process.supports_elevated_security?
elevated_supported ? Puppet::Util::Windows::Process.elevated_security? : true
end
module_function :admin?
# The name of the account in all locales is `LocalSystem`. `.\LocalSystem` or `ComputerName\LocalSystem' can also be used.
# This account is not recognized by the security subsystem, so you cannot specify its name in a call to the `LookupAccountName` function.
# https://docs.microsoft.com/en-us/windows/win32/services/localsystem-account
def localsystem?(name)
["LocalSystem", ".\\LocalSystem", "#{Puppet::Util::Windows::ADSI.computer_name}\\LocalSystem"].any? { |s| s.casecmp(name) == 0 }
end
module_function :localsystem?
# Check if a given user is one of the default system accounts
# These accounts do not have a password and all checks done through logon attempt will fail
# https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/local-accounts#default-local-system-accounts
def default_system_account?(name)
user_sid = Puppet::Util::Windows::SID.name_to_sid(name)
[Puppet::Util::Windows::SID::LocalSystem, Puppet::Util::Windows::SID::NtLocal, Puppet::Util::Windows::SID::NtNetwork].include?(user_sid)
end
module_function :default_system_account?
# https://msdn.microsoft.com/en-us/library/windows/desktop/ee207397(v=vs.85).aspx
SECURITY_MAX_SID_SIZE = 68
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx
# These error codes indicate successful authentication but failure to
# logon for a separate reason
ERROR_ACCOUNT_RESTRICTION = 1327
ERROR_INVALID_LOGON_HOURS = 1328
ERROR_INVALID_WORKSTATION = 1329
ERROR_ACCOUNT_DISABLED = 1331
def check_token_membership
is_admin = false
FFI::MemoryPointer.new(:byte, SECURITY_MAX_SID_SIZE) do |sid_pointer|
FFI::MemoryPointer.new(:dword, 1) do |size_pointer|
size_pointer.write_uint32(SECURITY_MAX_SID_SIZE)
if CreateWellKnownSid(:WinBuiltinAdministratorsSid, FFI::Pointer::NULL, sid_pointer, size_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to create administrators SID")
end
end
if IsValidSid(sid_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Invalid SID")
end
FFI::MemoryPointer.new(:win32_bool, 1) do |ismember_pointer|
if CheckTokenMembership(FFI::Pointer::NULL_HANDLE, sid_pointer, ismember_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to check membership")
end
# Is administrators SID enabled in calling thread's access token?
is_admin = ismember_pointer.read_win32_bool
end
end
is_admin
end
module_function :check_token_membership
def password_is?(name, password, domain = '.')
logon_user(name, password, domain) { |token| }
rescue Puppet::Util::Windows::Error => detail
authenticated_error_codes = Set[
ERROR_ACCOUNT_RESTRICTION,
ERROR_INVALID_LOGON_HOURS,
ERROR_INVALID_WORKSTATION,
ERROR_ACCOUNT_DISABLED,
]
authenticated_error_codes.include?(detail.code)
end
module_function :password_is?
def logon_user(name, password, domain = '.', &block)
fLOGON32_PROVIDER_DEFAULT = 0
fLOGON32_LOGON_INTERACTIVE = 2
fLOGON32_LOGON_NETWORK = 3
token = nil
begin
FFI::MemoryPointer.new(:handle, 1) do |token_pointer|
# try logon using network else try logon using interactive mode
if logon_user_by_logon_type(name, domain, password, fLOGON32_LOGON_NETWORK, fLOGON32_PROVIDER_DEFAULT, token_pointer) == FFI::WIN32_FALSE
if logon_user_by_logon_type(name, domain, password, fLOGON32_LOGON_INTERACTIVE, fLOGON32_PROVIDER_DEFAULT, token_pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to logon user %{name}") % { name: name.inspect }
end
end
yield token = token_pointer.read_handle
end
ensure
FFI::WIN32.CloseHandle(token) if token
end
# token has been closed by this point
true
end
module_function :logon_user
def self.logon_user_by_logon_type(name, domain, password, logon_type, logon_provider, token)
LogonUserW(wide_string(name), wide_string(domain), password.nil? ? FFI::Pointer::NULL : wide_string(password), logon_type, logon_provider, token)
end
private_class_method :logon_user_by_logon_type
def load_profile(user, password)
logon_user(user, password) do |token|
FFI::MemoryPointer.from_string_to_wide_string(user) do |lpUserName|
pi = PROFILEINFO.new
pi[:dwSize] = PROFILEINFO.size
pi[:dwFlags] = 1 # PI_NOUI - prevents display of profile error msgs
pi[:lpUserName] = lpUserName
# Load the profile. Since it doesn't exist, it will be created
if LoadUserProfileW(token, pi.pointer) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to load user profile %{user}") % { user: user.inspect }
end
Puppet.debug("Loaded profile for #{user}")
if UnloadUserProfile(token, pi[:hProfile]) == FFI::WIN32_FALSE
raise Puppet::Util::Windows::Error, _("Failed to unload user profile %{user}") % { user: user.inspect }
end
end
end
end
module_function :load_profile
def get_rights(name)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
return "" unless user_info
rights = []
rights_pointer = FFI::MemoryPointer.new(:pointer)
number_of_rights = FFI::MemoryPointer.new(:ulong)
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaEnumerateAccountRights(policy_handle.read_pointer, sid_pointer, rights_pointer, number_of_rights)
check_lsa_nt_status_and_raise_failures(result, "LsaEnumerateAccountRights")
end
number_of_rights.read_ulong.times do |index|
right = LSA_UNICODE_STRING.new(rights_pointer.read_pointer + index * LSA_UNICODE_STRING.size)
rights << right[:Buffer].read_arbitrary_wide_string_up_to
end
result = LsaFreeMemory(rights_pointer.read_pointer)
check_lsa_nt_status_and_raise_failures(result, "LsaFreeMemory")
rights.join(",")
end
module_function :get_rights
def set_rights(name, rights)
rights_pointer = new_lsa_unicode_strings_pointer(rights)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaAddAccountRights(policy_handle.read_pointer, sid_pointer, rights_pointer, rights.size)
check_lsa_nt_status_and_raise_failures(result, "LsaAddAccountRights")
end
end
module_function :set_rights
def remove_rights(name, rights)
rights_pointer = new_lsa_unicode_strings_pointer(rights)
user_info = Puppet::Util::Windows::SID.name_to_principal(name.sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\"))
sid_pointer = FFI::MemoryPointer.new(:byte, user_info.sid_bytes.length).write_array_of_uchar(user_info.sid_bytes)
new_lsa_policy_handle do |policy_handle|
result = LsaRemoveAccountRights(policy_handle.read_pointer, sid_pointer, false, rights_pointer, rights.size)
check_lsa_nt_status_and_raise_failures(result, "LsaRemoveAccountRights")
end
end
module_function :remove_rights
# ACCESS_MASK flags for Policy Objects
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-lsad/b61b7268-987a-420b-84f9-6c75f8dc8558
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002
POLICY_GET_PRIVATE_INFORMATION = 0x00000004
POLICY_TRUST_ADMIN = 0x00000008
POLICY_CREATE_ACCOUNT = 0x00000010
POLICY_CREATE_SECRET = 0x00000020
POLICY_CREATE_PRIVILEGE = 0x00000040
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100
POLICY_AUDIT_LOG_ADMIN = 0x00000200
POLICY_SERVER_ADMIN = 0x00000400
POLICY_LOOKUP_NAMES = 0x00000800
POLICY_NOTIFICATION = 0x00001000
def self.new_lsa_policy_handle
access = 0
access |= POLICY_LOOKUP_NAMES
access |= POLICY_CREATE_ACCOUNT
policy_handle = FFI::MemoryPointer.new(:pointer)
result = LsaOpenPolicy(nil, LSA_OBJECT_ATTRIBUTES.new, access, policy_handle)
check_lsa_nt_status_and_raise_failures(result, "LsaOpenPolicy")
begin
yield policy_handle
ensure
result = LsaClose(policy_handle.read_pointer)
check_lsa_nt_status_and_raise_failures(result, "LsaClose")
end
end
private_class_method :new_lsa_policy_handle
def self.new_lsa_unicode_strings_pointer(strings)
lsa_unicode_strings_pointer = FFI::MemoryPointer.new(LSA_UNICODE_STRING, strings.size)
strings.each_with_index do |string, index|
lsa_string = LSA_UNICODE_STRING.new(lsa_unicode_strings_pointer + index * LSA_UNICODE_STRING.size)
lsa_string[:Buffer] = FFI::MemoryPointer.from_string(wide_string(string))
lsa_string[:Length] = string.length * 2
lsa_string[:MaximumLength] = lsa_string[:Length] + 2
end
lsa_unicode_strings_pointer
end
private_class_method :new_lsa_unicode_strings_pointer
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d
def self.check_lsa_nt_status_and_raise_failures(status, method_name)
error_code = LsaNtStatusToWinError(status)
error_reason = case error_code.to_s(16)
when '0' # ERROR_SUCCESS
return # Method call succeded
when '2' # ERROR_FILE_NOT_FOUND
return # No rights/privilleges assigned to given user
when '5' # ERROR_ACCESS_DENIED
"Access is denied. Please make sure that puppet is running as administrator."
when '521' # ERROR_NO_SUCH_PRIVILEGE
"One or more of the given rights/privilleges are incorrect."
when '6ba' # RPC_S_SERVER_UNAVAILABLE
"The RPC server is unavailable or given domain name is invalid."
end
raise Puppet::Error, "Calling `#{method_name}` returned 'Win32 Error Code 0x%08X'. #{error_reason}" % error_code
end
private_class_method :check_lsa_nt_status_and_raise_failures
ffi_convention :stdcall
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx
# BOOL LogonUser(
# _In_ LPTSTR lpszUsername,
# _In_opt_ LPTSTR lpszDomain,
# _In_opt_ LPTSTR lpszPassword,
# _In_ DWORD dwLogonType,
# _In_ DWORD dwLogonProvider,
# _Out_ PHANDLE phToken
# );
ffi_lib :advapi32
attach_function_private :LogonUserW,
[:lpwstr, :lpwstr, :lpwstr, :dword, :dword, :phandle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb773378(v=vs.85).aspx
# typedef struct _PROFILEINFO {
# DWORD dwSize;
# DWORD dwFlags;
# LPTSTR lpUserName;
# LPTSTR lpProfilePath;
# LPTSTR lpDefaultPath;
# LPTSTR lpServerName;
# LPTSTR lpPolicyPath;
# HANDLE hProfile;
# } PROFILEINFO, *LPPROFILEINFO;
# technically
# NOTE: that for structs, buffer_* (lptstr alias) cannot be used
class PROFILEINFO < FFI::Struct
layout :dwSize, :dword,
:dwFlags, :dword,
:lpUserName, :pointer,
:lpProfilePath, :pointer,
:lpDefaultPath, :pointer,
:lpServerName, :pointer,
:lpPolicyPath, :pointer,
:hProfile, :handle
end
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb762281(v=vs.85).aspx
# BOOL WINAPI LoadUserProfile(
# _In_ HANDLE hToken,
# _Inout_ LPPROFILEINFO lpProfileInfo
# );
ffi_lib :userenv
attach_function_private :LoadUserProfileW,
[:handle, :pointer], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/bb762282(v=vs.85).aspx
# BOOL WINAPI UnloadUserProfile(
# _In_ HANDLE hToken,
# _In_ HANDLE hProfile
# );
ffi_lib :userenv
attach_function_private :UnloadUserProfile,
[:handle, :handle], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx
# BOOL WINAPI CheckTokenMembership(
# _In_opt_ HANDLE TokenHandle,
# _In_ PSID SidToCheck,
# _Out_ PBOOL IsMember
# );
ffi_lib :advapi32
attach_function_private :CheckTokenMembership,
[:handle, :pointer, :pbool], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379650(v=vs.85).aspx
# rubocop:disable Layout/SpaceBeforeComma
WELL_KNOWN_SID_TYPE = enum(
:WinNullSid , 0,
:WinWorldSid , 1,
:WinLocalSid , 2,
:WinCreatorOwnerSid , 3,
:WinCreatorGroupSid , 4,
:WinCreatorOwnerServerSid , 5,
:WinCreatorGroupServerSid , 6,
:WinNtAuthoritySid , 7,
:WinDialupSid , 8,
:WinNetworkSid , 9,
:WinBatchSid , 10,
:WinInteractiveSid , 11,
:WinServiceSid , 12,
:WinAnonymousSid , 13,
:WinProxySid , 14,
:WinEnterpriseControllersSid , 15,
:WinSelfSid , 16,
:WinAuthenticatedUserSid , 17,
:WinRestrictedCodeSid , 18,
:WinTerminalServerSid , 19,
:WinRemoteLogonIdSid , 20,
:WinLogonIdsSid , 21,
:WinLocalSystemSid , 22,
:WinLocalServiceSid , 23,
:WinNetworkServiceSid , 24,
:WinBuiltinDomainSid , 25,
:WinBuiltinAdministratorsSid , 26,
:WinBuiltinUsersSid , 27,
:WinBuiltinGuestsSid , 28,
:WinBuiltinPowerUsersSid , 29,
:WinBuiltinAccountOperatorsSid , 30,
:WinBuiltinSystemOperatorsSid , 31,
:WinBuiltinPrintOperatorsSid , 32,
:WinBuiltinBackupOperatorsSid , 33,
:WinBuiltinReplicatorSid , 34,
:WinBuiltinPreWindows2000CompatibleAccessSid , 35,
:WinBuiltinRemoteDesktopUsersSid , 36,
:WinBuiltinNetworkConfigurationOperatorsSid , 37,
:WinAccountAdministratorSid , 38,
:WinAccountGuestSid , 39,
:WinAccountKrbtgtSid , 40,
:WinAccountDomainAdminsSid , 41,
:WinAccountDomainUsersSid , 42,
:WinAccountDomainGuestsSid , 43,
:WinAccountComputersSid , 44,
:WinAccountControllersSid , 45,
:WinAccountCertAdminsSid , 46,
:WinAccountSchemaAdminsSid , 47,
:WinAccountEnterpriseAdminsSid , 48,
:WinAccountPolicyAdminsSid , 49,
:WinAccountRasAndIasServersSid , 50,
:WinNTLMAuthenticationSid , 51,
:WinDigestAuthenticationSid , 52,
:WinSChannelAuthenticationSid , 53,
:WinThisOrganizationSid , 54,
:WinOtherOrganizationSid , 55,
:WinBuiltinIncomingForestTrustBuildersSid , 56,
:WinBuiltinPerfMonitoringUsersSid , 57,
:WinBuiltinPerfLoggingUsersSid , 58,
:WinBuiltinAuthorizationAccessSid , 59,
:WinBuiltinTerminalServerLicenseServersSid , 60,
:WinBuiltinDCOMUsersSid , 61,
:WinBuiltinIUsersSid , 62,
:WinIUserSid , 63,
:WinBuiltinCryptoOperatorsSid , 64,
:WinUntrustedLabelSid , 65,
:WinLowLabelSid , 66,
:WinMediumLabelSid , 67,
:WinHighLabelSid , 68,
:WinSystemLabelSid , 69,
:WinWriteRestrictedCodeSid , 70,
:WinCreatorOwnerRightsSid , 71,
:WinCacheablePrincipalsGroupSid , 72,
:WinNonCacheablePrincipalsGroupSid , 73,
:WinEnterpriseReadonlyControllersSid , 74,
:WinAccountReadonlyControllersSid , 75,
:WinBuiltinEventLogReadersGroup , 76,
:WinNewEnterpriseReadonlyControllersSid , 77,
:WinBuiltinCertSvcDComAccessGroup , 78,
:WinMediumPlusLabelSid , 79,
:WinLocalLogonSid , 80,
:WinConsoleLogonSid , 81,
:WinThisOrganizationCertificateSid , 82,
:WinApplicationPackageAuthoritySid , 83,
:WinBuiltinAnyPackageSid , 84,
:WinCapabilityInternetClientSid , 85,
:WinCapabilityInternetClientServerSid , 86,
:WinCapabilityPrivateNetworkClientServerSid , 87,
:WinCapabilityPicturesLibrarySid , 88,
:WinCapabilityVideosLibrarySid , 89,
:WinCapabilityMusicLibrarySid , 90,
:WinCapabilityDocumentsLibrarySid , 91,
:WinCapabilitySharedUserCertificatesSid , 92,
:WinCapabilityEnterpriseAuthenticationSid , 93,
:WinCapabilityRemovableStorageSid , 94
)
# rubocop:enable Layout/SpaceBeforeComma
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa446585(v=vs.85).aspx
# BOOL WINAPI CreateWellKnownSid(
# _In_ WELL_KNOWN_SID_TYPE WellKnownSidType,
# _In_opt_ PSID DomainSid,
# _Out_opt_ PSID pSid,
# _Inout_ DWORD *cbSid
# );
ffi_lib :advapi32
attach_function_private :CreateWellKnownSid,
[WELL_KNOWN_SID_TYPE, :pointer, :pointer, :lpdword], :win32_bool
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa379151(v=vs.85).aspx
# BOOL WINAPI IsValidSid(
# _In_ PSID pSid
# );
ffi_lib :advapi32
attach_function_private :IsValidSid,
[:pointer], :win32_bool
# https://docs.microsoft.com/en-us/windows/win32/api/lsalookup/ns-lsalookup-lsa_object_attributes
# typedef struct _LSA_OBJECT_ATTRIBUTES {
# ULONG Length;
# HANDLE RootDirectory;
# PLSA_UNICODE_STRING ObjectName;
# ULONG Attributes;
# PVOID SecurityDescriptor;
# PVOID SecurityQualityOfService;
# } LSA_OBJECT_ATTRIBUTES, *PLSA_OBJECT_ATTRIBUTES;
class LSA_OBJECT_ATTRIBUTES < FFI::Struct
layout :Length, :ulong,
:RootDirectory, :handle,
:ObjectName, :plsa_unicode_string,
:Attributes, :ulong,
:SecurityDescriptor, :pvoid,
:SecurityQualityOfService, :pvoid
end
# https://docs.microsoft.com/en-us/windows/win32/api/lsalookup/ns-lsalookup-lsa_unicode_string
# typedef struct _LSA_UNICODE_STRING {
# USHORT Length;
# USHORT MaximumLength;
# PWSTR Buffer;
# } LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;
class LSA_UNICODE_STRING < FFI::Struct
layout :Length, :ushort,
:MaximumLength, :ushort,
:Buffer, :pwstr
end
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaenumerateaccountrights
# https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/user-rights-assignment
# NTSTATUS LsaEnumerateAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# PLSA_UNICODE_STRING *UserRights,
# PULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaEnumerateAccountRights,
[:lsa_handle, :psid, :plsa_unicode_string, :pulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaaddaccountrights
# NTSTATUS LsaAddAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# PLSA_UNICODE_STRING UserRights,
# ULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaAddAccountRights,
[:lsa_handle, :psid, :plsa_unicode_string, :ulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaremoveaccountrights
# NTSTATUS LsaRemoveAccountRights(
# LSA_HANDLE PolicyHandle,
# PSID AccountSid,
# BOOLEAN AllRights,
# PLSA_UNICODE_STRING UserRights,
# ULONG CountOfRights
# );
ffi_lib :advapi32
attach_function_private :LsaRemoveAccountRights,
[:lsa_handle, :psid, :bool, :plsa_unicode_string, :ulong], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaopenpolicy
# NTSTATUS LsaOpenPolicy(
# PLSA_UNICODE_STRING SystemName,
# PLSA_OBJECT_ATTRIBUTES ObjectAttributes,
# ACCESS_MASK DesiredAccess,
# PLSA_HANDLE PolicyHandle
# );
ffi_lib :advapi32
attach_function_private :LsaOpenPolicy,
[:plsa_unicode_string, :plsa_object_attributes, :access_mask, :plsa_handle], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsaclose
# NTSTATUS LsaClose(
# LSA_HANDLE ObjectHandle
# );
ffi_lib :advapi32
attach_function_private :LsaClose,
[:lsa_handle], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsafreememory
# NTSTATUS LsaFreeMemory(
# PVOID Buffer
# );
ffi_lib :advapi32
attach_function_private :LsaFreeMemory,
[:pvoid], :ntstatus
# https://docs.microsoft.com/en-us/windows/win32/api/ntsecapi/nf-ntsecapi-lsantstatustowinerror
# ULONG LsaNtStatusToWinError(
# NTSTATUS Status
# );
ffi_lib :advapi32
attach_function_private :LsaNtStatusToWinError,
[:ntstatus], :ulong
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/windows/monkey_patches/process.rb | lib/puppet/util/windows/monkey_patches/process.rb | # frozen_string_literal: true
require 'ffi'
require_relative '../../../../puppet/ffi/windows'
require_relative '../../../../puppet/util/windows/string'
module Process
extend FFI::Library
extend Puppet::Util::Windows::String
extend Puppet::FFI::Windows::APITypes
extend Puppet::FFI::Windows::Functions
extend Puppet::FFI::Windows::Structs
include Puppet::FFI::Windows::Constants
include Puppet::FFI::Windows::Structs
ProcessInfo = Struct.new(
'ProcessInfo',
:process_handle,
:thread_handle,
:process_id,
:thread_id
)
private_constant :ProcessInfo
# Disable popups. This mostly affects the Process.kill method.
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX)
class << self
private :SetHandleInformation, :SetErrorMode, :CreateProcessW, :OpenProcess,
:SetPriorityClass, :CreateProcessWithLogonW, :get_osfhandle, :get_errno
# Process.create(key => value, ...) => ProcessInfo
#
# This is a wrapper for the CreateProcess() function. It executes a process,
# returning a ProcessInfo struct. It accepts a hash as an argument.
# There are several primary keys:
#
# * command_line (this or app_name must be present)
# * app_name (default: nil)
# * inherit (default: false)
# * process_inherit (default: false)
# * thread_inherit (default: false)
# * creation_flags (default: 0)
# * cwd (default: Dir.pwd)
# * startup_info (default: nil)
# * environment (default: nil)
# * close_handles (default: true)
# * with_logon (default: nil)
# * domain (default: nil)
# * password (default: nil, mandatory if with_logon)
#
# Of these, the 'command_line' or 'app_name' must be specified or an
# error is raised. Both may be set individually, but 'command_line' should
# be preferred if only one of them is set because it does not (necessarily)
# require an explicit path or extension to work.
#
# The 'domain' and 'password' options are only relevent in the context
# of 'with_logon'. If 'with_logon' is set, then the 'password' option is
# mandatory.
#
# The startup_info key takes a hash. Its keys are attributes that are
# part of the StartupInfo struct, and are generally only meaningful for
# GUI or console processes. See the documentation on CreateProcess()
# and the StartupInfo struct on MSDN for more information.
#
# * desktop
# * title
# * x
# * y
# * x_size
# * y_size
# * x_count_chars
# * y_count_chars
# * fill_attribute
# * sw_flags
# * startf_flags
# * stdin
# * stdout
# * stderr
#
# Note that the 'stdin', 'stdout' and 'stderr' options can be either Ruby
# IO objects or file descriptors (i.e. a fileno). However, StringIO objects
# are not currently supported. Unfortunately, setting these is not currently
# an option for JRuby.
#
# If 'stdin', 'stdout' or 'stderr' are specified, then the +inherit+ value
# is automatically set to true and the Process::STARTF_USESTDHANDLES flag is
# automatically OR'd to the +startf_flags+ value.
#
# The ProcessInfo struct contains the following members:
#
# * process_handle - The handle to the newly created process.
# * thread_handle - The handle to the primary thread of the process.
# * process_id - Process ID.
# * thread_id - Thread ID.
#
# If the 'close_handles' option is set to true (the default) then the
# process_handle and the thread_handle are automatically closed for you
# before the ProcessInfo struct is returned.
#
# If the 'with_logon' option is set, then the process runs the specified
# executable file in the security context of the specified credentials.
VALID_KEYS = %i[
app_name command_line inherit creation_flags cwd environment
startup_info thread_inherit process_inherit close_handles with_logon
domain password
].freeze
VALID_SI_KEYS = %i[
startf_flags desktop title x y x_size y_size x_count_chars
y_count_chars fill_attribute sw_flags stdin stdout stderr
].freeze
private_constant :VALID_KEYS, :VALID_SI_KEYS
def create(args)
# Validate that args is a Hash
validate_args(args)
initialize_defaults
# Validate the keys, and convert symbols and case to lowercase strings.
validate_keys(args)
# If the startup_info key is present, validate its subkeys
validate_startup_info if hash[:startup_info]
# validates that 'app_name' or 'command_line' is set
validate_command_line
if hash[:app_name] && !hash[:command_line]
hash[:command_line] = hash[:app_name]
hash[:app_name] = nil
end
# Setup stdin, stdout and stderr handlers
setup_std_handlers
if logon
create_process_with_logon
else
create_process
end
# Automatically close the process and thread handles in the
# PROCESS_INFORMATION struct unless explicitly told not to.
if hash[:close_handles]
FFI::WIN32.CloseHandle(procinfo[:hProcess])
FFI::WIN32.CloseHandle(procinfo[:hThread])
end
ProcessInfo.new(
procinfo[:hProcess],
procinfo[:hThread],
procinfo[:dwProcessId],
procinfo[:dwThreadId]
)
end
remove_method :setpriority
# Sets the priority class for the specified process id +int+.
#
# The +kind+ parameter is ignored but present for API compatibility.
# You can only retrieve process information, not process group or user
# information, so it is effectively always Process::PRIO_PROCESS.
#
# Possible +int_priority+ values are:
#
# * Process::NORMAL_PRIORITY_CLASS
# * Process::IDLE_PRIORITY_CLASS
# * Process::HIGH_PRIORITY_CLASS
# * Process::REALTIME_PRIORITY_CLASS
# * Process::BELOW_NORMAL_PRIORITY_CLASS
# * Process::ABOVE_NORMAL_PRIORITY_CLASS
def setpriority(kind, int, int_priority)
raise TypeError unless kind.is_a?(Integer)
raise TypeError unless int.is_a?(Integer)
raise TypeError unless int_priority.is_a?(Integer)
int = Process.pid if int == 0
handle = OpenProcess(PROCESS_SET_INFORMATION, 0, int)
if handle == 0
raise SystemCallError, FFI.errno, "OpenProcess"
end
begin
result = SetPriorityClass(handle, int_priority)
raise SystemCallError, FFI.errno, "SetPriorityClass" unless result
ensure
FFI::WIN32.CloseHandle(handle)
end
0
end
private
def initialize_defaults
@hash = {
app_name: nil,
creation_flags: 0,
close_handles: true
}
@si_hash = nil
@procinfo = nil
end
def validate_args(args)
raise TypeError, 'hash keyword arguments expected' unless args.is_a?(Hash)
end
def validate_keys(args)
args.each do |key, val|
key = key.to_s.to_sym
raise ArgumentError, "invalid key '#{key}'" unless VALID_KEYS.include?(key)
hash[key] = val
end
end
def validate_startup_info
hash[:startup_info].each do |key, val|
key = key.to_s.to_sym
raise ArgumentError, "invalid startup_info key '#{key}'" unless VALID_SI_KEYS.include?(key)
si_hash[key] = val
end
end
def validate_command_line
raise ArgumentError, 'command_line or app_name must be specified' unless hash[:app_name] || hash[:command_line]
end
def procinfo
@procinfo ||= PROCESS_INFORMATION.new
end
def hash
@hash ||= {}
end
def si_hash
@si_hash ||= {}
end
def app
wide_string(hash[:app_name])
end
def cmd
wide_string(hash[:command_line])
end
def cwd
wide_string(hash[:cwd])
end
def password
wide_string(hash[:password])
end
def logon
wide_string(hash[:with_logon])
end
def domain
wide_string(hash[:domain])
end
def env
env = hash[:environment]
return unless env
env = env.split(File::PATH_SEPARATOR) unless env.respond_to?(:join)
env = env.map { |e| e + 0.chr }.join('') + 0.chr
env = wide_string(env) if hash[:with_logon]
env
end
def process_security
return unless hash[:process_inherit]
process_security = SECURITY_ATTRIBUTES.new
process_security[:nLength] = SECURITY_ATTRIBUTES.size
process_security[:bInheritHandle] = 1
process_security
end
def thread_security
return unless hash[:thread_inherit]
thread_security = SECURITY_ATTRIBUTES.new
thread_security[:nLength] = SECURITY_ATTRIBUTES.size
thread_security[:bInheritHandle] = 1
thread_security
end
# Automatically handle stdin, stdout and stderr as either IO objects
# or file descriptors. This won't work for StringIO, however. It also
# will not work on JRuby because of the way it handles internal file
# descriptors.
def setup_std_handlers
%i[stdin stdout stderr].each do |io|
next unless si_hash[io]
handle = if si_hash[io].respond_to?(:fileno)
get_osfhandle(si_hash[io].fileno)
else
get_osfhandle(si_hash[io])
end
if handle == INVALID_HANDLE_VALUE
ptr = FFI::MemoryPointer.new(:int)
errno = if get_errno(ptr).zero?
ptr.read_int
else
FFI.errno
end
raise SystemCallError.new('get_osfhandle', errno)
end
# Most implementations of Ruby on Windows create inheritable
# handles by default, but some do not. RF bug #26988.
bool = SetHandleInformation(
handle,
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT
)
raise SystemCallError.new('SetHandleInformation', FFI.errno) unless bool
si_hash[io] = handle
si_hash[:startf_flags] ||= 0
si_hash[:startf_flags] |= STARTF_USESTDHANDLES
hash[:inherit] = true
end
end
def startinfo
startinfo = STARTUPINFO.new
return startinfo if si_hash.empty?
startinfo[:cb] = startinfo.size
startinfo[:lpDesktop] = si_hash[:desktop] if si_hash[:desktop]
startinfo[:lpTitle] = si_hash[:title] if si_hash[:title]
startinfo[:dwX] = si_hash[:x] if si_hash[:x]
startinfo[:dwY] = si_hash[:y] if si_hash[:y]
startinfo[:dwXSize] = si_hash[:x_size] if si_hash[:x_size]
startinfo[:dwYSize] = si_hash[:y_size] if si_hash[:y_size]
startinfo[:dwXCountChars] = si_hash[:x_count_chars] if si_hash[:x_count_chars]
startinfo[:dwYCountChars] = si_hash[:y_count_chars] if si_hash[:y_count_chars]
startinfo[:dwFillAttribute] = si_hash[:fill_attribute] if si_hash[:fill_attribute]
startinfo[:dwFlags] = si_hash[:startf_flags] if si_hash[:startf_flags]
startinfo[:wShowWindow] = si_hash[:sw_flags] if si_hash[:sw_flags]
startinfo[:cbReserved2] = 0
startinfo[:hStdInput] = si_hash[:stdin] if si_hash[:stdin]
startinfo[:hStdOutput] = si_hash[:stdout] if si_hash[:stdout]
startinfo[:hStdError] = si_hash[:stderr] if si_hash[:stderr]
startinfo
end
def create_process_with_logon
raise ArgumentError, 'password must be specified if with_logon is used' unless password
hash[:creation_flags] |= CREATE_UNICODE_ENVIRONMENT
bool = CreateProcessWithLogonW(
logon, # User
domain, # Domain
password, # Password
LOGON_WITH_PROFILE, # Logon flags
app, # App name
cmd, # Command line
hash[:creation_flags], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
raise SystemCallError.new('CreateProcessWithLogonW', FFI.errno) unless bool
end
def create_process
inherit = hash[:inherit] ? 1 : 0
bool = CreateProcessW(
app, # App name
cmd, # Command line
process_security, # Process attributes
thread_security, # Thread attributes
inherit, # Inherit handles?
hash[:creation_flags], # Creation flags
env, # Environment
cwd, # Working directory
startinfo, # Startup Info
procinfo # Process Info
)
raise SystemCallError.new('CreateProcess', FFI.errno) unless bool
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range.rb | lib/puppet/util/package/version/range.rb | # frozen_string_literal: true
require_relative 'range/lt'
require_relative 'range/lt_eq'
require_relative 'range/gt'
require_relative 'range/gt_eq'
require_relative 'range/eq'
require_relative 'range/min_max'
module Puppet::Util::Package::Version
class Range
class ValidationFailure < ArgumentError; end
# Parses a version range string into a comparable {Range} instance.
#
# Currently parsed version range string may take any of the following
# forms:
#
# * Regular Version strings
# * ex. `"1.0.0"`, `"1.2.3-pre"`
# * Inequalities
# * ex. `">1.0.0"`, `"<3.2.0"`, `">=4.0.0"`
# * Range Intersections (min is always first)
# * ex. `">1.0.0 <=2.3.0"`
#
RANGE_SPLIT = /\s+/
FULL_REGEX = /\A((?:[<>=])*)(.+)\Z/
# @param range_string [String] the version range string to parse
# @param version_class [Version] a version class implementing comparison operators and parse method
# @return [Range] a new {Range} instance
# @api public
def self.parse(range_string, version_class)
raise ValidationFailure, "Unable to parse '#{range_string}' as a string" unless range_string.is_a?(String)
simples = range_string.split(RANGE_SPLIT).map do |simple|
match, operator, version = *simple.match(FULL_REGEX)
raise ValidationFailure, "Unable to parse '#{simple}' as a version range identifier" unless match
case operator
when '>'
Gt.new(version_class.parse(version))
when '>='
GtEq.new(version_class.parse(version))
when '<'
Lt.new(version_class.parse(version))
when '<='
LtEq.new(version_class.parse(version))
when ''
Eq.new(version_class.parse(version))
else
raise ValidationFailure, "Operator '#{operator}' is not implemented"
end
end
simples.size == 1 ? simples[0] : MinMax.new(simples[0], simples[1])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/pip.rb | lib/puppet/util/package/version/pip.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Pip
include Comparable
VERSION_PATTERN = "
v?
(?:
(?:(?<epoch>[0-9]+)!)? # epoch
(?<release>[0-9]+(?:\\.[0-9]+)*) # release segment
(?<pre> # pre-release
[-_\\.]?
(?<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
[-_\\.]?
(?<pre_n>[0-9]+)?
)?
(?<post> # post release
(?:-(?<post_n1>[0-9]+))
|
(?:
[-_\\.]?
(?<post_l>post|rev|r)
[-_\\.]?
(?<post_n2>[0-9]+)?
)
)?
(?<dev> # dev release
[-_\\.]?
(?<dev_l>dev)
[-_\\.]?
(?<dev_n>[0-9]+)?
)?
)
(?:\\+(?<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))? # local version
"
def self.parse(version)
raise ValidationFailure, version.to_s unless version.is_a? String
matched = version.match(Regexp.new("^\\s*" + VERSION_PATTERN + "\\s*$", Regexp::EXTENDED | Regexp::MULTILINE | Regexp::IGNORECASE))
raise ValidationFailure, version unless matched
new(matched)
end
def self.compare(version_a, version_b)
version_a = parse(version_a) unless version_a.is_a?(self)
version_b = parse(version_b) unless version_b.is_a?(self)
version_a <=> version_b
end
def to_s
parts = []
parts.push("#{@epoch_data}!") if @epoch_data && @epoch_data != 0
parts.push(@release_data.join(".")) if @release_data
parts.push(@pre_data.join) if @pre_data
parts.push(".post#{@post_data[1]}") if @post_data
parts.push(".dev#{@dev_data[1]}") if @dev_data
parts.push("+#{@local_data.join('.')}") if @local_data
parts.join
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) && key.eql?(other.key)
end
alias == eql?
def <=>(other)
raise ValidationFailure, other.to_s unless other.is_a?(self.class)
compare(key, other.key)
end
attr_reader :key
private
def initialize(matched)
@epoch_data = matched[:epoch].to_i
@release_data = matched[:release].split('.').map(&:to_i) if matched[:release]
@pre_data = parse_letter_version(matched[:pre_l], matched[:pre_n]) if matched[:pre_l] || matched[:pre_n]
@post_data = parse_letter_version(matched[:post_l], matched[:post_n1] || matched[:post_n2]) if matched[:post_l] || matched[:post_n1] || matched[:post_n2]
@dev_data = parse_letter_version(matched[:dev_l], matched[:dev_n]) if matched[:dev_l] || matched[:dev_n]
@local_data = parse_local_version(matched[:local]) if matched[:local]
@key = compose_key(@epoch_data, @release_data, @pre_data, @post_data, @dev_data, @local_data)
end
def parse_letter_version(letter, number)
if letter
number ||= 0
letter.downcase!
if letter == "alpha"
letter = "a"
elsif letter == "beta"
letter = "b"
elsif %w[c pre preview].include?(letter)
letter = "rc"
elsif %w[rev r].include?(letter)
letter = "post"
end
return [letter, number.to_i]
end
["post", number.to_i] if !letter && number
end
def parse_local_version(local_version)
local_version.split(/[\\._-]/).map { |part| part =~ /[0-9]+/ && part !~ /[a-zA-Z]+/ ? part.to_i : part.downcase } if local_version
end
def compose_key(epoch, release, pre, post, dev, local)
release_key = release.reverse
release_key.each_with_index do |element, index|
break unless element == 0
release_key.delete_at(index) unless release_key.at(index + 1) != 0
end
release_key.reverse!
if !pre && !post && dev
pre_key = -Float::INFINITY
else
pre_key = pre || Float::INFINITY
end
post_key = post || -Float::INFINITY
dev_key = dev || Float::INFINITY
if !local
local_key = [[-Float::INFINITY, ""]]
else
local_key = local.map { |i| (i.is_a? Integer) ? [i, ""] : [-Float::INFINITY, i] }
end
[epoch, release_key, pre_key, post_key, dev_key, local_key]
end
def compare(this, other)
if (this.is_a? Array) && (other.is_a? Array)
this << -Float::INFINITY if this.length < other.length
other << -Float::INFINITY if this.length > other.length
this.each_with_index do |element, index|
return compare(element, other.at(index)) if element != other.at(index)
end
elsif (this.is_a? Array) && !(other.is_a? Array)
raise Puppet::Error, "Cannot compare #{this} (Array) with #{other} (#{other.class}). Only ±Float::INFINITY accepted." unless other.abs == Float::INFINITY
return other == -Float::INFINITY ? 1 : -1
elsif !(this.is_a? Array) && (other.is_a? Array)
raise Puppet::Error, "Cannot compare #{this} (#{this.class}) with #{other} (Array). Only ±Float::INFINITY accepted." unless this.abs == Float::INFINITY
return this == -Float::INFINITY ? -1 : 1
end
this <=> other
end
class ValidationFailure < ArgumentError
def initialize(version)
super("#{version} is not a valid python package version. Please refer to https://www.python.org/dev/peps/pep-0440/.")
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/debian.rb | lib/puppet/util/package/version/debian.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Debian < Numeric
include Comparable
# Version string matching regexes
REGEX_EPOCH = '(?:([0-9]+):)?'
# alphanumerics and the characters . + - ~ , starts with a digit, ~ only of debian_revision is present
REGEX_UPSTREAM_VERSION = '([\.\+~0-9a-zA-Z-]+?)'
# alphanumerics and the characters + . ~
REGEX_DEBIAN_REVISION = '(?:-([\.\+~0-9a-zA-Z]*))?'
REGEX_FULL = REGEX_EPOCH + REGEX_UPSTREAM_VERSION + REGEX_DEBIAN_REVISION.freeze
REGEX_FULL_RX = /\A#{REGEX_FULL}\Z/
class ValidationFailure < ArgumentError; end
def self.parse(ver)
raise ValidationFailure, "Unable to parse '#{ver}' as a string" unless ver.is_a?(String)
match, epoch, upstream_version, debian_revision = *ver.match(REGEX_FULL_RX)
raise ValidationFailure, "Unable to parse '#{ver}' as a debian version identifier" unless match
new(epoch.to_i, upstream_version, debian_revision).freeze
end
def to_s
s = @upstream_version
s = "#{@epoch}:#{s}" if @epoch != 0
s = "#{s}-#{@debian_revision}" if @debian_revision
s
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) &&
@epoch.eql?(other.epoch) &&
@upstream_version.eql?(other.upstream_version) &&
@debian_revision.eql?(other.debian_revision)
end
alias == eql?
def <=>(other)
return nil unless other.is_a?(self.class)
cmp = @epoch <=> other.epoch
if cmp == 0
cmp = compare_upstream_version(other)
if cmp == 0
cmp = compare_debian_revision(other)
end
end
cmp
end
attr_reader :epoch, :upstream_version, :debian_revision
private
def initialize(epoch, upstream_version, debian_revision)
@epoch = epoch
@upstream_version = upstream_version
@debian_revision = debian_revision
end
def compare_upstream_version(other)
mine = @upstream_version
yours = other.upstream_version
compare_debian_versions(mine, yours)
end
def compare_debian_revision(other)
mine = @debian_revision
yours = other.debian_revision
compare_debian_versions(mine, yours)
end
def compare_debian_versions(mine, yours)
# First the initial part of each string consisting entirely of non-digit characters is determined.
# These two parts (one of which may be empty) are compared lexically. If a difference is found it is
# returned. The lexical comparison is a comparison of ASCII values modified so that all the letters
# sort earlier than all the non-letters and so that a tilde sorts before anything, even the end of a
# part. For example, the following parts are in sorted order from earliest to latest: ~~, ~~a, ~, the
# empty part, a.
#
# Then the initial part of the remainder of each string which consists entirely of digit characters
# is determined. The numerical values of these two parts are compared, and any difference found is
# returned as the result of the comparison. For these purposes an empty string (which can only occur
# at the end of one or both version strings being compared) counts as zero.
#
# These two steps (comparing and removing initial non-digit strings and initial digit strings) are
# repeated until a difference is found or both strings are exhausted.
mine_index = 0
yours_index = 0
cmp = 0
mine ||= ''
yours ||= ''
while mine_index < mine.length && yours_index < yours.length && cmp == 0
# handle ~
_mymatch, mytilde = *match_tildes(mine.slice(mine_index..-1))
mytilde ||= ''
_yoursmatch, yourstilde = *match_tildes(yours.slice(yours_index..-1))
yourstilde ||= ''
cmp = -1 * (mytilde.length <=> yourstilde.length)
mine_index += mytilde.length
yours_index += yourstilde.length
next unless cmp == 0 # handle letters
_mymatch, myletters = *match_letters(mine.slice(mine_index..-1))
myletters ||= ''
_yoursmatch, yoursletters = *match_letters(yours.slice(yours_index..-1))
yoursletters ||= ''
cmp = myletters <=> yoursletters
mine_index += myletters.length
yours_index += yoursletters.length
next unless cmp == 0 # handle nonletters except tilde
_mymatch, mynon_letters = *match_non_letters(mine.slice(mine_index..-1))
mynon_letters ||= ''
_yoursmatch, yoursnon_letters = *match_non_letters(yours.slice(yours_index..-1))
yoursnon_letters ||= ''
cmp = mynon_letters <=> yoursnon_letters
mine_index += mynon_letters.length
yours_index += yoursnon_letters.length
next unless cmp == 0 # handle digits
_mymatch, mydigits = *match_digits(mine.slice(mine_index..-1))
mydigits ||= ''
_yoursmatch, yoursdigits = *match_digits(yours.slice(yours_index..-1))
yoursdigits ||= ''
cmp = mydigits.to_i <=> yoursdigits.to_i
mine_index += mydigits.length
yours_index += yoursdigits.length
end
if cmp == 0
if mine_index < mine.length && match_tildes(mine[mine_index])
cmp = -1
elsif yours_index < yours.length && match_tildes(yours[yours_index])
cmp = 1
else
cmp = mine.length <=> yours.length
end
end
cmp
end
def match_digits(a)
a.match(/^([0-9]+)/)
end
def match_non_letters(a)
a.match(/^([.+-]+)/)
end
def match_tildes(a)
a.match(/^(~+)/)
end
def match_letters(a)
a.match(/^([A-Za-z]+)/)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/gem.rb | lib/puppet/util/package/version/gem.rb | # frozen_string_literal: true
module Puppet::Util::Package::Version
class Gem < ::Gem::Version
def self.parse(version)
raise ValidationFailure, version unless version.is_a? String
raise ValidationFailure, version unless version =~ ANCHORED_VERSION_PATTERN
new(version)
end
class ValidationFailure < ArgumentError
def initialize(version)
super("#{version} is not a valid ruby gem version.")
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/rpm.rb | lib/puppet/util/package/version/rpm.rb | # frozen_string_literal: true
require_relative '../../../../puppet/util/rpm_compare'
module Puppet::Util::Package::Version
class Rpm < Numeric
# provides Rpm parsing and comparison
extend Puppet::Util::RpmCompare
include Puppet::Util::RpmCompare
include Comparable
class ValidationFailure < ArgumentError; end
attr_reader :epoch, :version, :release, :arch
def self.parse(ver)
raise ValidationFailure unless ver.is_a?(String)
version = rpm_parse_evr(ver)
new(version[:epoch], version[:version], version[:release], version[:arch]).freeze
end
def to_s
version_found = ''.dup
version_found += "#{@epoch}:" if @epoch
version_found += @version
version_found += "-#{@release}" if @release
version_found
end
alias inspect to_s
def eql?(other)
other.is_a?(self.class) &&
@epoch.eql?(other.epoch) &&
@version.eql?(other.version) &&
@release.eql?(other.release) &&
@arch.eql?(other.arch)
end
alias == eql?
def <=>(other)
raise ArgumentError, _("Cannot compare, as %{other} is not a Rpm Version") % { other: other } unless other.is_a?(self.class)
rpm_compare_evr(to_s, other.to_s)
end
private
# overwrite rpm_compare_evr to treat no epoch as zero epoch
# in order to compare version correctly
#
# returns 1 if a is newer than b,
# 0 if they are identical
# -1 if a is older than b
def rpm_compare_evr(a, b)
a_hash = rpm_parse_evr(a)
b_hash = rpm_parse_evr(b)
a_hash[:epoch] ||= '0'
b_hash[:epoch] ||= '0'
rc = compare_values(a_hash[:epoch], b_hash[:epoch])
return rc unless rc == 0
super(a, b)
end
def initialize(epoch, version, release, arch)
@epoch = epoch
@version = version
@release = release
@arch = arch
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/gt_eq.rb | lib/puppet/util/package/version/range/gt_eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class GtEq < Simple
def to_s
">=#{@version}"
end
def include?(version)
version >= @version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/lt.rb | lib/puppet/util/package/version/range/lt.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Lt < Simple
def to_s
"<#{@version}"
end
def include?(version)
version < @version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/min_max.rb | lib/puppet/util/package/version/range/min_max.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range'
module Puppet::Util::Package::Version
class Range
class MinMax
def initialize(min, max)
@min = min
@max = max
end
def to_s
"#{@min} #{@max}"
end
def to_gem_version
"#{@min}, #{@max}"
end
def include?(version)
@min.include?(version) && @max.include?(version)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/simple.rb | lib/puppet/util/package/version/range/simple.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range'
module Puppet::Util::Package::Version
class Range
class Simple
def initialize(version)
@version = version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/eq.rb | lib/puppet/util/package/version/range/eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Eq < Simple
def to_s
@version.to_s
end
def include?(version)
version == @version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/lt_eq.rb | lib/puppet/util/package/version/range/lt_eq.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class LtEq < Simple
def to_s
"<=#{@version}"
end
def include?(version)
version <= @version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/package/version/range/gt.rb | lib/puppet/util/package/version/range/gt.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/util/package/version/range/simple'
module Puppet::Util::Package::Version
class Range
class Gt < Simple
def to_s
">#{@version}"
end
def include?(version)
version > @version
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/log/destinations.rb | lib/puppet/util/log/destinations.rb | # frozen_string_literal: true
Puppet::Util::Log.newdesttype :syslog do
def self.suitable?(obj)
Puppet.features.syslog?
end
def close
Syslog.close
end
def initialize
Syslog.close if Syslog.opened?
name = "puppet-#{Puppet.run_mode.name}"
options = Syslog::LOG_PID | Syslog::LOG_NDELAY
# XXX This should really be configurable.
str = Puppet[:syslogfacility]
begin
facility = Syslog.const_get("LOG_#{str.upcase}")
rescue NameError => e
raise Puppet::Error, _("Invalid syslog facility %{str}") % { str: str }, e.backtrace
end
@syslog = Syslog.open(name, options, facility)
end
def handle(msg)
# XXX Syslog currently has a bug that makes it so you
# cannot log a message with a '%' in it. So, we get rid
# of them.
if msg.source == "Puppet"
msg.to_s.split("\n").each do |line|
@syslog.send(msg.level, line.gsub("%", '%%'))
end
else
msg.to_s.split("\n").each do |line|
@syslog.send(msg.level, "(%s) %s" % [msg.source.to_s.delete("%"),
line.gsub("%", '%%')])
end
end
end
end
Puppet::Util::Log.newdesttype :file do
require 'fileutils'
def self.match?(obj)
obj.is_a?(String) && Puppet::Util.absolute_path?(obj)
end
def close
if defined?(@file)
@file.close
@file = nil
end
end
def flush
@file.flush if defined?(@file)
end
attr_accessor :autoflush
def initialize(path)
@name = path
@json = path.end_with?('.json') ? 1 : 0
@jsonl = path.end_with?('.jsonl')
# first make sure the directory exists
# We can't just use 'Config.use' here, because they've
# specified a "special" destination.
unless Puppet::FileSystem.exist?(Puppet::FileSystem.dir(path))
FileUtils.mkdir_p(File.dirname(path), :mode => 0o755)
Puppet.info _("Creating log directory %{dir}") % { dir: File.dirname(path) }
end
# create the log file, if it doesn't already exist
need_array_start = false
file_exists = Puppet::FileSystem.exist?(path)
if @json == 1
need_array_start = true
if file_exists
sz = File.size(path)
need_array_start = sz == 0
# Assume that entries have been written and that a comma
# is needed before next entry
@json = 2 if sz > 2
end
end
file = File.new(path, File::WRONLY | File::CREAT | File::APPEND)
file.puts('[') if need_array_start
@file = file
@autoflush = Puppet[:autoflush]
end
def handle(msg)
if @json > 0
@json > 1 ? @file.puts(',') : @json = 2
@file.puts(Puppet::Util::Json.dump(msg.to_structured_hash))
elsif @jsonl
@file.puts(Puppet::Util::Json.dump(msg.to_structured_hash))
else
@file.puts("#{msg.time} #{msg.source} (#{msg.level}): #{msg}")
end
@file.flush if @autoflush
end
end
Puppet::Util::Log.newdesttype :logstash_event do
require 'time'
def format(msg)
# logstash_event format is documented at
# https://logstash.jira.com/browse/LOGSTASH-675
data = msg.to_hash
data['version'] = 1
data['@timestamp'] = data['time']
data.delete('time')
data
end
def handle(msg)
message = format(msg)
$stdout.puts Puppet::Util::Json.dump(message)
end
end
Puppet::Util::Log.newdesttype :console do
require_relative '../../../puppet/util/colors'
include Puppet::Util::Colors
def initialize
# Flush output immediately.
$stderr.sync = true
$stdout.sync = true
end
def handle(msg)
levels = {
:emerg => { :name => 'Emergency', :color => :hred, :stream => $stderr },
:alert => { :name => 'Alert', :color => :hred, :stream => $stderr },
:crit => { :name => 'Critical', :color => :hred, :stream => $stderr },
:err => { :name => 'Error', :color => :hred, :stream => $stderr },
:warning => { :name => 'Warning', :color => :hyellow, :stream => $stderr },
:notice => { :name => 'Notice', :color => :reset, :stream => $stdout },
:info => { :name => 'Info', :color => :green, :stream => $stdout },
:debug => { :name => 'Debug', :color => :cyan, :stream => $stdout },
}
str = msg.respond_to?(:multiline) ? msg.multiline : msg.to_s
str = msg.source == "Puppet" ? str : "#{msg.source}: #{str}"
level = levels[msg.level]
level[:stream].puts colorize(level[:color], "#{level[:name]}: #{str}")
end
end
# Log to a transaction report.
Puppet::Util::Log.newdesttype :report do
attr_reader :report
match "Puppet::Transaction::Report"
def initialize(report)
@report = report
end
def handle(msg)
@report << msg
end
end
# Log to an array, just for testing.
module Puppet::Test
class LogCollector
def initialize(logs)
@logs = logs
end
def <<(value)
@logs << value
end
end
end
Puppet::Util::Log.newdesttype :array do
match "Puppet::Test::LogCollector"
def initialize(messages)
@messages = messages
end
def handle(msg)
@messages << msg
end
end
Puppet::Util::Log.newdesttype :eventlog do
# Leaving these in for backwards compatibility - duplicates the same in
# Puppet::Util::Windows::EventLog
Puppet::Util::Log::DestEventlog::EVENTLOG_ERROR_TYPE = 0x0001
Puppet::Util::Log::DestEventlog::EVENTLOG_WARNING_TYPE = 0x0002
Puppet::Util::Log::DestEventlog::EVENTLOG_INFORMATION_TYPE = 0x0004
Puppet::Util::Log::DestEventlog::EVENTLOG_CHARACTER_LIMIT = 31_838
def self.suitable?(obj)
Puppet::Util::Platform.windows?
end
def initialize
@eventlog = Puppet::Util::Windows::EventLog.open("Puppet")
end
def to_native(level)
Puppet::Util::Windows::EventLog.to_native(level)
end
def handle(msg)
native_type, native_id = to_native(msg.level)
stringified_msg = msg.message.to_s
if stringified_msg.length > self.class::EVENTLOG_CHARACTER_LIMIT
warning = "...Message exceeds character length limit, truncating."
truncated_message_length = self.class::EVENTLOG_CHARACTER_LIMIT - warning.length
stringified_truncated_msg = stringified_msg[0..truncated_message_length]
stringified_truncated_msg << warning
msg.message = stringified_truncated_msg
end
@eventlog.report_event(
:event_type => native_type,
:event_id => native_id,
:data => (msg.source && msg.source != 'Puppet' ? "#{msg.source}: " : '') + msg.to_s
)
end
def close
if @eventlog
@eventlog.close
@eventlog = nil
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/util/log/destination.rb | lib/puppet/util/log/destination.rb | # frozen_string_literal: true
# A type of log destination.
class Puppet::Util::Log::Destination
class << self
attr_accessor :name
end
def self.initvars
@matches = []
end
# Mark the things we're supposed to match.
def self.match(obj)
@matches ||= []
@matches << obj
end
# See whether we match a given thing.
def self.match?(obj)
# Convert single-word strings into symbols like :console and :syslog
if obj.is_a? String and obj =~ /^\w+$/
obj = obj.downcase.intern
end
@matches.each do |thing|
# Search for direct matches or class matches
return true if thing === obj or thing == obj.class.to_s
end
false
end
def name
if defined?(@name)
@name
else
self.class.name
end
end
# Set how to handle a message.
def self.sethandler(&block)
define_method(:handle, &block)
end
# Mark how to initialize our object.
def self.setinit(&block)
define_method(:initialize, &block)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.