Response class for Multiple Choices
responses (status code 300).
The Multiple Choices
response indicates that the server offers multiple options for the resource from which the client may choose.
References:
Response class for Multiple Choices
responses (status code 300).
The Multiple Choices
response indicates that the server offers multiple options for the resource from which the client may choose.
References:
Response class for Conflict
responses (status code 409).
The request could not be processed because of conflict in the current state of the resource.
References:
Response class for Service Unavailable
responses (status code 503).
The server cannot handle the request (because it is overloaded or down for maintenance).
References:
BasicSpecification
is an abstract class which implements some common code used by both Specification and StubSpecification.
Raised when there are conflicting gem specs loaded
Represents an error communicating via HTTP.
The SourceList
represents the sources rubygems has been configured to use. A source may be created from an array of sources:
Gem::SourceList.from %w[https://rubygems.example https://internal.example]
Or by adding them:
sources = Gem::SourceList.new sources << 'https://rubygems.example'
The most common way to get a SourceList
is Gem.sources
.
Raised by Encoding
and String
methods when the string being transcoded contains a byte invalid for the either the source or target encoding.
Numeric is the class from which all higher-level numeric classes should inherit.
Numeric allows instantiation of heap-allocated objects. Other core numeric classes such as Integer
are implemented as immediates, which means that each Integer
is a single immutable object which is always passed by value.
a = 1 1.object_id == a.object_id #=> true
There can only ever be one instance of the integer 1
, for example. Ruby
ensures this by preventing instantiation. If duplication is attempted, the same instance is returned.
Integer.new(1) #=> NoMethodError: undefined method `new' for Integer:Class 1.dup #=> 1 1.object_id == 1.dup.object_id #=> true
For this reason, Numeric should be used when defining other numeric classes.
Classes which inherit from Numeric must implement coerce
, which returns a two-member Array
containing an object that has been coerced into an instance of the new class and self
(see coerce
).
Inheriting classes should also implement arithmetic operator methods (+
, -
, *
and /
) and the <=>
operator (see Comparable
). These methods may rely on coerce
to ensure interoperability with instances of other numeric classes.
class Tally < Numeric def initialize(string) @string = string end def to_s @string end def to_i @string.size end def coerce(other) [self.class.new('|' * other.to_i), self] end def <=>(other) to_i <=> other.to_i end def +(other) self.class.new('|' * (to_i + other.to_i)) end def -(other) self.class.new('|' * (to_i - other.to_i)) end def *(other) self.class.new('|' * (to_i * other.to_i)) end def /(other) self.class.new('|' * (to_i / other.to_i)) end end tally = Tally.new('||') puts tally * 2 #=> "||||" puts tally > 1 #=> true
First, what’s elsewhere. Class
Numeric:
Inherits from class Object.
Includes module Comparable.
Here, class Numeric provides methods for:
finite?
: Returns true unless self
is infinite or not a number.
infinite?
: Returns -1, nil
or +1, depending on whether self
is -Infinity<tt>, finite, or <tt>+Infinity
.
integer?
: Returns whether self
is an integer.
negative?
: Returns whether self
is negative.
nonzero?
: Returns whether self
is not zero.
positive?
: Returns whether self
is positive.
real?
: Returns whether self
is a real value.
zero?
: Returns whether self
is zero.
<=>
: Returns:
-1 if self
is less than the given value.
0 if self
is equal to the given value.
1 if self
is greater than the given value.
nil
if self
and the given value are not comparable.
eql?
: Returns whether self
and the given value have the same value and type.
%
(aliased as modulo
): Returns the remainder of self
divided by the given value.
-@
: Returns the value of self
, negated.
abs
(aliased as magnitude
): Returns the absolute value of self
.
abs2
: Returns the square of self
.
angle
(aliased as arg
and phase
): Returns 0 if self
is positive, Math::PI otherwise.
ceil
: Returns the smallest number greater than or equal to self
, to a given precision.
coerce
: Returns array [coerced_self, coerced_other]
for the given other value.
conj
(aliased as conjugate
): Returns the complex conjugate of self
.
denominator
: Returns the denominator (always positive) of the Rational
representation of self
.
div
: Returns the value of self
divided by the given value and converted to an integer.
divmod
: Returns array [quotient, modulus]
resulting from dividing self
the given divisor.
fdiv
: Returns the Float
result of dividing self
by the given divisor.
floor
: Returns the largest number less than or equal to self
, to a given precision.
i
: Returns the Complex
object Complex(0, self)
. the given value.
imaginary
(aliased as imag
): Returns the imaginary part of the self
.
numerator
: Returns the numerator of the Rational
representation of self
; has the same sign as self
.
polar
: Returns the array [self.abs, self.arg]
.
quo
: Returns the value of self
divided by the given value.
real
: Returns the real part of self
.
rect
(aliased as rectangular
): Returns the array [self, 0]
.
remainder
: Returns self-arg*(self/arg).truncate
for the given arg
.
round
: Returns the value of self
rounded to the nearest value for the given a precision.
to_int
: Returns the Integer
representation of self
, truncating if necessary.
truncate
: Returns self
truncated (toward zero) to a given precision.
Class
Exception
and its subclasses are used to indicate that an error or other problem has occurred, and may need to be handled. See Exceptions.
An Exception
object carries certain information:
The type (the exception’s class), commonly StandardError
, RuntimeError
, or a subclass of one or the other; see Built-In Exception Class Hierarchy.
An optional descriptive message; see methods ::new
, message
.
Optional backtrace information; see methods backtrace
, backtrace_locations
, set_backtrace
.
An optional cause; see method cause
.
Class
Hierarchy The hierarchy of built-in subclasses of class Exception
:
Errno
(and its subclasses, representing system errors)
Raised when a signal is received.
begin Process.kill('HUP',Process.pid) sleep # wait for receiver to handle signal sent by Process.kill rescue SignalException => e puts "received Exception #{e}" end
produces:
received Exception SIGHUP
BasicSocket
is the super class for all the Socket
classes.
BasicObject
is the parent class of all classes in Ruby
. In particular, BasicObject
is the parent class of class Object
, which is itself the default parent class of every Ruby
class:
class Foo; end Foo.superclass # => Object Object.superclass # => BasicObject
BasicObject
is the only class that has no parent:
BasicObject.superclass # => nil
Class
BasicObject
can be used to create an object hierarchy (e.g., class Delegator
) that is independent of Ruby’s object hierarchy. Such objects:
Do not have namespace “pollution” from the many methods provided in class Object
and its included module Kernel
.
Do not have definitions of common classes, and so references to such common classes must be fully qualified (::String
, not String
).
A variety of strategies can be used to provide useful portions of the Standard Library in subclasses of BasicObject
:
The immediate subclass could include Kernel
, which would define methods such as puts
, exit
, etc.
A custom Kernel-like module could be created and included.
Delegation can be used via method_missing
:
class MyObjectSystem < BasicObject DELEGATE = [:puts, :p] def method_missing(name, *args, &block) return super unless DELEGATE.include? name ::Kernel.send(name, *args, &block) end def respond_to_missing?(name, include_private = false) DELEGATE.include?(name) end end
These are the methods defined for BasicObject:
::new
: Returns a new BasicObject instance.
!
: Returns the boolean negation of self
: true
or false
.
!=
: Returns whether self
and the given object are not equal.
==
: Returns whether self
and the given object are equivalent.
__id__
: Returns the integer object identifier for self
.
__send__
: Calls the method identified by the given symbol.
equal?
: Returns whether self
and the given object are the same object.
instance_eval
: Evaluates the given string or block in the context of self
.
instance_exec
: Executes the given block in the context of self
, passing the given arguments.
method_missing
: Called when self
is called with a method it does not define.
singleton_method_added
: Called when a singleton method is added to self
.
singleton_method_removed
: Called when a singleton method is removed from self
.
singleton_method_undefined
: Called when a singleton method is undefined in self
.
A class that provides the functionality of Kernel#set_trace_func
in a well-structured Object-Oriented API.
Use TracePoint
to gather information specifically for exceptions:
trace = TracePoint.new(:raise) do |tp| p [tp.lineno, tp.event, tp.raised_exception] end #=> #<TracePoint:disabled> trace.enable #=> false 0 / 0 #=> [5, :raise, #<ZeroDivisionError: divided by 0>]
If you don’t specify the types of events you want to listen for, TracePoint
will include all available events.
Note: Do not depend on the current event set, as this list is subject to change. Instead, it is recommended to specify the types of events you want to use.
To filter what is traced, you can pass any of the following as events
:
:line
Execute an expression or statement on a new line.
:class
Start a class or module definition.
:end
Finish a class or module definition.
:call
Call a Ruby
method.
:return
Return from a Ruby
method.
:c_call
Call a C-language routine.
:c_return
Return from a C-language routine.
:raise
Raise an exception.
:rescue
Rescue an exception.
:b_call
Event hook at block entry.
:b_return
Event hook at block ending.
:a_call
Event hook at all calls (call
, b_call
, and c_call
).
:a_return
Event hook at all returns (return
, b_return
, and c_return
).
:thread_begin
Event hook at thread beginning.
:thread_end
Event hook at thread ending.
:fiber_switch
Event hook at fiber switch.
:script_compiled
New Ruby
code compiled (with eval
, load
, or require
).
The objspace library extends the ObjectSpace
module and adds several methods to get internal statistic information about object/memory management.
You need to require 'objspace'
to use this extension module.
Generally, you SHOULD NOT use this library if you do not know about the MRI implementation. Mainly, this library is for (memory) profiler developers and MRI developers who need to know about MRI memory usage.
The ObjectSpace
module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.
ObjectSpace
also provides support for object finalizers, procs that will be called after a specific object was destroyed by garbage collection. See the documentation for ObjectSpace.define_finalizer
for important information on how to use this method correctly.
a = "A" b = "B" ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" }) ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" }) a = nil b = nil
produces:
Finalizer two on 537763470 Finalizer one on 537763480
OpenSSL
provides SSL
, TLS and general purpose cryptography. It wraps the OpenSSL library.
All examples assume you have loaded OpenSSL
with:
require 'openssl'
These examples build atop each other. For example the key created in the next is used in throughout these examples.
This example creates a 2048 bit RSA keypair and writes it to the current directory.
key = OpenSSL::PKey::RSA.new 2048 File.write 'private_key.pem', key.private_to_pem File.write 'public_key.pem', key.public_to_pem
Keys saved to disk without encryption are not secure as anyone who gets ahold of the key may use it unless it is encrypted. In order to securely export a key you may export it with a password.
cipher = OpenSSL::Cipher.new 'aes-256-cbc' password = 'my secure password goes here' key_secure = key.private_to_pem cipher, password File.write 'private.secure.pem', key_secure
OpenSSL::Cipher.ciphers
returns a list of available ciphers.
A key can also be loaded from a file.
key2 = OpenSSL::PKey.read File.read 'private_key.pem' key2.public? # => true key2.private? # => true
or
key3 = OpenSSL::PKey.read File.read 'public_key.pem' key3.public? # => true key3.private? # => false
OpenSSL
will prompt you for your password when loading an encrypted key. If you will not be able to type in the password you may provide it when loading the key:
key4_pem = File.read 'private.secure.pem' password = 'my secure password goes here' key4 = OpenSSL::PKey.read key4_pem, password
RSA provides encryption and decryption using the public and private keys. You can use a variety of padding methods depending upon the intended use of encrypted data.
Asymmetric public/private key encryption is slow and victim to attack in cases where it is used without padding or directly to encrypt larger chunks of data. Typical use cases for RSA encryption involve “wrapping” a symmetric key with the public key of the recipient who would “unwrap” that symmetric key again using their private key. The following illustrates a simplified example of such a key transport scheme. It shouldn’t be used in practice, though, standardized protocols should always be preferred.
wrapped_key = key.public_encrypt key
A symmetric key encrypted with the public key can only be decrypted with the corresponding private key of the recipient.
original_key = key.private_decrypt wrapped_key
By default PKCS#1 padding will be used, but it is also possible to use other forms of padding, see PKey::RSA
for further details.
Using “private_encrypt” to encrypt some data with the private key is equivalent to applying a digital signature to the data. A verifying party may validate the signature by comparing the result of decrypting the signature with “public_decrypt” to the original data. However, OpenSSL::PKey
already has methods “sign” and “verify” that handle digital signatures in a standardized way - “private_encrypt” and “public_decrypt” shouldn’t be used in practice.
To sign a document, a cryptographically secure hash of the document is computed first, which is then signed using the private key.
signature = key.sign 'SHA256', document
To validate the signature, again a hash of the document is computed and the signature is decrypted using the public key. The result is then compared to the hash just computed, if they are equal the signature was valid.
if key.verify 'SHA256', signature, document puts 'Valid' else puts 'Invalid' end
If supported by the underlying OpenSSL
version used, Password-based Encryption should use the features of PKCS5
. If not supported or if required by legacy applications, the older, less secure methods specified in RFC 2898 are also supported (see below).
PKCS5
supports PBKDF2 as it was specified in PKCS#5 v2.0. It still uses a password, a salt, and additionally a number of iterations that will slow the key derivation process down. The slower this is, the more work it requires being able to brute-force the resulting key.
The strategy is to first instantiate a Cipher
for encryption, and then to generate a random IV plus a key derived from the password using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt, the number of iterations largely depends on the hardware being used.
cipher = OpenSSL::Cipher.new 'aes-256-cbc' cipher.encrypt iv = cipher.random_iv pwd = 'some hopefully not to easily guessable password' salt = OpenSSL::Random.random_bytes 16 iter = 20000 key_len = cipher.key_len digest = OpenSSL::Digest.new('SHA256') key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest) cipher.key = key Now encrypt the data: encrypted = cipher.update document encrypted << cipher.final
Use the same steps as before to derive the symmetric AES key, this time setting the Cipher
up for decryption.
cipher = OpenSSL::Cipher.new 'aes-256-cbc' cipher.decrypt cipher.iv = iv # the one generated with #random_iv pwd = 'some hopefully not to easily guessable password' salt = ... # the one generated above iter = 20000 key_len = cipher.key_len digest = OpenSSL::Digest.new('SHA256') key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest) cipher.key = key Now decrypt the data: decrypted = cipher.update encrypted decrypted << cipher.final
X509
Certificates This example creates a self-signed certificate using an RSA key and a SHA1 signature.
key = OpenSSL::PKey::RSA.new 2048 name = OpenSSL::X509::Name.parse '/CN=nobody/DC=example' cert = OpenSSL::X509::Certificate.new cert.version = 2 cert.serial = 0 cert.not_before = Time.now cert.not_after = Time.now + 3600 cert.public_key = key.public_key cert.subject = name
You can add extensions to the certificate with OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert cert.add_extension \ extension_factory.create_extension('basicConstraints', 'CA:FALSE', true) cert.add_extension \ extension_factory.create_extension( 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature') cert.add_extension \ extension_factory.create_extension('subjectKeyIdentifier', 'hash')
The list of supported extensions (and in some cases their possible values) can be derived from the “objects.h” file in the OpenSSL
source code.
To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
with a digest algorithm. This creates a self-signed cert because we’re using the same name and key to sign the certificate as was used to create the certificate.
cert.issuer = name cert.sign key, OpenSSL::Digest.new('SHA1') open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
Like a key, a cert can also be loaded from a file.
cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
Certificate#verify will return true when a certificate was signed with the given public key.
raise 'certificate can not be verified' unless cert2.verify key
A certificate authority (CA) is a trusted third party that allows you to verify the ownership of unknown certificates. The CA issues key signatures that indicate it trusts the user of that key. A user encountering the key can verify the signature by using the CA’s public key.
CA keys are valuable, so we encrypt and save it to disk and make sure it is not readable by other users.
ca_key = OpenSSL::PKey::RSA.new 2048 password = 'my secure password goes here' cipher = 'aes-256-cbc' open 'ca_key.pem', 'w', 0400 do |io| io.write ca_key.private_to_pem(cipher, password) end
A CA certificate is created the same way we created a certificate above, but with different extensions.
ca_name = OpenSSL::X509::Name.parse '/CN=ca/DC=example' ca_cert = OpenSSL::X509::Certificate.new ca_cert.serial = 0 ca_cert.version = 2 ca_cert.not_before = Time.now ca_cert.not_after = Time.now + 86400 ca_cert.public_key = ca_key.public_key ca_cert.subject = ca_name ca_cert.issuer = ca_name extension_factory = OpenSSL::X509::ExtensionFactory.new extension_factory.subject_certificate = ca_cert extension_factory.issuer_certificate = ca_cert ca_cert.add_extension \ extension_factory.create_extension('subjectKeyIdentifier', 'hash')
This extension indicates the CA’s key may be used as a CA.
ca_cert.add_extension \ extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
This extension indicates the CA’s key may be used to verify signatures on both certificates and certificate revocations.
ca_cert.add_extension \ extension_factory.create_extension( 'keyUsage', 'cRLSign,keyCertSign', true)
Root CA certificates are self-signed.
ca_cert.sign ca_key, OpenSSL::Digest.new('SHA1')
The CA certificate is saved to disk so it may be distributed to all the users of the keys this CA will sign.
open 'ca_cert.pem', 'w' do |io| io.write ca_cert.to_pem end
The CA signs keys through a Certificate Signing Request (CSR). The CSR contains the information necessary to identify the key.
csr = OpenSSL::X509::Request.new csr.version = 0 csr.subject = name csr.public_key = key.public_key csr.sign key, OpenSSL::Digest.new('SHA1')
A CSR is saved to disk and sent to the CA for signing.
open 'csr.pem', 'w' do |io| io.write csr.to_pem end
Upon receiving a CSR the CA will verify it before signing it. A minimal verification would be to check the CSR’s signature.
csr = OpenSSL::X509::Request.new File.read 'csr.pem' raise 'CSR can not be verified' unless csr.verify csr.public_key
After verification a certificate is created, marked for various usages, signed with the CA key and returned to the requester.
csr_cert = OpenSSL::X509::Certificate.new csr_cert.serial = 0 csr_cert.version = 2 csr_cert.not_before = Time.now csr_cert.not_after = Time.now + 600 csr_cert.subject = csr.subject csr_cert.public_key = csr.public_key csr_cert.issuer = ca_cert.subject extension_factory = OpenSSL::X509::ExtensionFactory.new extension_factory.subject_certificate = csr_cert extension_factory.issuer_certificate = ca_cert csr_cert.add_extension \ extension_factory.create_extension('basicConstraints', 'CA:FALSE') csr_cert.add_extension \ extension_factory.create_extension( 'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature') csr_cert.add_extension \ extension_factory.create_extension('subjectKeyIdentifier', 'hash') csr_cert.sign ca_key, OpenSSL::Digest.new('SHA1') open 'csr_cert.pem', 'w' do |io| io.write csr_cert.to_pem end
SSL
and TLS Connections Using our created key and certificate we can create an SSL
or TLS connection. An SSLContext is used to set up an SSL
session.
context = OpenSSL::SSL::SSLContext.new
SSL
Server An SSL
server requires the certificate and private key to communicate securely with its clients:
context.cert = cert context.key = key
Then create an SSLServer with a TCP server socket and the context. Use the SSLServer like an ordinary TCP server.
require 'socket' tcp_server = TCPServer.new 5000 ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context loop do ssl_connection = ssl_server.accept data = ssl_connection.gets response = "I got #{data.dump}" puts response ssl_connection.puts "I got #{data.dump}" ssl_connection.close end
SSL
client An SSL
client is created with a TCP socket and the context. SSLSocket#connect must be called to initiate the SSL
handshake and start encryption. A key and certificate are not required for the client socket.
Note that SSLSocket#close doesn’t close the underlying socket by default. Set
SSLSocket#sync_close to true if you want.
require 'socket' tcp_socket = TCPSocket.new 'localhost', 5000 ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context ssl_client.sync_close = true ssl_client.connect ssl_client.puts "hello server!" puts ssl_client.gets ssl_client.close # shutdown the TLS connection and close tcp_socket
An unverified SSL
connection does not provide much security. For enhanced security the client or server can verify the certificate of its peer.
The client can be modified to verify the server’s certificate against the certificate authority’s certificate:
context.ca_file = 'ca_cert.pem' context.verify_mode = OpenSSL::SSL::VERIFY_PEER require 'socket' tcp_socket = TCPSocket.new 'localhost', 5000 ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context ssl_client.connect ssl_client.puts "hello server!" puts ssl_client.gets
If the server certificate is invalid or context.ca_file
is not set when verifying peers an OpenSSL::SSL::SSLError
will be raised.
This module provides access to the zlib library. Zlib
is designed to be a portable, free, general-purpose, legally unencumbered – that is, not covered by any patents – lossless data-compression library for use on virtually any computer hardware and operating system.
The zlib compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data.
The zlib compressed data format is described in RFC 1950, which is a wrapper around a deflate stream which is described in RFC 1951.
The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of IO
. The gzip format is described in RFC 1952 which is also a wrapper around a deflate stream.
The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single-file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib.
See your system’s zlib.h for further information about zlib
Using the wrapper to compress strings with default parameters is quite simple:
require "zlib" data_to_compress = File.read("don_quixote.txt") puts "Input size: #{data_to_compress.size}" #=> Input size: 2347740 data_compressed = Zlib::Deflate.deflate(data_to_compress) puts "Compressed size: #{data_compressed.size}" #=> Compressed size: 887238 uncompressed_data = Zlib::Inflate.inflate(data_compressed) puts "Uncompressed data is: #{uncompressed_data}" #=> Uncompressed data is: The Project Gutenberg EBook of Don Quixote...
Class
tree (if you have GZIP_SUPPORT)
Include the English
library file in a Ruby
script, and you can reference the global variables such as $_
using less cryptic names, listed below.
Without ‘English’:
$\ = ' -- ' "waterbuffalo" =~ /buff/ print $', $$, "\n"
With English:
require "English" $OUTPUT_FIELD_SEPARATOR = ' -- ' "waterbuffalo" =~ /buff/ print $POSTMATCH, $PID, "\n"
Below is a full list of descriptive aliases and their associated global variable:
$!
$@
$;
$;
$,
$,
$/
$/
$\
$\
$.
$.
$_
$>
$<
$$
$$
$?
$~
$*
$&
$‘
$‘
$+
Module
Process
represents a process in the underlying operating system. Its methods support management of the current process and its child processes.
Process
Creation Each of the following methods executes a given command in a new process or subshell, or multiple commands in new processes and/or subshells. The choice of process or subshell depends on the form of the command; see Argument command_line or exe_path.
Process.spawn
, Kernel#spawn
: Executes the command; returns the new pid without waiting for completion.
Process.exec
: Replaces the current process by executing the command.
In addition:
Method
Kernel#system
executes a given command-line (string) in a subshell; returns true
, false
, or nil
.
Method
Kernel#`
executes a given command-line (string) in a subshell; returns its $stdout string.
Module
Open3
supports creating child processes with access to their $stdin, $stdout, and $stderr streams.
Optional leading argument env
is a hash of name/value pairs, where each name is a string and each value is a string or nil
; each name/value pair is added to ENV
in the new process.
Process.spawn( 'ruby -e "p ENV[\"Foo\"]"') Process.spawn({'Foo' => '0'}, 'ruby -e "p ENV[\"Foo\"]"')
Output:
"0"
The effect is usually similar to that of calling ENV#update with argument env
, where each named environment variable is created or updated (if the value is non-nil
), or deleted (if the value is nil
).
However, some modifications to the calling process may remain if the new process fails. For example, hard resource limits are not restored.
command_line
or exe_path
The required string argument is one of the following:
command_line
if it begins with a shell reserved word or special built-in, or if it contains one or more meta characters.
exe_path
otherwise.
command_line
String argument command_line
is a command line to be passed to a shell; it must begin with a shell reserved word, begin with a special built-in, or contain meta characters:
system('if true; then echo "Foo"; fi') # => true # Shell reserved word. system('exit') # => true # Built-in. system('date > /tmp/date.tmp') # => true # Contains meta character. system('date > /nop/date.tmp') # => false system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
The command line may also contain arguments and options for the command:
system('echo "Foo"') # => true
Output:
Foo
See Execution Shell for details about the shell.
exe_path
Argument exe_path
is one of the following:
The string path to an executable file to be called:
Example:
system('/usr/bin/date') # => true # Path to date on Unix-style system. system('foo') # => nil # Command execlution failed.
Output:
Thu Aug 31 10:06:48 AM CDT 2023
A path or command name containing spaces without arguments cannot be distinguished from command_line
above, so you must quote or escape the entire command name using a shell in platform dependent manner, or use the array form below.
If exe_path
does not contain any path separator, an executable file is searched from directories specified with the PATH
environment variable. What the word “executable” means here is depending on platforms.
Even if the file considered “executable”, its content may not be in proper executable format. In that case, Ruby
tries to run it by using /bin/sh
on a Unix-like system, like system(3) does.
File.write('shell_command', 'echo $SHELL', perm: 0o755) system('./shell_command') # prints "/bin/sh" or something.
A 2-element array containing the path to an executable and the string to be used as the name of the executing process:
Example:
pid = spawn(['sleep', 'Hello!'], '1') # 2-element array. p `ps -p #{pid} -o command=`
Output:
"Hello! 1\n"
args
If command_line
does not contain shell meta characters except for spaces and tabs, or exe_path
is given, Ruby
invokes the executable directly. This form does not use the shell:
spawn("doesnt_exist") # Raises Errno::ENOENT spawn("doesnt_exist", "\n") # Raises Errno::ENOENT spawn("doesnt_exist\n") # => false # sh: 1: doesnot_exist: not found
The error message is from a shell and would vary depending on your system.
If one or more args
is given after exe_path
, each is an argument or option to be passed to the executable:
Example:
system('echo', '<', 'C*', '|', '$SHELL', '>') # => true
Output:
< C* | $SHELL >
However, there are exceptions on Windows. See Execution Shell on Windows.
If you want to invoke a path containing spaces with no arguments without shell, you will need to use a 2-element array exe_path
.
Example:
path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' spawn(path) # Raises Errno::ENOENT; No such file or directory - /Applications/Google spawn([path] * 2)
Optional trailing argument options
is a hash of execution options.
:chdir
) By default, the working directory for the new process is the same as that of the current process:
Dir.chdir('/var') Process.spawn('ruby -e "puts Dir.pwd"')
Output:
/var
Use option :chdir
to set the working directory for the new process:
Process.spawn('ruby -e "puts Dir.pwd"', {chdir: '/tmp'})
Output:
/tmp
The working directory of the current process is not changed:
Dir.pwd # => "/var"
Use execution options for file redirection in the new process.
The key for such an option may be an integer file descriptor (fd), specifying a source, or an array of fds, specifying multiple sources.
An integer source fd may be specified as:
n: Specifies file descriptor n.
There are these shorthand symbols for fds:
:in
: Specifies file descriptor 0 (STDIN).
:out
: Specifies file descriptor 1 (STDOUT).
:err
: Specifies file descriptor 2 (STDERR).
The value given with a source is one of:
n: Redirects to fd n in the parent process.
filepath
: Redirects from or to the file at filepath
via open(filepath, mode, 0644)
, where mode
is 'r'
for source :in
, or 'w'
for source :out
or :err
.
[filepath]
: Redirects from the file at filepath
via open(filepath, 'r', 0644)
.
[filepath, mode]
: Redirects from or to the file at filepath
via open(filepath, mode, 0644)
.
[filepath, mode, perm]
: Redirects from or to the file at filepath
via open(filepath, mode, perm)
.
[:child, fd]
: Redirects to the redirected fd
.
:close
: Closes the file descriptor in child process.
See Access Modes and File Permissions.
:unsetenv_others
) By default, the new process inherits environment variables from the parent process; use execution option key :unsetenv_others
with value true
to clear environment variables in the new process.
Any changes specified by execution option env
are made after the new process inherits or clears its environment variables; see Execution Environment.
:umask
) Use execution option :umask
to set the file-creation access for the new process; see Access Modes:
command = 'ruby -e "puts sprintf(\"0%o\", File.umask)"' options = {:umask => 0644} Process.spawn(command, options)
Output:
0644
Process
Groups (:pgroup
and :new_pgroup
) By default, the new process belongs to the same process group as the parent process.
To specify a different process group. use execution option :pgroup
with one of the following values:
true
: Create a new process group for the new process.
pgid: Create the new process in the process group whose id is pgid.
On Windows only, use execution option :new_pgroup
with value true
to create a new process group for the new process.
Use execution options to set resource limits.
The keys for these options are symbols of the form :rlimit_resource_name
, where resource_name is the downcased form of one of the string resource names described at method Process.setrlimit
. For example, key :rlimit_cpu
corresponds to resource limit 'CPU'
.
The value for such as key is one of:
An integer, specifying both the current and maximum limits.
A 2-element array of integers, specifying the current and maximum limits.
By default, the new process inherits file descriptors from the parent process.
Use execution option :close_others => true
to modify that inheritance by closing non-standard fds (3 and greater) that are not otherwise redirected.
On a Unix-like system, the shell invoked is /bin/sh
; the entire string command_line
is passed as an argument to shell option -c.
The shell performs normal shell expansion on the command line:
Example:
system('echo $SHELL: C*') # => true
Output:
/bin/bash: CONTRIBUTING.md COPYING COPYING.ja
On Windows, the shell invoked is determined by environment variable RUBYSHELL
, if defined, or COMSPEC
otherwise; the entire string command_line
is passed as an argument to -c
option for RUBYSHELL
, as well as /bin/sh
, and /c option for COMSPEC
. The shell is invoked automatically in the following cases:
The command is a built-in of cmd.exe
, such as echo
.
The executable file is a batch file; its name ends with .bat
or .cmd
.
Note that the command will still be invoked as command_line
form even when called in exe_path
form, because cmd.exe
does not accept a script name like /bin/sh
does but only works with /c
option.
The standard shell cmd.exe
performs environment variable expansion but does not have globbing functionality:
Example:
system("echo %COMSPEC%: C*")' # => true
Output:
C:\WINDOWS\system32\cmd.exe: C*
::argv0
: Returns the process name as a frozen string.
::egid
: Returns the effective group ID.
::euid
: Returns the effective user ID.
::getpgrp
: Return the process group ID.
::getrlimit
: Returns the resource limit.
::gid
: Returns the (real) group ID.
::pid
: Returns the process ID.
::ppid
: Returns the process ID of the parent process.
::uid
: Returns the (real) user ID.
::egid=
: Sets the effective group ID.
::euid=
: Sets the effective user ID.
::gid=
: Sets the (real) group ID.
::setproctitle
: Sets the process title.
::setpgrp
: Sets the process group ID of the process to zero.
::setrlimit
: Sets a resource limit.
::setsid
: Establishes the process as a new session and process group leader, with no controlling tty.
::uid=
: Sets the user ID.
::abort
: Immediately terminates the process.
::daemon
: Detaches the process from its controlling terminal and continues running it in the background as system daemon.
::exec
: Replaces the process by running a given external command.
::exit
: Initiates process termination by raising exception SystemExit
(which may be caught).
::exit!
: Immediately exits the process.
::warmup
: Notifies the Ruby
virtual machine that the boot sequence for the application is completed, and that the VM may begin optimizing the application.
::detach
: Guards against a child process becoming a zombie.
::fork
: Creates a child process.
::kill
: Sends a given signal to processes.
::spawn
: Creates a child process.
::wait
, ::waitpid
: Waits for a child process to exit; returns its process ID.
::wait2
, ::waitpid2
: Waits for a child process to exit; returns its process ID and status.
::waitall
: Waits for all child processes to exit; returns their process IDs and statuses.
Process
Groups ::getpgid
: Returns the process group ID for a process.
::getpriority
: Returns the scheduling priority for a process, process group, or user.
::getsid
: Returns the session ID for a process.
::groups
: Returns an array of the group IDs in the supplemental group access list for this process.
::groups=
: Sets the supplemental group access list to the given array of group IDs.
::initgroups
: Initializes the supplemental group access list.
::last_status
: Returns the status of the last executed child process in the current thread.
::maxgroups
: Returns the maximum number of group IDs allowed in the supplemental group access list.
::maxgroups=
: Sets the maximum number of group IDs allowed in the supplemental group access list.
::setpgid
: Sets the process group ID of a process.
::setpriority
: Sets the scheduling priority for a process, process group, or user.
::clock_getres
: Returns the resolution of a system clock.
::clock_gettime
: Returns the time from a system clock.
::times
: Returns a Process::Tms
object containing times for the current process and its child processes.
Implementation of an X.509 certificate as specified in RFC 5280. Provides access to a certificate’s attributes and allows certificates to be read from a string, but also supports the creation of new certificates from scratch.
Certificate
is capable of handling DER-encoded certificates and certificates encoded in OpenSSL’s PEM format.
raw = File.binread "cert.cer" # DER- or PEM-encoded certificate = OpenSSL::X509::Certificate.new raw
A certificate may be encoded in DER format
cert = ... File.open("cert.cer", "wb") { |f| f.print cert.to_der }
or in PEM format
cert = ... File.open("cert.pem", "wb") { |f| f.print cert.to_pem }
X.509 certificates are associated with a private/public key pair, typically a RSA, DSA or ECC key (see also OpenSSL::PKey::RSA
, OpenSSL::PKey::DSA
and OpenSSL::PKey::EC
), the public key itself is stored within the certificate and can be accessed in form of an OpenSSL::PKey
. Certificates are typically used to be able to associate some form of identity with a key pair, for example web servers serving pages over HTTPs use certificates to authenticate themselves to the user.
The public key infrastructure (PKI) model relies on trusted certificate authorities (“root CAs”) that issue these certificates, so that end users need to base their trust just on a selected few authorities that themselves again vouch for subordinate CAs issuing their certificates to end users.
The OpenSSL::X509
module provides the tools to set up an independent PKI, similar to scenarios where the ‘openssl’ command line tool is used for issuing certificates in a private PKI.
First, we need to create a “self-signed” root certificate. To do so, we need to generate a key first. Please note that the choice of “1” as a serial number is considered a security flaw for real certificates. Secure choices are integers in the two-digit byte range and ideally not sequential but secure random numbers, steps omitted here to keep the example concise.
root_key = OpenSSL::PKey::RSA.new 2048 # the CA's public/private key root_ca = OpenSSL::X509::Certificate.new root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate root_ca.serial = 1 root_ca.subject = OpenSSL::X509::Name.parse "/DC=org/DC=ruby-lang/CN=Ruby CA" root_ca.issuer = root_ca.subject # root CA's are "self-signed" root_ca.public_key = root_key.public_key root_ca.not_before = Time.now root_ca.not_after = root_ca.not_before + 2 * 365 * 24 * 60 * 60 # 2 years validity ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = root_ca ef.issuer_certificate = root_ca root_ca.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true)) root_ca.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true)) root_ca.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false)) root_ca.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false)) root_ca.sign(root_key, OpenSSL::Digest.new('SHA256'))
The next step is to create the end-entity certificate using the root CA certificate.
key = OpenSSL::PKey::RSA.new 2048 cert = OpenSSL::X509::Certificate.new cert.version = 2 cert.serial = 2 cert.subject = OpenSSL::X509::Name.parse "/DC=org/DC=ruby-lang/CN=Ruby certificate" cert.issuer = root_ca.subject # root CA is the issuer cert.public_key = key.public_key cert.not_before = Time.now cert.not_after = cert.not_before + 1 * 365 * 24 * 60 * 60 # 1 years validity ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = cert ef.issuer_certificate = root_ca cert.add_extension(ef.create_extension("keyUsage","digitalSignature", true)) cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false)) cert.sign(root_key, OpenSSL::Digest.new('SHA256'))