# Passenger Namespace Reference

Common code for all agents. More...

## Classes

class | DirectoryMapper
| Utility class for determining URI-to-application directory mappings. More...
class | AbstractSpawnManager
| Spawning of application processes. More...
class | EventedClient
| A utility class for making I/O handling in non-blocking libev evented servers much easier. More...
class | EventedMessageServer
| Note when overriding onNewClient: call the parent method first! It does some initialization but might disconnect the client if that initialization fails. More...
class | EventedServer
| A base class for writing single-threaded, evented servers that use non-blocking I/O. More...
class | SystemException
| Represents an error returned by a system call or a standard library call. More...
class | FileSystemException
| A filesystem error, as returned by the operating system. More...
class | TimeRetrievalException
| Unable to retrieve the system time using `time()`. More...
class | IOException
| Represents an error that occured during an I/O operation. More...
class | FileNotFoundException
| Thrown when a certain file cannot be found. More...
class | EOFException
| An unexpected end-of-file I/O error. More...
class | ConfigurationException
| Thrown when an invalid configuration is given. More...
class | SpawnException
| Thrown when SpawnManager or ApplicationPool fails to spawn an application instance. More...
class | ArgumentException
| Indicates that a specified argument is incorrect or violates a requirement. More...
class | RuntimeException
| A generic runtime exception. More...
class | TimeoutException
| An exception indicating that some timeout expired. More...
class | SecurityException
| Represents some kind of security error. More...
class | BusyException
| The application pool is too busy and cannot fulfill a get() request. More...
class | SyntaxError
| A parser detected a syntax error. More...
class | FileDescriptor
| Wrapper class around a file descriptor integer, for RAII behavior. More...
class | FileDescriptorPair
| A structure containing two FileDescriptor objects. More...
class | EventFd
| A synchronization mechanism that's implemented with file descriptors, and as such can be used in combination with select() and friends. More...
class | MessageChannel
| Convenience class for I/O operations on file descriptors. More...
class | Uint16Message
| For 16-bit big-endian integers. More...
class | Uint32Message
| For 32-bit big-endian integers. More...
class | ArrayMessage
| For array messages. More...
class | ScalarMessage
| Class for reading a scalar message. More...
class | MessageServer
| Simple pluggable request/response messaging server framework. More...
struct | PoolOptions
| This struct encapsulates information for ApplicationPool::get() and for SpawnManager::spawn(), such as which application is to be spawned. More...
class | Process
| Represents a single application process, as spawned by SpawnManager or by ApplicationPool::Interface::get(). More...
class | RandomGenerator
| A random data generator. More...
class | ResourceLocator
| Locates various Phusion Passenger resources on the filesystem. More...
class | SafeLibev
| Class for thread-safely using libev. More...
class | Session
| Represents a single request/response pair of an application process. More...
class | StandardSession
| A "standard" implementation of Session. More...
class | SpawnManager
| An AbstractSpawnManager implementation. More...
class | StaticString
| An immutable, static byte buffer. More...
class | BufferedUpload
| Represents a buffered upload file. More...
class | HttpStatusExtractor
| Utility class for extracting the HTTP status value from an HTTP response. More...
class | ScgiRequestParser
| A parser for SCGI requests. More...

## Typedefs

typedef shared_ptr < AbstractSpawnManager > | AbstractSpawnManagerPtr
| Convenient alias for AbstractSpawnManager smart pointer.
typedef shared_ptr< Process > | ProcessPtr
| Convenient alias for Process smart pointer.
typedef shared_ptr< SpawnManager > | SpawnManagerPtr
| Convenient alias for SpawnManager smart pointer.

## Enumerations

enum | FileType { FT_NONEXISTANT, FT_REGULAR, FT_DIRECTORY, FT_OTHER }
| Enumeration which indicates what kind of file a file is. More...

## Functions

apr_bucket * | passenger_bucket_create (SessionPtr session, PassengerBucketStatePtr state, apr_bucket_alloc_t *list)
| We used to use an apr_bucket_pipe for forwarding the backend process's response to the HTTP client.
bool | fileExists (const StaticString &filename, CachedFileStat *cstat=0, unsigned int throttleRate=0)
| Check whether the specified file exists.
FileType | getFileType (const StaticString &filename, CachedFileStat *cstat=0, unsigned int throttleRate=0)
| Check whether 'filename' exists and what kind of file it is.
void | createFile (const string &filename, const StaticString &contents, mode_t permissions=S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH, uid_t owner=USER_NOT_GIVEN, gid_t group=GROUP_NOT_GIVEN, bool overwrite=true)
| Create the given file with the given contents, permissions and ownership.
string | canonicalizePath (const string &path)
| Returns a canonical version of the specified path.
string | resolveSymlink (const string &path)
| If path refers to a symlink, then this function resolves the symlink for 1 level.
string | extractDirName (const StaticString &path)
| Given a path, extracts its directory name.
string | extractBaseName (const StaticString &path)
| Given a path, extracts its base name.
string | escapeForXml (const string &input)
| Escape the given raw string into an XML value.
string | getProcessUsername ()
| Returns the username of the user that the current process is running as.
mode_t | parseModeString (const StaticString &mode)
| Converts a mode string into a mode_t value.
const char * | getSystemTempDir ()
| Return the path name for the directory in which the system stores general temporary files.
void | makeDirTree (const string &path, const StaticString &mode="u=rwx,g=,o=", uid_t owner=USER_NOT_GIVEN, gid_t group=GROUP_NOT_GIVEN)
| Create the directory at the given path, creating intermediate directories if necessary.
void | removeDirTree (const string &path)
| Remove an entire directory tree recursively.
bool | verifyRailsDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
| Check whether the specified directory is a valid Ruby on Rails application root directory.
bool | verifyRackDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
| Check whether the specified directory is a valid Rack application root directory.
bool | verifyWSGIDir (const string &dir, CachedFileStat *cstat=0, unsigned int throttleRate=0)
| Check whether the specified directory is a valid WSGI application root directory.
void | runAndPrintExceptions (const function< void()> &func, bool toAbort)
| Runs the given function and catches any tracable_exceptions.
string | getHostName ()
| Returns the system's host name.
string | getSignalName (int sig)
| Convert a signal number to its associated name.
void | resetSignalHandlersAndMask ()
| Resets the current process's signal handler disposition and signal mask to default values.
void | closeAllFileDescriptors (int lastToKeepOpen)
| Close all file descriptors that are higher than lastToKeepOpen.
template<typename T >
shared_ptr< T > | ptr (T *pointer)
| Convenience shortcut for creating a `shared_ptr`.

## Detailed Description

Common code for all agents.

A random.

This file provides a bunch of classes for reading and writing messages in the MessageChannel format.

Unlike MessageChannel, whose operations take control over the I/O handle and may block, these classes act like parsers and data generators. To read messages one must feed data to them. To write messages one must instruct the classes to generate a bunch of data. These classes will never block, making them ideal for use in evented servers.

## Reading messages

To read a single message, one must instantiate a message object and feed network data to it with the feed() method. This method returns the number of bytes actually processed by the message object (i.e. the number of bytes that it has recognized as part of the message).

When the message object has either successfully parsed the data or encountered an error, it will indicate so via the done() method. With hasError() one can check whether an error was encountered or whether the reader succeeded, and with errorCode() one can obtain the exact error reason. Not all message objects support hasError() and errorCode() because some of them can never encounter errors and some of them can only fail for a single reason.

When successful, the parsed message can be obtained with value(). This method may only be called when done() is true and there is no error, otherwise the return value is undefined.

At this point, the message object cannot process any more data and feed() will always return 0. To reuse the object for processing another message, one must reset its state by calling reset().

The following example demonstrates how to read a continuous stream of 32-bit integers:

       Uint32Message intMessage;
       while (true) {
           // Read a bunch of network data...
           char buf[1024];
           ssize_t size = recv(fd, buf, sizeof(buf));
           size_t consumed = 0;

           // ...and process it all. We only feed data to the message object
           // that hasn't already been fed.
           while (consumed < size) {
               consumed += intReader.feed(buf + consumed, size - consumed);
               if (intMessage.done()) {
                   printf("Integer: %d\n", (int) intMessage.value());
                   // The state must be reset before the reader can be reused.
                   intMessage.reset();
               }
           }
       }

Some message objects return non-primitive values in their value() methods, such as ArrayMessage and ScalarMessage which return `const vector<StaticString> &` and `StaticString`, respectively. These values are only valid until either of the following things occur:

- The buffer containing last the fed data has been destroyed or modified.
- The message object itself has been destroyed.

This is because the message objects try to apply copy-zero optimizations whenever possible. For example, in case of ScalarMessage, it'll check whether the data that has been fed in the first feed() call already contains a full scalar message. If so then it'll just return a StaticString that points to the scalar message in the fed data; it will not copy the fed data. In this case it is important that the buffer containing the fed data is not modified or destroyed while the StaticString is in use. If the first feed() call does not supply a full scalar message then it will buffer all fed data until the buffer contains a full scalar message, and the result will point to this buffer. Because the buffer is owned by the message object, the result will be invalidated as soon as the message object is destroyed.

## Typedef Documentation

typedef shared_ptr<AbstractSpawnManager> Passenger::AbstractSpawnManagerPtr

Convenient alias for AbstractSpawnManager smart pointer.

typedef shared_ptr<Process> Passenger::ProcessPtr

Convenient alias for Process smart pointer.

typedef shared_ptr<SpawnManager> Passenger::SpawnManagerPtr

Convenient alias for SpawnManager smart pointer.

## Enumeration Type Documentation

enum Passenger::FileType

Enumeration which indicates what kind of file a file is.

Enumerator:

  FT_NONEXISTANT | The file doesn't exist.
  FT_REGULAR | A regular file or a symlink to a regular file.
  FT_DIRECTORY | A directory.
  FT_OTHER | Something else, e.g. a pipe or a socket.

## Function Documentation

void Passenger::closeAllFileDescriptors | ( | int | lastToKeepOpen | ) |

Close all file descriptors that are higher than lastToKeepOpen.

This function is async-signal safe. But make sure there are no other threads running that might open file descriptors!

string Passenger::getHostName | ( |  | ) |

Returns the system's host name.

Exceptions:

  | SystemException | The host name cannot be retrieved.

string Passenger::getProcessUsername | ( |  | ) |

Returns the username of the user that the current process is running as.

If the user has no associated username, then "UID xxxx" is returned, where xxxx is the current UID.

void Passenger::makeDirTree | ( | const string & | path,
|  | const StaticString & | mode = `"u=rwx,g=,o="`,
|  | uid_t | owner = `USER_NOT_GIVEN`,
|  | gid_t | group = `GROUP_NOT_GIVEN` |
| ) |  |  |

Create the directory at the given path, creating intermediate directories if necessary.

The created directories' permissions are exactly as specified by the 'mode' parameter (i.e. the umask will be ignored). You can specify this directory's owner and group through the 'owner' and 'group' parameters. A value of USER_NOT_GIVEN for 'owner' and/or GROUP_NOT_GIVEN 'group' means that the owner/group should not be changed.

If 'path' already exists, then nothing will happen.

Parameters:

  | mode | A mode string, as supported by parseModeString().

Exceptions:

  | FileSystemException | Something went wrong.
  | InvalidModeStringException | The mode string cannot be parsed.

mode_t Passenger::parseModeString | ( | const StaticString & | mode | ) |

Converts a mode string into a mode_t value.

At this time only the symbolic mode strings are supported, e.g. something like looks this: "u=rwx,g=w,o=rx". The grammar is as follows:

       mode   ::= (clause ("," clause)*)?
       clause ::= who "=" permission*
       who    ::= "u" | "g" | "o"
       permission ::= "r" | "w" | "x" | "s"

Notes:

- The mode value starts with 0. So if you specify "u=rwx", then the group and world permissions will be empty (set to 0).
- The "s" permission is only allowed for who == "u" or who == "g".
- The return value does not depend on the umask.

Exceptions:

  | InvalidModeStringException | The mode string cannot be parsed.

apr_bucket * Passenger::passenger_bucket_create | ( | SessionPtr | session,
|  | PassengerBucketStatePtr | state,
|  | apr_bucket_alloc_t * | list |
| ) |  |  |

We used to use an apr_bucket_pipe for forwarding the backend process's response to the HTTP client.

However, apr_bucket_pipe has a number of issues:

- It closes the pipe's file descriptor when it has reached end-of-stream, but not when an error has occurred. This behavior is undesirable because it can easily cause file descriptor leaks.
- It does weird non-blocking-I/O related things which can cause it to read less data than can actually be read.

PassengerBucket is like apr_bucket_pipe, but:

- It also holds a reference to a Session. When a read error has occured or when end-of-stream has been reached, the Session will be dereferenced, so that the underlying file descriptor is closed.
- It ignores the APR_NONBLOCK_READ flag because that's known to cause strange I/O problems.
- It can store its current state in a PassengerBucketState data structure.

void Passenger::removeDirTree | ( | const string & | path | ) |

Remove an entire directory tree recursively.

If the directory doesn't exist then this function does nothing.

Exceptions:

  | FileSystemException | Something went wrong.

void Passenger::resetSignalHandlersAndMask | ( |  | ) |

Resets the current process's signal handler disposition and signal mask to default values.

One should call this every time one forks a child process; non-default signal masks/handler dispositions can cause all kinds of weird quirks, like waitpid() malfunctioning on OS X.

This function is async-signal safe.

void Passenger::runAndPrintExceptions | ( | const function< void()> & | func,
|  | bool | toAbort |
| ) |  |  |

Runs the given function and catches any tracable_exceptions.

Upon catching such an exception, its message and backtrace will be printed. If toAbort is true then it will call abort(), otherwise the exception is swallowed. thread_interrupted and all other exceptions are silently propagated.