Dmitry Shin лет назад: 11
Родитель
Сommit
42c4706453

BIN
bin/pwhoisd.phar


+ 181 - 0
share/example_pwhoisd.sql

@@ -0,0 +1,181 @@
+-- phpMyAdmin SQL Dump
+-- version 4.2.4
+-- http://www.phpmyadmin.net
+--
+-- Хост: localhost:3306
+-- Время создания: Апр 20 2015 г., 05:04
+-- Версия сервера: 5.6.19
+-- Версия PHP: 5.4.29
+
+SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
+SET time_zone = "+00:00";
+
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8 */;
+
+--
+-- База данных: `pwhoisd`
+--
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `contact_pir`
+--
+
+CREATE TABLE IF NOT EXISTS `contact_pir` (
+  `ID` varchar(64) NOT NULL,
+  `Name` varchar(2048) NOT NULL,
+  `Organization` varchar(2048) NOT NULL,
+  `Street` text NOT NULL,
+  `City` varchar(2048) NOT NULL,
+  `StateProvince` varchar(2048) NOT NULL,
+  `PostalCode` varchar(256) NOT NULL,
+  `Country` varchar(256) NOT NULL,
+  `Phone` varchar(256) NOT NULL,
+  `PhoneExt` varchar(256) NOT NULL,
+  `Fax` varchar(256) NOT NULL,
+  `FaxExt` varchar(256) NOT NULL,
+  `Email` varchar(256) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `contact_pir`
+--
+
+INSERT INTO `contact_pir` (`ID`, `Name`, `Organization`, `Street`, `City`, `StateProvince`, `PostalCode`, `Country`, `Phone`, `PhoneExt`, `Fax`, `FaxExt`, `Email`) VALUES
+('DI_10634473', 'Domain Coordination Centre', 'OOO Informacionnye Seti', '1a Pugacheva St.\r\nNOTE: For spam or abuse issues\r\nNOTE: send requests to abuse@hsdn.org', 'Saratov', 'Saratovskaya oblast', '410004', 'RU', '+7.8452220456', '', '', '', 'domains@hsdn.org'),
+('GODA-02131674', 'Registration Private', 'Domains By Proxy, LLC', ' DomainsByProxy.com\r\n 14747 N Northsight Blvd Suite 111, PMB 309', 'Scottsdale', 'Arizona', '85260', 'US', '+1.4806242599', '', ' +1.4806242598', '', 'PIR.ORG@domainsbyproxy.com');
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `domain_pir`
+--
+
+CREATE TABLE IF NOT EXISTS `domain_pir` (
+  `DomainName` varchar(256) NOT NULL,
+  `DomainID` varchar(64) NOT NULL,
+  `CreationDate` timestamp NULL DEFAULT NULL,
+  `UpdatedDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `RegistryExpiryDate` timestamp NULL DEFAULT NULL,
+  `TrademarkName` varchar(256) DEFAULT NULL,
+  `TrademarkDate` varchar(256) DEFAULT NULL,
+  `TrademarkCountry` varchar(256) DEFAULT NULL,
+  `TrademarkNumber` varchar(256) DEFAULT NULL,
+  `SponsoringRegistrar` varchar(256) NOT NULL,
+  `SponsoringRegistrarIANAID` varchar(256) NOT NULL,
+  `WHOISServer` varchar(256) NOT NULL,
+  `ReferralURL` varchar(256) NOT NULL,
+  `DomainStatus` text NOT NULL,
+  `RegistrantID` varchar(256) DEFAULT NULL,
+  `AdminID` varchar(256) DEFAULT NULL,
+  `TechID` varchar(256) DEFAULT NULL,
+  `BillingID` varchar(256) DEFAULT NULL,
+  `NameServer1` varchar(256) NOT NULL,
+  `NameServer2` varchar(256) NOT NULL,
+  `NameServer3` varchar(256) NOT NULL,
+  `NameServer4` varchar(256) NOT NULL,
+  `NameServer5` varchar(256) NOT NULL,
+  `NameServer6` varchar(256) NOT NULL,
+  `NameServer7` varchar(256) NOT NULL,
+  `NameServer8` varchar(256) NOT NULL,
+  `NameServer9` varchar(256) NOT NULL,
+  `NameServer10` varchar(256) NOT NULL,
+  `NameServer11` varchar(256) NOT NULL,
+  `NameServer12` varchar(256) NOT NULL,
+  `NameServer13` varchar(256) NOT NULL,
+  `DNSSEC` varchar(256) NOT NULL DEFAULT 'Unsigned',
+  `DSCreated1` timestamp NULL DEFAULT NULL,
+  `DSKeyTag1` varchar(256) DEFAULT NULL,
+  `Algorithm1` varchar(256) DEFAULT NULL,
+  `DigestType1` varchar(256) DEFAULT NULL,
+  `Digest1` varchar(256) DEFAULT NULL,
+  `DSMaximumSignatureLife1` varchar(256) DEFAULT NULL,
+  `DSCreated2` timestamp NULL DEFAULT NULL,
+  `DSKeyTag2` varchar(256) DEFAULT NULL,
+  `Algorithm2` varchar(256) DEFAULT NULL,
+  `DigestType2` varchar(256) DEFAULT NULL,
+  `Digest2` varchar(256) DEFAULT NULL,
+  `DSMaximumSignatureLife2` varchar(256) DEFAULT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+--
+-- Дамп данных таблицы `domain_pir`
+--
+
+INSERT INTO `domain_pir` (`DomainName`, `DomainID`, `CreationDate`, `UpdatedDate`, `RegistryExpiryDate`, `TrademarkName`, `TrademarkDate`, `TrademarkCountry`, `TrademarkNumber`, `SponsoringRegistrar`, `SponsoringRegistrarIANAID`, `WHOISServer`, `ReferralURL`, `DomainStatus`, `RegistrantID`, `AdminID`, `TechID`, `BillingID`, `NameServer1`, `NameServer2`, `NameServer3`, `NameServer4`, `NameServer5`, `NameServer6`, `NameServer7`, `NameServer8`, `NameServer9`, `NameServer10`, `NameServer11`, `NameServer12`, `NameServer13`, `DNSSEC`, `DSCreated1`, `DSKeyTag1`, `Algorithm1`, `DigestType1`, `Digest1`, `DSMaximumSignatureLife1`, `DSCreated2`, `DSKeyTag2`, `Algorithm2`, `DigestType2`, `Digest2`, `DSMaximumSignatureLife2`) VALUES
+('HSDN.ORG', 'D119032872-LROR', '2006-03-23 10:21:15', '2015-03-11 20:07:03', '2016-03-23 10:21:15', NULL, NULL, NULL, NULL, 'PDR Ltd. d/b/a PublicDomainRegistry.com (R27-LROR)', '303', '', '', 'ok -- http://www.icann.org/epp#ok', 'DI_10634473', 'DI_10634473', 'DI_10634473', NULL, 'NS1.HSDN.ORG', 'NS2.HSDN.ORG', 'NS3.HSDN.ORG', 'NS4.HSDN.ORG', '', '', '', '', '', '', '', '', '', 'Unsigned', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
+('PIR.ORG', 'D96207-LROR', '1996-02-18 02:00:00', '2015-02-19 22:41:55', '2016-02-19 02:00:00', NULL, NULL, NULL, NULL, 'GoDaddy.com, LLC (R91-LROR)', '146', '', '', 'serverDeleteProhibited -- http://www.icann.org/epp#serverDeleteProhibited\r\nserverTransferProhibited -- http://www.icann.org/epp#serverTransferProhibited\r\nserverUpdateProhibited -- http://www.icann.org/epp#serverUpdateProhibited', 'GODA-02131674', 'GODA-02131674', 'GODA-02131674', NULL, 'NS1.AMS1.AFILIAS-NST.INFO', 'NS1.MIA1.AFILIAS-NST.INFO', 'NS1.SEA1.AFILIAS-NST.INFO', 'NS1.YYZ1.AFILIAS-NST.INFO', '', '', '', '', '', '', '', '', '', 'signedDelegation', '2010-03-26 13:52:50', '54135', '5', '1', '225F055ACB65C8B60AD18B3640062E8C23A5FD89', '1814400 seconds', NULL, NULL, NULL, NULL, NULL, NULL);
+
+-- --------------------------------------------------------
+
+--
+-- Структура таблицы `domain_ripn`
+--
+
+CREATE TABLE IF NOT EXISTS `domain_ripn` (
+`id` int(11) NOT NULL,
+  `domain` varchar(256) NOT NULL,
+  `nserver1` varchar(256) NOT NULL,
+  `nserver2` varchar(256) NOT NULL,
+  `nserver3` varchar(256) NOT NULL,
+  `nserver4` varchar(256) NOT NULL,
+  `state` varchar(256) NOT NULL,
+  `person` varchar(256) NOT NULL DEFAULT 'Private person',
+  `org` varchar(256) NOT NULL,
+  `registrar` varchar(256) NOT NULL,
+  `admin_contact` varchar(256) NOT NULL,
+  `descr` text NOT NULL,
+  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
+  `paid_till` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `free_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
+  `source` varchar(256) NOT NULL,
+  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
+) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
+
+--
+-- Дамп данных таблицы `domain_ripn`
+--
+
+INSERT INTO `domain_ripn` (`id`, `domain`, `nserver1`, `nserver2`, `nserver3`, `nserver4`, `state`, `person`, `org`, `registrar`, `admin_contact`, `descr`, `created`, `paid_till`, `free_date`, `source`, `updated`) VALUES
+(1, 'YA.RU', 'ns1.yandex.ru.', 'ns2.yandex.ru.', '', '', 'REGISTERED, DELEGATED, VERIFIED', '', 'YANDEX, LLC.', 'RU-CENTER-RU', 'https://www.nic.ru/whois', '', '1999-07-11 20:00:00', '2015-04-15 04:36:24', '2015-04-15 04:36:24', 'RIPN', '2015-04-20 02:00:50'),
+(2, 'HSDN.RU', 'ns1.hsdn.org.', 'ns2.hsdn.org.', 'ns3.hsdn.org.', 'ns4.hsdn.org.', 'REGISTERED, DELEGATED, VERIFIED', '', 'OOO "Informacionnye Seti"', 'NAUNET-RU', 'domains@hsdn.org', 'NOTE: For spam or abuse issues\r\nNOTE: send requests to abuse@hsdn.org', '2009-02-04 21:00:00', '2016-02-04 21:00:00', '2016-03-06 21:00:00', 'TCI', '2015-04-20 02:01:51');
+
+--
+-- Indexes for dumped tables
+--
+
+--
+-- Indexes for table `contact_pir`
+--
+ALTER TABLE `contact_pir`
+ ADD PRIMARY KEY (`ID`);
+
+--
+-- Indexes for table `domain_pir`
+--
+ALTER TABLE `domain_pir`
+ ADD PRIMARY KEY (`DomainID`), ADD KEY `DomainName` (`DomainName`(255));
+
+--
+-- Indexes for table `domain_ripn`
+--
+ALTER TABLE `domain_ripn`
+ ADD PRIMARY KEY (`id`), ADD KEY `updated` (`updated`);
+
+--
+-- AUTO_INCREMENT for dumped tables
+--
+
+--
+-- AUTO_INCREMENT for table `domain_ripn`
+--
+ALTER TABLE `domain_ripn`
+MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3;
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

+ 71 - 0
share/make_phar.php

@@ -0,0 +1,71 @@
+<?php
+chdir(realpath(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'));
+
+$phar = new Phar('bin/pwhoisd.phar', 0, 'pwhoisd.phar' );
+$phar->setSignatureAlgorithm(Phar::SHA1);
+$phar->startBuffering();
+
+$rd = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
+
+$files = [];
+
+foreach($rd as $file)
+{
+	if ($file->getFilename() != '..' AND 
+		$file->getFilename() != '.' AND 
+		$file->getFilename() != __FILE__)
+	{
+		if (preg_match('|^\.\/src/include|', $file->getPath()))
+		{
+			$files[substr($file->getPath().DIRECTORY_SEPARATOR.$file->getFilename(), 2)] = 
+				$file->getPath().DIRECTORY_SEPARATOR.$file->getFilename();
+		}
+	}
+}
+
+$phar->buildFromIterator(new ArrayIterator($files));
+
+print_r($files);
+
+$phar->setStub( <<<EOB
+#!/usr/bin/env php
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2015 Information Networks Ltd.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+Phar::mapPhar();
+(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') and die('This program cannot be run in Windows environment.');
+(PHP_SAPI === 'cli') or die('This program running available in CLI mode only.');
+define('INCLUDE_PATH', 'phar://pwhoisd.phar/src/include');
+require_once INCLUDE_PATH.DIRECTORY_SEPARATOR.'Autoloader.php';
+\pWhoisd\Autoloader::register();
+\pWhoisd\Application::factory()->run();
+__HALT_COMPILER();
+?>
+EOB
+);
+
+$phar->stopBuffering();
+$phar->compressFiles(Phar::GZ);

+ 495 - 0
src/config.php

@@ -0,0 +1,495 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+// This line can not be deleted!
+namespace pWhoisd;
+
+return [
+	// Daemon configuration
+	'daemon' =>
+	[
+		// Server listen IP address
+		'listen_address' => '0.0.0.0',
+
+		// Server listen IPv6 address
+		'listen_address_ipv6' => '',
+
+		// Server listen port
+		'listen_port'    => 43,
+
+		// Max server worker processes
+		'workers'        => 300,
+	],
+
+	// Logging configuration
+	'logging' =>
+	[
+		// Log severity (Log::debug, Log::info, Log::warning, Log::error)
+		'severity' => Log::debug,
+
+		// Log file path (e.g. ./pwhoisd.log)
+		'file'     => FALSE,
+	],
+
+	// Security configuration
+	'security' =>
+	[
+		// List of access rules
+		// Warning! By default all connections are allowed and no limits do not apply.
+		//
+		// Access rule format:
+		// ['ACTION'(, 'MESSAGE')(, ['VARIABLE', 'OPERATOR', 'VALUE/UNIT'])(, ['VARIABLE', 'OPERATOR', 'VALUE/UNIT'])(, ...)]
+		//
+		// ACTION:
+		//   allow       Permit a client connections and requests
+		//   deny        Print specified message to a client (optional) and drop the connection
+		//   drop        Silently drop a client connection. No messages is sent
+		//
+		// VARIABLE:
+		//   client_ip   Client connection IP address (used for IP/subnets checks)
+		//   requests    Used to specify a requests rate limit to the specific client connections
+		//   rate        Used to specify the global server requests rate limit for all clients connections
+		//
+		// MESSAGE:
+		//   Here specify the name of the section in the messages array configuration.
+		//
+		// OPERATOR:
+		// Any one of the allowed operators. Not to be used in IP rules. The allowed operators are:
+		//   <           Less than
+		//   ==          Equal to
+		//   <=          Less than or equal to
+		//   >           Greater than
+		//   >=          Greater than or equal to
+		//
+		// VALUE:
+		// For requests rate rules specifies a numeric value with UNIT (see below).
+		// It can also be a single IP address (subnet, in CIDR format) or an array of IP addresses (subnets).
+		//
+		// UNIT:
+		// Any one of the allowed units. Not to be used in IP rules. The allowed units are:
+		//   sec         Second(s)
+		//   hr          Hour(s)
+		//   min         Minute(s)
+		//   day         Day(s)
+		//
+		'rules' =>
+		[
+			// Drop all connections if server rate more 20 requests per one seconds
+			// This rule will work with the previous rules (sets a global server rate limits).
+			['drop', ['rate', '>', '20/sec']],
+
+			// Allow all connections from IP 127.0.0.1.
+			// It is owerride previous (bottom) 'deny' rule for this IP (limits do not works)
+			['allow', ['client_ip', '127.0.0.1'] ],
+
+			// Deny any client if rate more 50 requests per one minute.
+			['deny', 'limit_exceeded', ['requests', '>', '50/min']],
+
+			// Permit all connections (it is first rule).
+			['allow'],
+		],
+	],
+
+	// Messages configuration (use empty quotes to set <CR><LF>)
+	//
+	// This variables is available to use in all messages:
+	//   {_request_}      Current request string
+	//   {_client_ip_}    Current client IP address
+	//   {_client_port_}  Current client port number
+	//   {%...%}          Includes other message context (for example: {%header%})
+	//   {...}            Includes any data-field value
+	//
+	'messages' =>
+	[
+		//
+		// Global messages
+		//
+
+		// Limit exceeded response message
+		'limit_exceeded' => 
+		[
+			'Whois limit exceeded.',
+		],
+
+		// Access denied response message
+		'access_denied' => 
+		[
+			'Access denied.',
+		],
+
+		//
+		// RIPN's style messages
+		//
+
+		// Whois response header fragment
+		'header_ripn'  => 
+		[
+			'% By submitting a query to RIPN\'s Whois Service',
+			'% you agree to abide by the following terms of use:',
+			'% http://www.ripn.net/about/servpol.html#3.2 (in Russian)',
+			'% http://www.ripn.net/about/en/servpol.html#3.2 (in English).',
+			'', // <CR><LF>
+		],
+
+		// Whois response footer fragment
+		'footer_ripn'  => 
+		[
+			'', // <CR><LF>
+			'Last updated on {updated_new}',
+		],
+
+
+		//
+		// PIR's style messages
+		//
+
+		// Whois response footer fragment
+		'footer_pir'  => 
+		[
+			'', // <CR><LF>
+			'Access to Public Interest Registry WHOIS information is provided to assist persons in determining the contents of a domain name registration record in the Public Interest Registry registry database. The data in this record is provided by Public Interest Registry for informational purposes only, and Public Interest Registry does not guarantee its accuracy. This service is intended only for query-based access. You agree that you will use this data only for lawful purposes and that, under no circumstances will you use this data to(a) allow, enable, or otherwise support the transmission by e-mail, telephone, or facsimile of mass unsolicited, commercial advertising or solicitations to entities other than the data recipient\'s own existing customers; or (b) enable high volume, automated, electronic processes that send queries or data to the systems of Registry Operator, a Registrar, or Afilias except as reasonably necessary to register domain names or modify existing registrations. All rights reserved. Public Interest Registry reserves the right to modify these terms at any time. By submitting this query, you agree to abide by this policy. For more information on Whois status codes, please visit https://www.icann.org/resources/pages/epp-status-codes-2014-06-16-en.',
+		],
+	],
+
+	// Data configuration (first entry is default)
+	'data' =>
+	[
+		// Domain (RIPN's style)
+		[
+			// Request flag or key
+			'flag'    => '-R domain',
+
+			// Storage configuration
+			'storage' =>
+			[
+				// Storage type (mysql)
+				'type'    => 'mysql',
+
+				// MySQL storage configuration
+				'db_host' => 'localhost',
+				'db_port' => 3306,
+				'db_user' => 'pwhoisd',
+				'db_pass' => 'J35tn4fFhEB7YJ6B',
+				'db_name' => 'pwhoisd',
+
+				// Database SQL queries (uses first row of query result)
+				//
+				// This variables is available to use in queries (use variable {_request_} to specify request string):
+				//   {_request_}      Current request string
+				//   {_client_ip_}    Current client IP address
+				//   {_client_port_}  Current client port number
+				//   {...}            Includes any data-field value from previous query results (uses first rows)
+				// Warning! Value of all variabled are automate escaped.
+				//
+				'queries' =>
+				[
+					// Fetch last database update timestamp
+					'SELECT MAX(`updated`) AS `updated` FROM `domain_ripn`',
+
+					// Search and fetch row by request
+					'SELECT * FROM `domain_ripn` WHERE `domain` LIKE \'{_request_}\' LIMIT 1',
+				],
+			],
+
+			// Formatting data in fields (overrides or creates fields)
+			// The variables is specified in the following format: {VARIABLE}.
+			// Warning! Value of all variables are automate quoted (uses double quotes).
+			'format'  =>
+			[
+				// Create new field 'updated_new' based on date-formatted field 'updated'
+				['updated_new', 'date("Y.m.d H:i:s \M\S\K", strtotime({updated}))'],
+
+				// Format date fields
+				['created', 'date("Y.m.d", strtotime({created}))'],
+				['paid_till', 'date("Y.m.d", strtotime({paid_till}))'],
+				['free_date', 'date("Y.m.d", strtotime({free_date}))'],
+
+				// Example: hide 'admin_contact' field if not exists flag '-L' in request
+				['admin_contact_new', '{admin_contact}'],
+				['admin_contact', NULL],
+				['admin_contact', '{admin_contact_new}', '-L'],
+
+				// Make a domain field uppercase
+				['domain', 'strtoupper({domain})'],
+			],
+
+			// Enable fields message space padding (uses only for ['MESSAGE', 'FIELD'] entries)
+			//
+			// Example #1 (no padding):
+			//   ...
+			//   domain:HSDN.RU
+			//   nserver:ns1.hsdn.org.
+			//   org:OOO "Informacionnye Seti"
+			//   ...
+			//
+			// Example #2 (with padding):
+			//   ...
+			//   domain:  HSDN.RU
+			//   nserver: ns1.hsdn.org.
+			//   org:     OOO "Informacionnye Seti"
+			//   ...
+			//
+			'spacing' => TRUE,
+
+			// Enables empty (not NULL) fields hidding
+			// Note: Fields contains NULL values are hidden anyway.
+			'hide_empty' => TRUE,
+
+			// Response data fields entries (use empty entry array to set <CR><LF>)
+			//
+			// Entries format:
+			// [('MESSAGE')(, 'FIELD')(, 'FLAG')]
+			//
+			// MESSAGE:
+			//   The message for the data-field or any other text. Any variables allowed (see. above).
+			//   Note: Can insert padding before the data values, use the option 'spacing'.
+			//
+			// FIELD:
+			//   The name of existing the data-field name or new formatted field (see. above).
+			//
+			// FLAG:
+			//   NULL    Entry is shown if the data-field exists and is not empty.
+			//           The value of the data-field is inserted after the text (by default).
+			//
+			//   TRUE    Entry shown only if there is a field exists and data not empty.
+			//           The value of the field data is not inserted.
+			//
+			//   FALSE   Entry shown only if there is no a field or data is empty.
+			//           The value of the field data is not inserted.
+			'fields'  =>
+			[
+				// Header message anchor
+				['{%header_ripn%}'],
+
+				// This text shown only an empty data-field 'domain'
+				['No entries found for the selected source(s).', 'domain', FALSE],
+
+				// Fields below are only shown if exists and data not empty
+				['domain', 'domain'],
+				['nserver', 'nserver1'],
+				['nserver', 'nserver2'],
+				['nserver', 'nserver3'],
+				['nserver', 'nserver4'],
+				['state', 'state'],
+				['person', 'person'],
+				['org', 'org'],
+				['registrar', 'registrar'],
+				['admin-contact', 'admin_contact'],
+				['descr', 'descr'],
+				['created', 'created'],
+				['paid-till', 'paid_till'],
+				['free-date', 'free_date'],
+				['source', 'source'],
+
+				// Footer message anchor (always shown, even if the result is empty)
+				['{%footer_ripn%}'],
+			],
+
+			// Invalid request message
+			'invalid_request'=> 
+			[
+				'{%header_ripn%}',
+				'Invalid request.',
+			],
+		],
+
+		// Domain (PIR's style)
+		[
+			'flag'    => 'pir',
+
+			'storage' =>
+			[
+				'type'    => 'mysql',
+
+				'db_host' => 'localhost',
+				'db_port' => 3306,
+				'db_user' => 'pwhoisd',
+				'db_pass' => 'J35tn4fFhEB7YJ6B',
+				'db_name' => 'pwhoisd',
+
+				'queries' =>
+				[
+					// Fetch domain information
+					'SELECT * FROM `domain_pir` WHERE `DomainName` LIKE \'{_request_}\' LIMIT 1',
+
+					// Fetch registrant contact
+					'SELECT 
+						`ID` AS `RegistrantID`,
+						`Name` AS `RegistrantName`,
+						`Organization` AS `RegistrantOrganization`,
+						`Street` AS `RegistrantStreet`,
+						`City` AS `RegistrantCity`,
+						`StateProvince` AS `RegistrantStateProvince`,
+						`PostalCode` AS `RegistrantPostalCode`,
+						`Country` AS `RegistrantCountry`,
+						`Phone` AS `RegistrantPhone`,
+						`PhoneExt` AS `RegistrantPhoneExt`,
+						`Fax` AS `RegistrantFax`,
+						`FaxExt` AS `RegistrantFaxExt`,
+						`Email` AS `RegistrantEmail`
+					FROM `contact_pir` WHERE `ID` = \'{RegistrantID}\' LIMIT 1',
+
+					// Fetch admin contact
+					'SELECT 
+						`ID` AS `AdminID`,
+						`Name` AS `AdminName`,
+						`Organization` AS `AdminOrganization`,
+						`Street` AS `AdminStreet`,
+						`City` AS `AdminCity`,
+						`StateProvince` AS `AdminStateProvince`,
+						`PostalCode` AS `AdminPostalCode`,
+						`Country` AS `AdminCountry`,
+						`Phone` AS `AdminPhone`,
+						`PhoneExt` AS `AdminPhoneExt`,
+						`Fax` AS `AdminFax`,
+						`FaxExt` AS `AdminFaxExt`,
+						`Email` AS `AdminEmail`
+					FROM `contact_pir` WHERE `ID` = \'{AdminID}\' LIMIT 1',
+
+					// Fetch tech contact
+					'SELECT 
+						`ID` AS `TechID`,
+						`Name` AS `TechName`,
+						`Organization` AS `TechOrganization`,
+						`Street` AS `TechStreet`,
+						`City` AS `TechCity`,
+						`StateProvince` AS `TechStateProvince`,
+						`PostalCode` AS `TechPostalCode`,
+						`Country` AS `TechCountry`,
+						`Phone` AS `TechPhone`,
+						`PhoneExt` AS `TechPhoneExt`,
+						`Fax` AS `TechFax`,
+						`FaxExt` AS `TechFaxExt`,
+						`Email` AS `TechEmail`
+					FROM `contact_pir` WHERE `ID` = \'{TechID}\' LIMIT 1',
+				],
+			],
+
+			'format' =>
+			[
+				['CreationDate', 'date("Y-m-d\TH:i:s\Z", strtotime({CreationDate}))'],
+				['UpdatedDate', 'date("Y-m-d\TH:i:s\Z", strtotime({UpdatedDate}))'],
+				['RegistryExpiryDate', 'date("Y-m-d\TH:i:s\Z", strtotime({RegistryExpiryDate}))'],
+				['DSCreated1', 'date("Y-m-d\TH:i:s\Z", strtotime({DSCreated1}))'],
+				['DSCreated2', 'date("Y-m-d\TH:i:s\Z", strtotime({DSCreated2}))'],
+			],
+
+			'spacing'    => FALSE,
+			'hide_empty' => FALSE,
+
+			'fields' =>
+			[
+				['Domain Name', 'DomainName'],
+				['Domain ID', 'DomainID'],
+				['Creation Date', 'CreationDate'],
+				['Updated Date', 'UpdatedDate'],
+				['Registry Expiry Date', 'RegistryExpiryDate'],
+				['Trademark Name', 'TrademarkName'],
+				['Trademark Date', 'TrademarkDate'],
+				['Trademark Country', 'TrademarkCountry'],
+				['Trademark Number', 'TrademarkNumber'],
+				['Sponsoring Registrar', 'SponsoringRegistrar'],
+				['Sponsoring Registrar IANA ID', 'SponsoringRegistrarIANAID'],
+				['WHOIS Server', 'WHOISServer'],
+				['Referral URL', 'ReferralURL'],
+				['Domain Status', 'DomainStatus'],
+				['Registrant ID', 'RegistrantID'],
+				['Registrant Name', 'RegistrantName'],
+				['Registrant Organization', 'RegistrantOrganization'],
+				['Registrant Street', 'RegistrantStreet'],
+				['Registrant City', 'RegistrantCity'],
+				['Registrant State/Province', 'RegistrantStateProvince'],
+				['Registrant Postal Code', 'RegistrantPostalCode'],
+				['Registrant Country', 'RegistrantCountry'],
+				['Registrant Phone', 'RegistrantPhone'],
+				['Registrant Phone Ext', 'RegistrantPhoneExt'],
+				['Registrant Fax', 'RegistrantFax'],
+				['Registrant Fax Ext', 'RegistrantFaxExt'],
+				['Registrant Email', 'RegistrantEmail'],
+				['Admin ID', 'AdminID'],
+				['Admin Name', 'AdminName'],
+				['Admin Organization', 'AdminOrganization'],
+				['Admin Street', 'AdminStreet'],
+				['Admin City', 'AdminCity'],
+				['Admin State/Province', 'AdminStateProvince'],
+				['Admin Postal Code', 'AdminPostalCode'],
+				['Admin Country', 'AdminCountry'],
+				['Admin Phone', 'AdminPhone'],
+				['Admin Phone Ext', 'AdminPhoneExt'],
+				['Admin Fax', 'AdminFax'],
+				['Admin Fax Ext', 'AdminFaxExt'],
+				['Admin Email', 'AdminEmail'],
+				['Tech ID', 'TechID'],
+				['Tech Name', 'TechName'],
+				['Tech Organization', 'TechOrganization'],
+				['Tech Street', 'TechStreet'],
+				['Tech City', 'TechCity'],
+				['Tech State/Province', 'TechStateProvince'],
+				['Tech Postal Code', 'TechPostalCode'],
+				['Tech Country', 'TechCountry'],
+				['Tech Phone', 'TechPhone'],
+				['Tech Phone Ext', 'TechPhoneExt'],
+				['Tech Fax', 'TechFax'],
+				['Tech Fax Ext', 'TechFaxExt'],
+				['Tech Email', 'TechEmail'],
+				['Name Server', 'NameServer1'],
+				['Name Server', 'NameServer2'],
+				['Name Server', 'NameServer3'],
+				['Name Server', 'NameServer4'],
+				['Name Server', 'NameServer5'],
+				['Name Server', 'NameServer6'],
+				['Name Server', 'NameServer7'],
+				['Name Server', 'NameServer8'],
+				['Name Server', 'NameServer9'],
+				['Name Server', 'NameServer10'],
+				['Name Server', 'NameServer11'],
+				['Name Server', 'NameServer12'],
+				['Name Server', 'NameServer13'],
+				['DNSSEC', 'DNSSEC'],
+				['DS Created 1', 'DSCreated1'],
+				['DS Key Tag 1', 'DSKeyTag1'],
+				['Algorithm 1', 'Algorithm1'],
+				['Digest Type 1', 'DigestType1'],
+				['Digest 1', 'Digest1'],
+				['DS Maximum Signature Life 1', 'DSMaximumSignatureLife1'],
+				['DS Created 2', 'DSCreated2'],
+				['DS Key Tag 2', 'DSKeyTag2'],
+				['Algorithm 2', 'Algorithm2'],
+				['Digest Type 2', 'DigestType2'],
+				['Digest 2', 'Digest2'],
+				['DS Maximum Signature Life 2', 'DSMaximumSignatureLife2'],
+
+				// This text shown only an empty data-field 'DomainName'
+				['NOT FOUND', 'DomainName', FALSE],
+
+				// Footer message anchor (shown only if the data-field 'DomainName' is exists and not empty)
+				['{%footer_pir%}', 'DomainName', TRUE],
+			],
+
+			'invalid_request' => 
+			[
+				'{%header_ripn%}',
+				'Invalid request.',
+			],
+		],
+
+		// Help
+		[
+			'flag'   => 'help',
+			'fields' =>
+			[
+				['{%header_ripn%}'],
+				['This is help!'],
+			],
+		],
+	],
+
+];
+
+// end of config

+ 194 - 0
src/include/Application.php

@@ -0,0 +1,194 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Console;
+use pWhoisd\Log;
+use pWhoisd\Config;
+use pWhoisd\Server;
+use RuntimeException;
+use ErrorException;
+
+define('PWHOISD_VERSION', '0.1.1b');
+
+/**
+ * Application class.
+ */
+class Application extends Daemon {
+
+	/*
+	 * @var  object  Instance of Config class
+	 */
+	public static $config;
+
+	/*
+	 * @var  object  Instance of Log class
+	 */
+	public static $log;
+
+	/*
+	 * @var  object  Instance of Security class
+	 */
+	public static $security;
+
+	/*
+	 * @var  object  Instance of Server class
+	 */
+	public static $server;
+
+
+	/**
+	 * Returns instance of Application.
+	 *
+	 * @return Application
+	 */
+	public static function factory()
+	{
+		return new self;
+	}
+
+	/**
+	 * Loads command-line arguments, configuration and Server class.
+	 *
+	 * @return  void
+	 */
+	public function __construct()
+	{
+		$this->initialize();
+
+		self::$config   = new Config;
+		self::$log      = new Log;
+		self::$security = new Security;
+		self::$server   = new Server;
+
+		if (!self::$arguments['daemon'])
+		{
+			Console::head();
+		}
+
+		self::$log->debug('Configuration loaded');
+	}
+
+	/**
+	 * Initialize application
+	 *
+	 * @return  void
+	 */
+	private function initialize()
+	{
+		set_time_limit(0);
+
+		$this->set_exception_handlers();
+		$this->test_dependences();
+		$this->assign_arguments();
+
+		if (!self::$arguments['daemon'])
+		{
+			Console::help();
+		}
+
+		if (self::$arguments['help'])
+		{
+			exit;
+		}
+
+		$this->set_identifiers();
+		$this->set_signal_handlers();
+	}
+
+	/**
+	 * Sets exception and error handlers
+	 *
+	 * @return  void
+	 */
+	private function set_exception_handlers()
+	{
+		set_exception_handler([$this, 'exception_handler']);
+		set_error_handler([$this, 'error_handler']);
+	}
+
+	/**
+	 * Test application dependences.
+	 *
+	 * @throws  \RuntimeException  If require dependence
+	 * @return  void
+	 */
+	private function test_dependences()
+	{
+		version_compare(PHP_VERSION, '5.4', '<') and die('Requires PHP 5.4 or newer.');
+
+		if (!extension_loaded('posix'))
+		{
+			throw new RuntimeException('Requires POSIX functions support (https://php.net/manual/en/posix.installation.php)');
+		}
+
+		if (!extension_loaded('pcntl'))
+		{
+			throw new RuntimeException('Requires PCNTL extension (http://www.php.net/manual/en/pcntl.installation.php)');
+		}
+
+		if (!extension_loaded('filter'))
+		{
+			throw new RuntimeException('Requires filter extension (http://www.php.net/manual/en/filter.installation.php)');
+		}
+
+		if (!extension_loaded('gmp') AND !extension_loaded('bcmath'))
+		{
+			throw new RuntimeException('Requires GMP or BCMATH extension (http://www.php.net/manual/en/gmp.installation.php)');
+		}
+
+		if (!extension_loaded('sockets'))
+		{
+			throw new RuntimeException('Requires sockets extension (http://www.php.net/manual/en/sockets.installation.php)');
+		}
+	}
+
+	/**
+	 * Exception handler method.
+	 *
+	 * @return  void
+	 */
+	public function exception_handler(\Exception $exception)
+	{
+		$message = get_class($exception).': '.$exception->getMessage();
+		$log     = Application::$log;
+
+		if (is_object($log))
+		{
+			$log->error($message);
+		}
+		else
+		{
+			Console::log($message, 'red');
+		}
+
+		// Terminate process if exception called before server loop
+		if (is_null(Application::$server) OR Application::$server->listen_loop === FALSE)
+		{
+			Application::terminate(FALSE);
+		}
+	}
+
+	/**
+	 * Error handler method.
+	 *
+	 * @return  void
+	 */
+	public function error_handler($severity, $message, $file, $line)
+	{
+		if (!(error_reporting() & $severity))
+		{
+			return;
+		}
+
+		throw new ErrorException('PHP Error: '.$message.'; file: '.$file.'; line: '.$line);
+	}
+
+} // end of class Application

+ 59 - 0
src/include/Autoloader.php

@@ -0,0 +1,59 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+/**
+ * Autoloader class.
+ */
+class Autoloader {
+
+	/**
+	 * Register the autoload callback
+	 *
+	 * @return  void
+	 */
+	static public function register()
+	{
+		ini_set('unserialize_callback_func', 'spl_autoload_call');
+
+		spl_autoload_register(array(__CLASS__, 'autoload'));
+	}
+
+	/**
+	 * Autoload callback
+	 *
+	 * @param   string  $class  Class name to loading
+	 * @return  void
+	 */
+	static public function autoload($class)
+	{
+		$class_pos  = -strpos(strrev($class), '\\');
+		$class_name = substr($class, $class_pos);
+		$namespace  = substr($class, 0, $class_pos);
+
+		if (strpos($namespace, __NAMESPACE__) !== 0)
+		{
+			return;
+		}
+
+		$namespace  = substr($namespace, strlen(__NAMESPACE__) + 1);
+		$class_file = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $namespace.$class_name).'.php';
+		$class_path = INCLUDE_PATH.DIRECTORY_SEPARATOR.$class_file;
+
+		if(!is_readable($class_path))
+		{
+			echo 'Unable to load file: '.$class_path."\n";
+			exit;
+		}
+
+		require_once $class_path;
+	}
+
+} // end of class Autoloader

+ 120 - 0
src/include/Client.php

@@ -0,0 +1,120 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+
+/**
+ * Client class.
+ */
+class Client {
+
+	/*
+	 * @var  resource  Worker socket resource
+	 */
+	private $socket;
+
+	/*
+	 * @var  string    Current client IP address
+	 */
+	private $address;
+
+	/*
+	 * @var  int       Current client port
+	 */
+	private $port;
+
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @param   object  $socket  Worker socket resource
+	 * @return  void
+	 */
+	public function __construct($socket)
+	{
+		$this->socket = $socket;
+
+		@socket_getsockname($this->socket, $this->address, $this->port);
+
+		Application::$log->debug('Socket assigned for client '.$this->address.':'.$this->port);
+		Application::$log->info('['.$this->address.'] Connected at port '.$this->port);
+	}
+
+	/**
+	 * Writes message to socket
+	 *
+	 * @param   string  $message  Message to write
+	 * @return  void
+	 */
+	public function send($message)
+	{
+		$message = str_replace(["\r", "\n"], ['', "\r\n"], $message)."\r\n";
+
+		@socket_write($this->socket, $message, strlen($message));
+
+		Application::$log->info('['.$this->address.'] Response sended (see debug)');
+		Application::$log->debug('Message writed to client socket: '.PHP_EOL.$message);
+	}
+
+	/**
+	 * Reads data from socket
+	 *
+	 * @param   int    $len  Read data length
+	 * @return  string
+	 */
+	public function read($len = 1024)
+	{
+		if (($buffer = @socket_read($this->socket, $len, PHP_BINARY_READ)) === FALSE)
+		{
+			return NULL;
+		}
+
+		Application::$log->info('['.$this->address.'] Request Recieved: '.trim($buffer));
+		Application::$log->debug('Request readed from client socket: '.$buffer);
+
+		return $buffer;
+	}
+
+	/**
+	 * Shutdown and Closes Worker socket
+	 *
+	 * @return  void
+	 */
+	public function close()
+	{
+		@socket_shutdown($this->socket);
+		@socket_close($this->socket);
+
+		Application::$log->debug('Client socket closed');
+		Application::$log->info('['.$this->address.'] Disconnected');
+	}
+
+	/**
+	 * Gets current client IP address
+	 *
+	 * @return  string
+	 */
+	public function get_address()
+	{
+		return $this->address;
+	}
+
+	/**
+	 * Gets current client port
+	 *
+	 * @return  int
+	 */
+	public function get_port()
+	{
+		return $this->port;
+	}
+
+} // end of class Client

+ 67 - 0
src/include/Config.php

@@ -0,0 +1,67 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use pWhoisd\Config\ConfigAbstract;
+use InvalidArgumentException;
+use RuntimeException;
+
+/**
+ * Config class.
+ */
+class Config extends Config\ConfigAbstract {
+
+	/**
+	 * Returns instance of Config.
+	 *
+	 * @return Config
+	 */
+	public static function factory()
+	{
+		return new self;
+	}
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @return  void
+	 */
+	public function __construct()
+	{
+		$this->load(realpath(Application::$arguments['config']));
+	}
+
+	/**
+	 * Load a configuration file.
+	 *
+	 * @throws \InvalidArgumentException  If $file is not a valid file.
+	 * @throws \RuntimeException          If $file does not return an array.
+	 * @param  string  $file  Path to php file which returns an array.
+	 * @return self
+	 */
+	public function load($file)
+	{
+		if (empty($file) OR !file_exists($file))
+		{
+			throw new InvalidArgumentException('Configuration file must be a valid file.');
+		}
+
+		$data = include $file;
+
+		if (!is_array($data))
+		{
+			throw new RuntimeException('Configuration file did not return an array.');
+		}
+
+		return $this->set($data);
+	}
+
+} // end of class Config

+ 221 - 0
src/include/Config/ConfigAbstract.php

@@ -0,0 +1,221 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Config;
+
+use pWhoisd\Config\ConfigInterface;
+use InvalidArgumentException;
+use RuntimeException;
+
+/**
+ * Abstract Config implementing ConfigInterface.
+ */
+abstract class ConfigAbstract implements ConfigInterface {
+
+	/**
+	 * @var array Configuration data.
+	 */
+	protected $data = [];
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function set($key, $value = NULL)
+	{
+		if (is_array($key)) 
+		{
+			foreach ($key as $k => $v)
+			{
+				$this->set($k, $v);
+			}
+		}
+		elseif (is_string($key))
+		{
+			if (strpos($key, '.') !== FALSE)
+			{
+				$this->setDotNotationKey($key, $value);
+			}
+			else
+			{
+				if (is_array($value) AND $this->containsOnlyStringKeys($value)) 
+				{
+					foreach ($value as $k => $v)
+					{
+						$this->set($key.'.'.$k, $v);
+					}
+				} 
+				else 
+				{
+					$this->data[$key] = $value;
+				}
+			}
+		}
+		else
+		{
+			throw new InvalidArgumentException('Key must be a string or an associative array');
+		}
+
+		return $this;
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function has($key = NULL)
+	{
+		if (is_null($key)) {
+			return !empty($this->data);
+		}
+
+		$segs = explode('.', $key);
+		$root = $this->data;
+
+		// nested case
+		foreach ($segs as $part)
+		{
+			if (!array_key_exists($part, $root))
+			{
+				return FALSE;
+			}
+
+			$root = $root[$part];
+		}
+
+		return TRUE;
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function get($key = NULL, $default = NULL)
+	{
+		if (is_null($key))
+		{
+			return $this->data;
+		}
+
+		if (!$this->has($key))
+		{
+			if ($default === NULL)
+			{
+				throw new RuntimeException('Specified key not found in configuration');
+			}
+
+			return $default;
+		}
+
+		$segs = explode('.', $key);
+		$root = $this->data;
+
+		foreach ($segs as $part)
+		{
+			$root = $root[$part];
+		}
+
+		return $root;
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function remove($key)
+	{
+		if ($this->has($key))
+		{
+			$segs = explode('.', $key);
+			$root = &$this->data;
+
+			foreach ($segs as $part) 
+			{
+				$parent = &$root;
+				$root   = &$root[$part];
+			}
+
+			unset($parent[$part]);
+		}
+
+		return $this;
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function clear()
+	{
+		$this->data = [];
+	}
+
+	/**
+	 * Handle setting a configuration value with a dot notation key.
+	 *
+	 * @param string $key   Dot notation key.
+	 * @param mixed  $value Configuration value.
+	 */
+	protected function setDotNotationKey($key, $value)
+	{
+		$splitKey = explode('.', $key);
+		$root	 = &$this->data;
+
+		while ($part = array_shift($splitKey)) 
+		{
+			if (!isset($root[$part]) AND count($splitKey)) 
+			{
+				$root[$part] = [];
+			}
+
+			$root = &$root[$part];
+		}
+
+		$root = $value;
+	}
+
+	/**
+	 * Check if an array contains only string keys.
+	 *
+	 * @param  array $array  Array to check.
+	 * @return bool  TRUE if array only contains string keys, FALSE if not.
+	 */
+	protected function containsOnlyStringKeys(array $array)
+	{
+		return count($array) === count(array_filter(array_keys($array), 'is_string'));
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function offsetSet($offset, $value)
+	{
+		$this->set($offset, $value);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function offsetExists($offset)
+	{
+		return $this->has($offset);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function offsetGet($offset)
+	{
+		return $this->get($offset);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function offsetUnset($offset)
+	{
+		$this->remove($offset);
+	}
+
+} // end of abstract class ConfigAbstract

+ 60 - 0
src/include/Config/ConfigInterface.php

@@ -0,0 +1,60 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Config;
+
+/**
+ * Config Interface.
+ */
+interface ConfigInterface extends \ArrayAccess
+{
+	/**
+	 * Set one or more configuration values.
+	 *
+	 * @throws \InvalidArgumentException  If key must be a string or an associative array
+	 * @param  string|array $key    Config key value or array of keys and values.
+	 * @param  mixed        $value  Configuration value or null if $key is given an array.
+	 * @return self
+	 */
+	public function set($key, $value = NULL);
+
+	/**
+	 * Check if a configuration value is set.
+	 *
+	 * @param  string $key  Confifuration key to check. If null if given it will check if any value is set at all.
+	 * @return bool   True if the key exists, false if not.
+	 */
+	public function has($key = NULL);
+
+	/**
+	 * Get a configuration value.
+	 *
+	 * @throws \RuntimeException  Specified key not found in configuration
+	 * @param  string $key     Configuration key whose value to get.
+	 * @param  mixed  $default Default value if the searched key is not found.
+	 * @return mixed  Matching Configuration value or $default if the key was not found.
+	 */
+	public function get($key = NULL, $default = NULL);
+
+	/**
+	 * Remove a configuration value.
+	 *
+	 * @param  string  $key  Configuration key to remove.
+	 * @return self.
+	 */
+	public function remove($key);
+
+	/**
+	 * Clear all configuration values.
+	 *
+	 * @return void
+	 */
+	public function clear();
+
+} // end of interface ConfigInterface

+ 114 - 0
src/include/Console.php

@@ -0,0 +1,114 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+/**
+ * Console class.
+ */
+class Console {
+
+	/*
+	 * @var array  Color codes
+	 */
+	private static $color = 
+	[
+		'red'    => 31,
+		'green'  => 32,
+		'brown'  => 33,
+		'blue'   => 34,
+		'purple' => 35,
+		'cyan'   => 36,
+		'grey'   => 37,
+		'yellow' => 33
+	];
+
+	/**
+	 * Print help message.
+	 *
+	 * @return void
+	 */
+	public static function help()
+	{
+		$message =
+			'Server version: pWhoisd/'.PWHOISD_VERSION.PHP_EOL.
+			'Usage: '.$GLOBALS['argv'][0].' [--config=file] [--pidfile=file] [--uid=identifier] [--gid=identifier] [--daemon]'.PHP_EOL.
+			'Options:                                   '.PHP_EOL.
+			'  --config : main configuration file       '.PHP_EOL.
+			'  --pidfile: file to save process ID       '.PHP_EOL.
+			'  --uid    : specify an UID for process    '.PHP_EOL.
+			'  --gid    : specify an GID for process    '.PHP_EOL.
+			'  --daemon : run process in background mode'.PHP_EOL.
+			'  --help   : show this help only           ';
+
+		self::print_message($message);
+	}
+
+	/**
+	 * Print header message.
+	 *
+	 * @return void
+	 */
+	public static function head()
+	{
+		$message =
+			'    __          ___           _         _ '.PHP_EOL.
+			'    \ \        / / |         (_)       | |'.PHP_EOL.
+			'  _ _\ \  /\  / /| |__   ___  _ ___  __| |'.PHP_EOL.
+			" | '_ \ \/  \/ / | '_ \ / _ \| / __|/ _` |".PHP_EOL.
+			' | |_) \  /\  /  | | | | (_) | \__ \ (_| |'.PHP_EOL.
+			' | .__/ \/  \/   |_| |_|\___/|_|___/\__,_|'.PHP_EOL.
+			' | |                                      '.PHP_EOL.
+			' |_|   HSDN PHP Whois Server Daemon       '.PHP_EOL;
+
+		self::print_message($message);
+	}
+
+	/**
+	 * Print any message.
+	 *
+	 * @param  string  Message text
+	 * @param  string  Color name
+	 * @return void
+	 */
+	public static function log($message, $color = 'green')
+	{
+		self::print_message($message, $color);
+	}
+
+	/**
+	 * Output message to console.
+	 *
+	 * @param  string  Message text
+	 * @param  string  Color name
+	 * @return void
+	 */
+	private static function print_message($message, $color = NULL)
+	{
+		echo self::colorize($message, $color).PHP_EOL;
+	}
+
+	/**
+	 * Adds bash color codes to string.
+	 *
+	 * @param  string  Message text
+	 * @param  string  Color name
+	 * @return string
+	 */
+	private static function colorize($string, $color = NULL)
+	{
+		if (isset(self::$color[$color]))
+		{
+			return "\033[".self::$color[$color].'m'.$string."\033[0m";
+		}
+
+		return $string;
+	}
+
+} // end of class Console

+ 233 - 0
src/include/Daemon.php

@@ -0,0 +1,233 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use RuntimeException;
+use ErrorException;
+
+/**
+ * Abstract Daemon class.
+ */
+abstract class Daemon {
+
+	/*
+	 * @var  array    Command-line arguments defaults
+	 */
+	public static $arguments =
+	[
+		'uid'     => FALSE,
+		'gid'     => FALSE,
+		'pidfile' => FALSE,
+		'daemon'  => FALSE,
+		'help'    => FALSE,
+		'config'  => 'config.php',
+	];
+
+	/*
+	 * @var  int     Process identifier
+	 */
+	protected static $pid;
+
+
+	/**
+	 * Run and listen the server.
+	 *
+	 * @return  void
+	 */
+	public function run()
+	{
+		Application::$log->debug('Process run as UID/GID: '.posix_getuid().'/'.posix_getgid());
+		Application::$server->initialize();
+
+		// Transfer process in the background mode
+		$this->fork();
+		$this->write_pid();
+
+		Application::$server->loop();
+	}
+
+	/**
+	 * Set the UID/GID of the current process
+	 *
+	 * @throws  \RuntimeException  If error while changing identifiers
+	 * @return  void
+	 */
+	protected function set_identifiers()
+	{
+		if (is_string(self::$arguments['uid']))
+		{
+			if (!posix_setuid(self::$arguments['uid']))
+			{
+				throw new RuntimeException('Can\'t change UID for process');
+			}
+		}
+
+		if (is_string(self::$arguments['gid']))
+		{
+			if (!posix_setuid(self::$arguments['gid']))
+			{
+				throw new RuntimeException('Can\'t change GID for process');
+			}
+		}
+	}
+
+	/**
+	 * Sets signal processign handlers
+	 *
+	 * @return  void
+	 */
+	protected function set_signal_handlers()
+	{
+		pcntl_signal(SIGTERM, [__CLASS__, 'terminate']);
+		pcntl_signal(SIGINT, [__CLASS__, 'terminate']);
+	}
+
+	/**
+	 * Parse and assigning command-line arguments.
+	 *
+	 * @return  void
+	 */
+	protected function assign_arguments()
+	{
+		if (isset($GLOBALS['argv']) AND is_array($GLOBALS['argv']))
+		{
+			foreach (array_slice($GLOBALS['argv'], 1) as $argument)
+			{
+				@list($param, $value) = explode('=', $argument);
+
+				if (substr($param, 0, 2) !== '--')
+				{
+					continue;
+				}
+
+				$param = ltrim($param, '-');
+
+				if (isset(self::$arguments[$param]))
+				{
+					self::$arguments[$param] = empty($value) ? TRUE : $value;
+				}
+			}
+		}
+	}
+
+	/**
+	 * Writes pid-file to specified path.
+	 *
+	 * @throws  \RuntimeException  If error while creating pid-file
+	 * @return  void
+	 */
+	protected function write_pid()
+	{
+		if (!self::$pid = posix_getpid())
+		{
+			throw new RuntimeException('Can\'t get process ID');
+		}
+
+		if (is_string(self::$arguments['pidfile']))
+		{
+			if (!@file_put_contents(self::$arguments['pidfile'], self::$pid.PHP_EOL))
+			{
+				throw new RuntimeException('Can\'t create pid-file for process');
+			}
+
+			self::$arguments['pidfile'] = realpath(self::$arguments['pidfile']);
+		}
+	}
+
+	/**
+	 * Delete pid-file from specified path.
+	 *
+	 * @throws  \RuntimeException  If error while creating pid-file
+	 * @return  void
+	 */
+	protected static function delete_pid()
+	{
+		if (is_string(self::$arguments['pidfile']) AND file_exists(self::$arguments['pidfile']))
+		{
+			@unlink(self::$arguments['pidfile']);
+		}
+	}
+
+	/**
+	 * Process fork function.
+	 *
+	 * @return  void
+	 */
+	protected function fork()
+	{
+		if (!self::$arguments['daemon'])
+		{
+			return;
+		}
+
+		switch ($pid = pcntl_fork())
+		{
+			case -1: throw new RuntimeException('Unable to fork process');
+			case  0: break;
+			default:
+				Application::$log->info('Process running in background mode on PID: '.$pid);
+				exit;
+		}
+
+		fclose(STDIN);
+		fclose(STDOUT);
+		fclose(STDERR);
+
+		$GLOBALS['STDIN']  = fopen('/dev/null', 'r');
+		$GLOBALS['STDOUT'] = fopen('/dev/null', 'w');
+		$GLOBALS['STDERR'] = fopen('php://stdout', 'w');
+
+		if (posix_setsid() === -1)
+		{
+			throw new RuntimeException('Could not set process ID');
+		}
+	}
+
+	/**
+	 * Terminate process
+	 *
+	 * @param   bool  $delete_pid  Set FALSE to keep pid-file
+	 * @return  void
+	 */
+	public static function terminate($delete_pid = TRUE)
+	{
+		if ($delete_pid)
+		{
+			Application::delete_pid();
+		}
+
+		if (!is_null(Application::$server))
+		{
+			Application::$server->listen_loop = FALSE;
+			Application::$server->close();
+		}
+
+		if (!is_null(Application::$log))
+		{
+			Application::$log->debug('Process terminated');
+		}
+
+		exit;
+	}
+
+	/**
+	 * Process tick function.
+	 *
+	 * @return  void
+	 */
+	public static function tick()
+	{
+		pcntl_signal_dispatch();
+
+		usleep(10000);
+	}
+
+} // end of class Daemon

+ 218 - 0
src/include/Inet.php

@@ -0,0 +1,218 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+/**
+ * Inet class.
+ */
+class Inet {
+
+	/*
+	 * @const  int  Number of bits in the IPv4 address
+	 */
+	const IPV4_BITS = 32;
+
+	/*
+	 * @const  int  Number of bits in the IPv6 address
+	 */
+	const IPV6_BITS = 128;
+
+
+	/**
+	 * Convert an IP address to a long string
+	 *
+	 * @param   string
+	 * @return  string|bool
+	 */
+	public static function ip2long($ip)
+	{
+		if (!filter_var($ip, FILTER_VALIDATE_IP))
+		{
+			return FALSE;
+		}
+
+		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
+		{
+			$bin = self::ip2bin($ip);
+
+			if (function_exists('gmp_init'))
+			{
+				return gmp_strval(gmp_init($bin, 2), 10);
+			}
+			elseif (function_exists('bcadd'))
+			{
+				$dec = '0';
+
+				for ($i = 0; $i < strlen($bin); $i++)
+				{
+					$dec = bcadd(bcmul($dec, '2', 0), $bin[$i], 0);
+				}
+
+				return $dec;
+			}
+
+			trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR);
+
+			return FALSE;
+		}
+
+		return @ip2long($ip);
+	}
+
+	/**
+	 * Converts an IP address to binary
+	 *
+	 * @param   string
+	 * @param   bool
+	 * @return  string|bool
+	 */
+	public static function ip2bin($ip)
+	{
+		if (!filter_var($ip, FILTER_VALIDATE_IP))
+		{
+			return FALSE;
+		}
+
+		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
+		{
+			if(($ip_n = inet_pton($ip)) === FALSE) 
+			{
+				return FALSE;
+			}
+
+			$bin = '';
+
+			for ($bit = 15; $bit >= 0; $bit--)
+			{
+				$bin = sprintf('%08b', ord($ip_n[$bit])).$bin;
+			}
+
+			return $bin;
+		}
+
+		return base_convert(ip2long($ip), 10, 2);
+	}
+
+	/**
+	 * Returns an array containing the IP address in the subnet
+	 *
+	 * @param   string
+	 * @param   array
+	 * @param   bool     If you specify TRUE, returns the full list of entries
+	 * @return  array|bool
+	 */
+	public static function ip_in_subnets($ip, $subnets, $return_all = FALSE)
+	{
+		if (!is_array($subnets))
+		{
+			$subnets = [$subnets];
+		}
+
+		$ip = self::ip2long($ip);
+		$all = [];
+
+		foreach ($subnets as $subnet)
+		{
+			$subnet = self::cidr2range($subnet);
+
+			if (!$ip OR !$subnet)
+			{
+				continue;
+			}
+
+			list($low, $high) = $subnet;
+
+			if ($ip <= self::ip2long($high) AND self::ip2long($low) <= $ip)
+			{
+				if (!$return_all)
+				{
+					return $subnet; 
+					
+					echo 1;
+				}
+
+				$all[] = $subnet;
+			}
+			elseif ($return_all)
+			{
+				$all[] = FALSE;
+			}
+		}
+
+		if ($return_all)
+		{
+			return $all;
+		}
+
+		return FALSE;
+	}
+
+	/**
+	 * Converts a CIDR block to range of addresses
+	 *
+	 * @param   string
+	 * @return  array|bool
+	 */
+	public static function cidr2range($cidr)
+	{
+		$cidr = explode('/', $cidr, 2);
+		$ip = $cidr[0];
+
+		if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
+		{
+			$prefix_len = isset($cidr[1]) ? $cidr[1] : self::IPV6_BITS;
+
+			if ($prefix_len > self::IPV6_BITS) 
+			{
+				return FALSE;
+			}
+
+			$bits = self::IPV6_BITS - $prefix_len;
+
+			$low_bin = inet_pton($ip);
+			$low_hex = unpack('H*', $low_bin);
+			$high_hex = reset($low_hex);
+			$pos = 31;
+
+			while ($bits > 0)
+			{
+				$val = hexdec(substr($high_hex, $pos, 1)) | (pow(2, min(4, $bits)) - 1);
+				$high_hex = substr_replace($high_hex, dechex($val), $pos, 1);
+
+				$bits -= 4;
+				$pos--;
+			}
+
+			$low = inet_ntop($low_bin);
+			$high = inet_ntop(pack('H*', $high_hex));
+
+			return [$low, $high];
+		}
+		elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
+		{
+			$prefix_len = isset($cidr[1]) ? $cidr[1] : self::IPV4_BITS;
+
+			if ($prefix_len > self::IPV4_BITS) 
+			{
+				return FALSE;
+			}
+
+			$bits = self::IPV4_BITS - $prefix_len;
+
+			$low = long2ip(ip2long($ip) & (-1 << $bits));
+			$high = long2ip(ip2long($ip) + pow(2, $bits) - 1);
+
+			return [$low, $high];
+		}
+
+		return FALSE;
+	}
+
+} // end of class Inet

+ 85 - 0
src/include/Log.php

@@ -0,0 +1,85 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Console;
+
+/**
+ * Log class.
+ */
+class Log extends Log\LogAbstract {
+
+	/**
+	 * Returns instance of Log.
+	 *
+	 * @return Config
+	 */
+	public static function factory()
+	{
+		return new self;
+	}
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @return  void
+	 */
+	public function __construct()
+	{
+		$this->severity = Application::$config->get('logging.severity', FALSE);
+		$this->file     = Application::$config->get('logging.file', FALSE);
+	}
+
+	/**
+	 * Adds any message to log.
+	 *
+	 * @param   string  $message   Message to write
+	 * @param   int     $severity  Message severity
+	 * @return  void
+	 */
+	public function add($message, $severity = self::info)
+	{
+		$message = '['.$this->severities[$severity][0].'] '.$message;
+
+		if ($severity < self::debug OR $this->severity >= self::debug)
+		{
+			Console::log($message, $this->severities[$severity][1]);
+		}
+
+		if ($this->severity AND $this->file AND $severity <= $this->severity)
+		{
+			@file_put_contents($this->file, '['.date('Y-m-d H:i:s').'] '.$message.PHP_EOL, FILE_APPEND);
+		}
+	}
+
+	/**
+	 * Gets name of the calling method class
+	 *
+	 * @return  string
+	 */
+	public function get_calling_class()
+	{
+		$trace = debug_backtrace();
+
+		$class = $trace[1]['class'];
+
+		for ($i = 1; $i < count($trace); $i++)
+		{
+			if (isset($trace[$i]))
+			{
+				if ($class != $trace[$i]['class'])
+				{
+					return preg_replace('/^'.__NAMESPACE__.'\\\/', '', $trace[$i]['class']);
+				}
+			}
+		}
+	}
+
+} // end of class Log

+ 91 - 0
src/include/Log/LogAbstract.php

@@ -0,0 +1,91 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Log;
+
+/**
+ * Abstract Log implementing LogInterface.
+ */
+abstract class LogAbstract implements LogInterface {
+
+	/*
+	 * @const  int   Error messages level
+	 */
+	const error   = 1;
+
+	/*
+	 * @const  int   Warning messages level
+	 */
+	const warning = 2;
+
+	/*
+	 * @const  int   Info messages level
+	 */
+	const info   = 3;
+
+	/*
+	 * @const  int   Debug messages level
+	 */
+	const debug   = 4;
+
+	/*
+	 * @var  int     Logging severity
+	 */
+	protected $severity;
+
+	/*
+	 * @var  string  Logging file path
+	 */
+	protected $path;
+
+	/*
+	 * @var  array   Severity names
+	 */
+	protected $severities =
+	[
+		self::debug   => ['debug',   'cyan'],
+		self::info    => ['info',    'green'],
+		self::warning => ['warning', 'yellow'],
+		self::error   => ['error',   'red'],
+	];
+
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function debug($message)
+	{
+		$this->add($this->get_calling_class().': '.$message, self::debug);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function info($message)
+	{
+		$this->add($message, self::info);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function warning($message)
+	{
+		$this->add($message, self::warning);
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function error($message)
+	{
+		$this->add($message, self::error);
+	}
+
+} // end of abstract class LogAbstract

+ 49 - 0
src/include/Log/LogInterface.php

@@ -0,0 +1,49 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Log;
+
+/**
+ * Log Interface.
+ */
+interface LogInterface {
+
+	/**
+	 * Adds debug message to log.
+	 *
+	 * @param   string  $message  Message to write
+	 * @return  void
+	 */
+	public function debug($message);
+
+	/**
+	 * Adds info message to log.
+	 *
+	 * @param   string  $message  Message to write
+	 * @return  void
+	 */
+	public function info($message);
+
+	/**
+	 * Adds warning message to log.
+	 *
+	 * @param   string  $message  Message to write
+	 * @return  void
+	 */
+	public function warning($message);
+
+	/**
+	 * Adds error message to log.
+	 *
+	 * @param   string  $message  Message to write
+	 * @return  void
+	 */
+	public function error($message);
+
+} // end of interface LogInterface

+ 167 - 0
src/include/Request.php

@@ -0,0 +1,167 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use pWhoisd\Storage;
+
+/**
+ * Request class.
+ */
+class Request extends Response {
+
+	/*
+	 * @var  object  Instance of Client class
+	 */
+	protected $client;
+
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @param   object  $client    Instance of Client class
+	 * @return  void
+	 */
+	public function __construct(Client $client)
+	{
+		$this->client = $client;
+	}
+
+	/**
+	 * Parse and process request and response.
+	 *
+	 * @return  void
+	 */
+	public function process()
+	{
+		if ($message = Application::$security->get_message())
+		{
+			$this->response = $this->process_message($message);
+		}
+
+		if (Application::$security->get_action() == 'deny')
+		{
+			Application::$log->warning('Access denied by security');
+
+			return;
+		}
+
+		$this->define_data_section();
+		$this->define_data_formats();
+
+		Application::$log->debug('Request processed');
+
+		if (isset($this->data_section['storage']) AND is_array($this->data_section['storage']))
+		{
+			if (!empty($this->request))
+			{
+				$storage = new Storage($this->client, $this->data_section['storage']);
+
+				$this->response_array = $storage->get($this->request);
+			}
+		}
+
+		$this->process_response_array();
+		$this->process_response();
+
+		Application::$log->debug('Response processed');
+	}
+
+	/**
+	 * Search and define section data.
+	 *
+	 * @return  void
+	 */
+	private function define_data_section()
+	{
+		$data = Application::$config->get('data');
+
+		foreach ($data as $section)
+		{
+			if (!isset($section['flag']) OR !isset($section['fields']))
+			{
+				continue;
+			}
+
+			if (!empty($section['flag']) AND $this->find_flag($section['flag']))
+			{
+				$this->data_section = $section;
+			}
+		}
+
+		if (is_null($this->data_section))
+		{
+			$this->data_section = array_shift($data);
+		}
+	}
+
+	/**
+	 * Search and define data formats.
+	 *
+	 * @return  void
+	 */
+	private function define_data_formats()
+	{
+		if (!isset($this->data_section['format']) OR !is_array($this->data_section['format']))
+		{
+			return;
+		}
+
+		$data_formats = [];
+
+		foreach ($this->data_section['format'] as $key => $section)
+		{
+			if (!isset($section[2]) OR empty($section[2]))
+			{
+				$data_formats[$key] = $section;
+			}
+			else if ($this->find_flag($section[2]))
+			{
+				$data_formats[$key] = $section;
+			}
+		}
+
+		if (!empty($data_formats))
+		{
+			$this->data_formats = $data_formats;
+		}
+	}
+
+	/**
+	 * Find flag in request string.
+	 *
+	 * @param   string  $flag  Flag string to search
+	 * @return  bool
+	 */
+	private function find_flag($flag)
+	{
+		if (preg_match('/\s+'.preg_quote($flag).'\s+/', ' '.$this->request.' '))
+		{
+			$this->request = preg_replace('/\s+'.preg_quote($flag).'\s+/', ' ', ' '.$this->request.' ', 1);
+			$this->request = trim($this->request);
+
+			return TRUE;
+		}
+
+		return FALSE;
+	}
+
+	/**
+	 * Sets current request string
+	 *
+	 * @param   string  $request  Request string to set
+	 * @return  void
+	 */
+	public function set_request($request)
+	{
+		$this->request = $this->complete_request = trim($request);
+	}
+
+} // end of class Request

+ 317 - 0
src/include/Response.php

@@ -0,0 +1,317 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+
+/**
+ * Abstract Response class.
+ */
+abstract class Response {
+
+	/*
+	 * @var  string  Request string
+	 */
+	protected $request;
+
+	/*
+	 * @var  string  Complete request string
+	 */
+	protected $complete_request;
+
+	/*
+	 * @var  array   Array of assigned data configuration section
+	 */
+	protected $data_section;
+
+	/*
+	 * @var  array   Array of assigned formats configuration
+	 */
+	protected $data_formats;
+
+	/*
+	 * @var  string  Response string
+	 */
+	protected $response;
+
+	/*
+	 * @var  array   Response array
+	 */
+	protected $response_array;
+
+
+	/**
+	 * Process response.
+	 *
+	 * @return  void
+	 */
+	protected function process_response()
+	{
+		if (!is_array($this->data_section['fields']) OR empty($this->data_section['fields']))
+		{
+			return;
+		}
+
+		$hide_empty = TRUE;
+
+		if (isset($this->data_section['hide_empty']))
+		{
+			$hide_empty = $this->data_section['hide_empty'];
+		}
+
+		$response_array = $response_array_names_len = [];
+
+		foreach ($this->data_section['fields'] as $field)
+		{
+			if (!is_array($field))
+			{
+				continue;
+			}
+
+			if (empty($field))
+			{
+				$response_array[] = '';
+
+				continue;
+			}
+
+			$field[0] = $this->process_response_macro($field[0]);
+
+			if ($field[0] === FALSE)
+			{
+				continue;
+			}
+
+			if (sizeof($field) > 1)
+			{
+				$field_flag = isset($field[2]) ? $field[2] : NULL;
+
+				if (isset($this->response_array[$field[1]]) AND $this->response_array[$field[1]] !== NULL)
+				{
+					if (!empty($this->response_array[$field[1]]) OR $hide_empty === FALSE)
+					{
+						if ($field_flag === NULL)
+						{
+							$values = explode("\n", str_replace("\r\n", "\n", $this->response_array[$field[1]]));
+
+							if (!preg_match('/\:$/', trim($field[0])))
+							{
+								$field[0] .= ':';
+							}
+
+							foreach ($values as $value)
+							{
+								$response_array[] = [$field[0], $value];
+							}
+
+							$response_array_names_len[] = strlen($field[0]);
+						}
+						elseif ($field_flag === TRUE)
+						{
+							$response_array[] = $field[0];
+						}
+					}
+				}
+				elseif ($field_flag === FALSE)
+				{
+					$response_array[] = $field[0];
+				}
+			}
+			else
+			{
+				$response_array[] = $field[0];
+			}
+		}
+
+		$max_len = 0;
+
+		if (!empty($response_array_names_len))
+		{
+			$max_len = max($response_array_names_len);
+		}
+
+		$response = [];
+
+		foreach ($response_array as $field)
+		{
+			if (is_array($field))
+			{
+				if (isset($this->data_section['spacing']) AND $this->data_section['spacing'])
+				{
+					$response[] = $field[0].' '.str_repeat(' ', $max_len - strlen($field[0])).$field[1];
+				}
+				else
+				{
+					$response[] = $field[0].$field[1];
+				}
+			}
+			else
+			{
+				$response[] = $field;
+			}
+		}
+
+		// Show invalid_request message
+		if ((empty($this->complete_request) AND empty($this->response_array)) OR empty($response))
+		{
+			$invalid_request = ['Invalid request.'];
+
+			if (isset($this->data_section['invalid_request']))
+			{
+				$invalid_request = $this->data_section['invalid_request'];
+			}
+
+			$response = [$this->process_message($invalid_request)];
+		}
+
+		$this->response = implode("\n", $response);
+	}
+
+	/**
+	 * Process response array.
+	 *
+	 * @return  void
+	 */
+	protected function process_response_array()
+	{
+		if (!is_array($this->response_array) OR empty($this->response_array))
+		{
+			return;
+		}
+
+		if (is_array($this->data_formats) AND !empty($this->data_formats))
+		{
+			foreach ($this->data_formats as $data_format)
+			{
+				if (sizeof($data_format) < 2)
+				{
+					continue;
+				}
+
+				@list($field, $format) = $data_format;
+
+				if (($eval = $this->process_response_macro($format, TRUE)) === FALSE)
+				{
+					continue;
+				}
+
+				if (!empty($eval))
+				{
+					eval("\$format = $eval;");
+				}
+
+				if (isset($this->response_array[$field]) AND $this->response_array[$field] == '0000-00-00 00:00:00')
+				{
+					$this->response_array[$field] = '';
+				}
+				else
+				{
+					$this->response_array[$field] = trim($format);
+				}
+			}
+		}
+	}
+
+	/**
+	 * Process message.
+	 *
+	 * @param   string  $message    Message string to process
+	 * @param   string  $recursion  Enables recursions in 'process_response_macro' method
+	 * @return  string
+	 */
+	protected function process_message($message, $quote = FALSE, $recursion = TRUE)
+	{
+		if (!is_array($message))
+		{
+			$message = [$message];
+		}
+
+		$lines = [];
+
+		foreach ($message as $line)
+		{
+			$line = $this->process_response_macro($line, $quote, $recursion);
+
+			if ($line !== FALSE)
+			{
+				$lines[] = $line;
+			}
+		}
+
+		return implode("\n", $lines);
+	}
+
+	/**
+	 * Process macro in response string.
+	 *
+	 * @param   string  $string     Response string to process
+	 * @param   bool    $quote      Quoting macro value
+	 * @param   string  $recursion  Enables recursions
+	 * @return  string|bool
+	 */
+	protected function process_response_macro($string, $quote = FALSE, $recursion = TRUE)
+	{
+		// System macro
+		$macros = [
+			'_request_'     => $this->request,
+			'_client_ip_'   => $this->client->get_address(),
+			'_client_port_' => $this->client->get_port(),
+		];
+
+		// Messages based macro
+		foreach (Application::$config->get('messages') as $message_key => $message_value)
+		{
+			$macros['%'.$message_key.'%'] = $message_value;
+		}
+
+		// Storage response macro
+		if (is_array($this->response_array) AND !empty($this->response_array))
+		{
+			$macros += $this->response_array;
+		}
+
+		foreach ($macros as $macro => $value)
+		{
+			if ($value !== NULL AND strpos($string, '{'.$macro.'}') !== FALSE)
+			{
+				// Recursion
+				if (is_array($value))
+				{
+					if ($recursion === FALSE)
+					{
+						continue;
+					}
+
+					$value = $this->process_message($value, $quote, FALSE);
+				}
+
+				if ($quote)
+				{
+					$value = '"'.$value.'"';
+				}
+
+				$string = str_replace('{'.$macro.'}', $value, $string);
+			}
+		}
+
+		return !preg_match('/\{[\%\w]+\}/', $string) ? $string : FALSE;
+	}
+
+	/**
+	 * Gets response string.
+	 *
+	 * @return  string
+	 */
+	public function get_response()
+	{
+		return $this->response;
+	}
+
+} // end of class Response

+ 390 - 0
src/include/Security.php

@@ -0,0 +1,390 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use pWhoisd\Inet;
+
+/**
+ * Security class.
+ */
+class Security {
+
+	/*
+	 * @const  int  One second period
+	 */
+	const interval_second = 1;
+
+	/*
+	 * @const  int  One minute period
+	 */
+	const interval_minute = 60;
+
+	/*
+	 * @const  int  One hour period
+	 */
+	const interval_hour   = 3600;
+
+	/*
+	 * @const  int  One day period
+	 */
+	const interval_day    = 86400;
+
+	/*
+	 * @var  array   Interval pools [[interval, time(), key, counter], ...]
+	 */
+	private $interval_pool = [];
+
+	/*
+	 * @var  object  Instance of Client class
+	 */
+	private $client;
+
+	/*
+	 * @var  array   Access control rules
+	 */
+	private $rules;
+
+	/*
+	 * @var  string  Message sent to client
+	 */
+	private $message;
+
+	/*
+	 * @var  string  Last assigned action
+	 */
+	private $action;
+
+
+	/**
+	 * Assigning class properties and parse rules configuration.
+	 *
+	 * @return  void
+	 */
+	public function __construct()
+	{
+		$this->rules = Application::$config->get('security.rules');
+
+		$this->parse_rules();
+	}
+
+	/**
+	 * Initialize security by client request.
+	 *
+	 * @param   object  $client  Instance of Client class
+	 * @return  void
+	 */
+	public function initialize(Client $client)
+	{
+		$this->client = $client;
+
+		$this->process_rules();
+	}
+
+	/**
+	 * Process defined access control rules.
+	 *
+	 * @return  void
+	 */
+	private function process_rules()
+	{
+		$this->message   = NULL;
+		$this->action    = NULL;
+		$this->intervals = [];
+
+		foreach (array_reverse($this->rules) as $rule)
+		{
+			if ($this->process_conditions($rule['conditions']))
+			{
+				$this->message = Application::$config->get('messages.'.$rule['message'], FALSE);
+				$this->action  = $rule['action'];
+			}
+		}
+
+		// Update presented intervals
+		foreach ($this->intervals as $key => $interval)
+		{
+			$this->interval_check($interval, $key, TRUE);
+		}
+	}
+
+	/**
+	 * Process rule condition.
+	 *
+	 * @return  bool  TRUE if all rules is accepted
+	 */
+	private function process_conditions($conditions)
+	{
+		if (empty($conditions))
+		{
+			return TRUE;
+		}
+
+		$client_address = $this->client->get_address();
+
+		$expressions = [TRUE];
+
+		foreach (['client_ip', 'requests', 'rate'] as $matched_condition)
+		{
+			foreach ($conditions as $condition)
+			{
+				$expression = NULL;
+
+				if ($condition['l'] != $matched_condition)
+				{
+					continue;
+				}
+
+				switch ($condition['l'])
+				{
+					// Match client IP policy
+					case 'client_ip':
+						$expression =  $this->compare_client_ip($condition['r']);
+						break;
+
+					// Client-based interval policy
+					case 'requests':
+						$expression = $this->compare_interval
+						(
+							$condition['op'],
+							$condition['r'],
+							$client_address
+						);
+						break;
+
+					// Global interval policy
+					case 'rate':
+						$expression = $this->compare_interval
+						(
+							$condition['op'],
+							$condition['r']
+						);
+						break;
+				}
+
+				if ($expression !== NULL)
+				{
+					$expressions[] = $expression;
+
+					if ($expression === FALSE)
+					{
+						break 2; // stop conditions checking
+					}
+				}
+			}
+		}
+
+		return (bool) min($expressions);
+	}
+
+	/**
+	 * Compares interval method.
+	 *
+	 * @param   string  Compare operator
+	 * @param   string  Variable parameter (count/type)
+	 * @param   string  Interval key
+	 * @return  bool  TRUE if condition is accepted
+	 */
+	private function compare_interval($op, $variable, $key = NULL)
+	{
+		@list($variable, $interval) = explode('/', $variable, 2);
+
+		switch ($interval)
+		{
+			case 'sec': $seconds = self::interval_second; break;
+			case 'min': $seconds = self::interval_minute; break;
+			case 'hr' : $seconds = self::interval_hour;   break;
+			case 'day': $seconds = self::interval_day;    break;
+		}
+
+		if (!isset($seconds) OR empty($variable))
+		{
+			return FALSE;
+		}
+
+		$counter = $this->interval_check($seconds, $key);
+
+		$this->intervals[$key] = $seconds;
+
+		$variable = (float) $variable;
+
+		switch ($op)
+		{
+			case '==': return $counter == $variable;
+			case '!=': return $counter != $variable;
+			case '>=': return $counter >= $variable;
+			case '<=': return $counter <= $variable;
+			case '>' : return $counter >  $variable;
+			case '<' : return $counter <  $variable;
+		}
+
+		return FALSE;
+	}
+
+	/**
+	 * Compares IP address method.
+	 *
+	 * @param   string|array  Variable parameter
+	 * @return  bool  TRUE if condition is accepted
+	 */
+	private function compare_client_ip($variable)
+	{
+		return Inet::ip_in_subnets($this->client->get_address(), $variable);
+	}
+
+	/**
+	 * Checks all intervals and returns current counter value.
+	 *
+	 * @param   int     Interval type
+	 * @param   string  Interval key
+	 * @return  int
+	 */
+	private function interval_check($interval = self::interval_second, $key = NULL, $update = FALSE)
+	{
+		$counter = FALSE;
+
+		foreach ($this->interval_pool as $id => $element)
+		{
+			if ($element[1] <= time() - $element[0])
+			{
+				$this->interval_pool[$id] = NULL;
+
+				unset($this->interval_pool[$id]);
+
+				continue;
+			}
+
+			if ($element[0] == $interval AND $element[2] == $key)
+			{
+				if ($update)
+				{
+					$counter = ++$this->interval_pool[$id][3];
+				}
+				else
+				{
+					$counter = $element[3];
+				}
+			}
+		}
+
+		if ($counter === FALSE)
+		{
+			$counter = 1;
+
+			if ($update)
+			{
+				$this->interval_pool[] = [$interval, time(), $key, ++$counter];
+			}
+		}
+
+		return $counter;
+	}
+
+	/**
+	 * Parse access control rules configuration.
+	 *
+	 * @return  void
+	 */
+	private function parse_rules()
+	{
+		$rules = [];
+
+		foreach ($this->rules as $id => $rule)
+		{
+			if (!is_array($rule))
+			{
+				continue;
+			}
+
+			$rules[$id]['action']     = NULL;
+			$rules[$id]['message']    = NULL;
+			$rules[$id]['conditions'] = [];
+
+			foreach ($rule as $rule_part)
+			{
+				// Assigning action
+				if (is_null($rules[$id]['action']) AND ($rule_part == 'allow' OR $rule_part == 'deny' OR $rule_part == 'drop'))
+				{
+					$rules[$id]['action'] = $rule_part;
+				}
+
+				// Assigning message
+				elseif (is_null($rules[$id]['message']) AND is_string($rule_part))
+				{
+					$rules[$id]['message'] = $rule_part;
+				}
+
+				// Assugning conditions
+				elseif (is_array($rule_part) AND sizeof($rule_part) >= 2)
+				{
+					$rules[$id]['conditions'][] = $this->parse_condition($rule_part);
+				}
+			}
+
+			if (is_null($rules[$id]['action']))
+			{
+				unset($rules[$id]);
+			}
+		}
+
+		$this->rules = $rules;
+	}
+
+	/**
+	 * Parse conditions in rule configuration.
+	 *
+	 * @param   array  Raw conditions array
+	 * @return  array
+	 */
+	private function parse_condition($condition_part)
+	{
+		$condition = [];
+
+		if (sizeof($condition_part) >= 3)
+		{
+			$condition['l']  = $condition_part[0];
+			$condition['op'] = $condition_part[1];
+			$condition['r']  = $condition_part[2];
+		}
+		else
+		{
+			$condition['l']  = $condition_part[0];
+			$condition['r']  = $condition_part[1];
+		}
+
+		if (!isset($condition['op']) OR !in_array($condition['op'], ['==', '!=', '=<', '=>', '<', '>']))
+		{
+			$condition['op'] = '==';
+		}
+
+		return $condition;
+	}
+
+	/**
+	 * Gets message sent to client.
+	 *
+	 * @return  string|NULL
+	 */
+	public function get_message()
+	{
+		return $this->message;
+	}
+
+	/**
+	 * Gets last assigned action.
+	 *
+	 * @return  string
+	 */
+	public function get_action()
+	{
+		return strtolower($this->action);
+	}
+
+} // end of class Security

+ 177 - 0
src/include/Server.php

@@ -0,0 +1,177 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use pWhoisd\Socket;
+use pWhoisd\Client;
+use pWhoisd\Worker;
+use RuntimeException;
+
+/**
+ * Server class.
+ */
+class Server {
+
+	/*
+	 * @var  object    Instance of Socket class for IPv4 connections
+	 */
+	private $socket;
+
+	/*
+	 * @var  object    Instance of Socket class for IPv6 connections
+	 */
+	private $socket_ipv6;
+
+	/*
+	 * @var  string    Server is now processing
+	 */
+	public $listen_loop;
+
+
+	/**
+	 * Assigning class properties and create socket.
+	 *
+	 * @return  void
+	 */
+	public function __construct()
+	{
+		$this->listen_loop = FALSE;
+
+		$listen_port = Application::$config->get('daemon.listen_port', 43);
+
+		$this->socket      = new Socket(AF_INET,  Application::$config->get('daemon.listen_address', FALSE), $listen_port);
+		$this->socket_ipv6 = new Socket(AF_INET6, Application::$config->get('daemon.listen_address_ipv6', FALSE), $listen_port);
+	}
+
+	/**
+	 * Initialize server.
+	 *
+	 * @return  void
+	 */
+	public function initialize()
+	{
+		$this->socket->initialize();
+		$this->socket_ipv6->initialize();
+	}
+
+	/**
+	 * Runs a main loop for accepting server requests.
+	 *
+	 * @throws  \RuntimeException  If error while accept connections
+	 * @throws  \RuntimeException  If error called in Worker
+	 * @return  void
+	 */
+	public function loop()
+	{
+		Application::$log->info('Server ready to accept connections');
+
+		$this->listen_loop = TRUE;
+
+		$worker_processes = [];
+
+		while ($this->listen_loop)
+		{
+			Application::tick();
+
+			if (($client_socket = $this->accept()) === FALSE)
+			{
+				continue;
+			}
+
+			Application::$log->debug('Server socket accept new connection');
+			Application::$log->debug('Client socket created');
+
+			$client = new Client($client_socket);
+			$worker = new Worker($client);
+
+			while ($pid = $worker->wait())
+			{
+				if ($pid == -1)
+				{
+					$worker_processes = [];
+
+					break;
+				}
+
+				unset($worker_processes[$pid]);
+
+				// Forces collection of any existing garbage cycles
+				gc_collect_cycles();
+			}
+
+			if (count($worker_processes) > Application::$config->get('daemon.workers'))
+			{
+				Application::$log->warning('Workers limit exceded');
+
+				$client->close();
+
+				continue;
+			}
+
+			try
+			{
+				Application::$security->initialize($client);
+
+				if ($pid = $worker->fork())
+				{
+					$worker_processes[$pid] = TRUE;
+
+					Application::$log->debug('Worker process created');
+
+					continue;
+				}
+
+				$worker->loop();
+				$client->close();
+
+				Application::$log->debug('Worker process terminated');
+
+				exit;
+			}
+			catch (\Exception $e)
+			{
+				$client->close();
+
+				throw new RuntimeException($e->getMessage());
+			}
+		}
+	}
+
+	/**
+	 * Closes a server socket resource.
+	 *
+	 * @return  void
+	 */
+	public function close()
+	{
+		$this->socket->close();
+		$this->socket_ipv6->close();
+	}
+
+	/**
+	 * Accept connection
+	 *
+	 * @return  resource|bool
+	 */
+	private function accept()
+	{
+		if (($socket = $this->socket->accept()) === FALSE)
+		{
+			if (($socket = $this->socket_ipv6->accept()) === FALSE)
+			{
+				return FALSE;
+			}
+		}
+
+		return $socket;
+	}
+
+} // end of class Server

+ 163 - 0
src/include/Socket.php

@@ -0,0 +1,163 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use RuntimeException;
+
+/**
+ * Socket class.
+ */
+class Socket {
+
+	/*
+	 * @var  resource  Server socket resource
+	 */
+	private $socket;
+
+	/*
+	 * @var  string    Listen IP address
+	 */
+	private $listen_address;
+
+	/*
+	 * @var  int       Listen port
+	 */
+	private $listen_port;
+
+	/*
+	 * @var  int       Socket domain
+	 */
+	private $domain;
+
+
+	/**
+	 * Assigning class properties and create socket.
+	 *
+	 * @return  void
+	 */
+	public function __construct($domain, $listen_address, $listen_port)
+	{
+		$this->domain         = $domain;
+		$this->listen_address = $listen_address;
+		$this->listen_port    = $listen_port;
+	}
+
+	/**
+	 * Initialize server.
+	 *
+	 * @return  void
+	 */
+	public function initialize()
+	{
+		if ($this->domain AND $this->listen_address AND $this->listen_port)
+		{
+			$this->create();
+			$this->bind();
+			$this->listen();
+		}
+	}
+
+	/**
+	 * Accept a socket connection.
+	 *
+	 * @return  bool
+	 */
+	public function accept()
+	{
+		if (is_resource($this->socket))
+		{
+			return @socket_accept($this->socket);
+		}
+
+		return FALSE;
+	}
+
+	/**
+	 * Closes a server socket resource.
+	 *
+	 * @return  void
+	 */
+	public function close()
+	{
+		if (is_resource($this->socket))
+		{
+			@socket_close($this->socket);
+
+			Application::$log->debug('Server socket closed');
+		}
+	}
+
+	/**
+	 * Creates a server socket resource and set socket options.
+	 *
+	 * @throws  \RuntimeException  If error while creating socket
+	 * @return  void
+	 */
+	protected function create()
+	{
+		$this->socket = @socket_create($this->domain, SOCK_STREAM, SOL_TCP);
+
+		if ($this->socket === FALSE)
+		{
+			throw new RuntimeException('Can\'t create socket: '.socket_strerror(socket_last_error()));
+		}
+
+		socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1);
+		socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO,
+		[
+			'sec'  => 3,
+			'usec' => 0
+		]);
+
+		Application::$log->debug('Server socket created');
+	}
+
+	/**
+	 * Binds a server socket.
+	 *
+	 * @throws  \RuntimeException  If error while binding socket
+	 * @return  void
+	 */
+	protected function bind()
+	{
+		if (is_resource($this->socket))
+		{
+			if (@socket_bind($this->socket, $this->listen_address, $this->listen_port) === FALSE)
+			{
+				throw new RuntimeException('Can\'t bind socket: '.socket_strerror(socket_last_error($this->socket)));
+			}
+
+			Application::$log->debug('Server socket binded');
+		}
+	}
+
+	/**
+	 * Listens for a connection on a server socket.
+	 *
+	 * @throws  \RuntimeException  If error while listening socket
+	 * @return  bool
+	 */
+	protected function listen()
+	{
+		if (is_resource($this->socket))
+		{
+			if(@socket_listen($this->socket, 5) === FALSE)
+			{
+				throw new RuntimeException('Can\'t listen: '.socket_strerror(socket_last_error($this->socket)));
+			}
+
+			@socket_set_nonblock($this->socket);
+
+			Application::$log->info('Server listening on '.$this->listen_address.':'.$this->listen_port.'...');
+		}
+	}
+
+} // end of class Socket

+ 95 - 0
src/include/Storage.php

@@ -0,0 +1,95 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use RuntimeException;
+
+/**
+ * Storage class.
+ */
+class Storage {
+
+	/*
+	 * @var  object  Instance of Client class
+	 */
+	private $client;
+
+	/*
+	 * @var  object  Instance of Storage Provider class
+	 */
+	private $provider;
+
+	/*
+	 * @var  array   Storage configuration segment
+	 */
+	private $storage;
+
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @param   object  $client   Instance of Client class
+	 * @param   array   $storage  Storage configuration segment
+	 * @return  void
+	 */
+	public function __construct(Client $client, $storage)
+	{
+		$this->client  = $client;
+		$this->storage = $storage;
+
+		$this->load_provider();
+	}
+
+	/**
+	 * Gets response data from storage provider.
+	 *
+	 * @param   string  $request  Requested search string
+	 * @return  array
+	 */
+	public function get($request)
+	{
+		$result = [];
+
+		if (!is_null($this->provider))
+		{
+			$result = $this->provider->get($request);
+		}
+
+		return $result;
+	}
+
+	/**
+	 * Loads storage provider class.
+	 *
+	 * @throws  \RuntimeException  If storage provider class does not exists
+	 * @return  void
+	 */
+	private function load_provider()
+	{
+		if (!isset($this->storage['type']) OR empty($this->storage['type']))
+		{
+			return;
+		}
+
+		$type  = $this->storage['type'];
+		$class = __NAMESPACE__.'\\Storage\\'.ucfirst($type).'Provider';
+
+		if (!class_exists($class))
+		{
+			throw new RuntimeException('Storage provider class "'.$class.'" does not exists');
+		}
+
+		$this->provider = new $class($this->client, $this->storage);
+
+		Application::$log->debug('Storage provider "'.$type.'" is loaded');
+	}
+
+} // end of class Storage

+ 180 - 0
src/include/Storage/MysqlProvider.php

@@ -0,0 +1,180 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Storage;
+
+use pWhoisd\Application;
+use RuntimeException;
+
+class MysqlProvider implements StorageInterface {
+
+	/*
+	 * @var  object  Instance of \pWhoisd\Client class
+	 */
+	private $client;
+
+	/*
+	 * @var  array   Storage configuration segment
+	 */
+	private $storage;
+
+	/*
+	 * @var  string  Request string
+	 */
+	private $request;
+
+	/*
+	 * @var  array   Array of SQL queries
+	 */
+	private $queries;
+
+	/*
+	 * @var  array   SQL queries result array
+	 */
+	private $result_array = [];
+
+
+	/**
+	 * Assigning class properties and connect to Database.
+	 *
+	 * @throws  \RuntimeException  If MySQL Connection error
+	 * @param   object  $client   Instance of \pWhoisd\Client class
+	 * @param   array   $storage  Storage configuration segment
+	 * @return  void
+	 */
+	public function __construct(\pWhoisd\Client $client, $storage)
+	{
+		$this->client  = $client;
+		$this->queries = $storage['queries'];
+
+		$this->db = @ new \mysqli
+		(
+			$storage['db_host'],
+			$storage['db_user'],
+			$storage['db_pass'],
+			$storage['db_name']
+		);
+
+		var_dump($storage);
+
+		if ($this->db->connect_errno)
+		{
+			throw new RuntimeException('Database connection error: '.$this->db->connect_error);
+		}
+		else
+		{
+			$this->db->set_charset(Application::$config->get('storage.db_charset', 'utf8'));
+		}
+
+		Application::$log->debug('Database connected');
+	}
+
+	/**
+	 * Closes Database connection.
+	 *
+	 * @return  void
+	 */
+	public function __destruct()
+	{
+		if (!$this->db->connect_errno)
+		{
+			$this->db->close();
+
+			Application::$log->debug('Database connection closed');
+		}
+	}
+
+	/**
+	 * {@inheritdoc}
+	 */
+	public function get($request)
+	{
+		if ($this->db->connect_errno)
+		{
+			return FALSE;
+		}
+
+		$this->request = $request;
+
+		foreach ($this->queries as $query)
+		{
+			if ($result = $this->query($query))
+			{
+				$this->result_array += $result;
+			}
+		}
+
+		return $this->result_array;
+	}
+
+	/**
+	 * Query database
+	 *
+	 * @param   string  $table   Database table name
+	 * @return  void
+	 */
+	private function query($query)
+	{
+		$query = $this->process_query_string($query);
+
+		$array = [];
+
+		if ($query !== FALSE)
+		{
+			if (!$result = $this->db->query($query))
+			{
+				throw new RuntimeException('Database '.__FUNCTION__.' qyery error: '.$this->db->error);
+			}
+
+			if ($result->num_rows)
+			{
+				$array = $result->fetch_array(MYSQLI_ASSOC);
+			}
+
+			Application::$log->debug('Database '.__FUNCTION__.' query was successful: '.$query);
+
+			$result->close();
+		}
+
+		return $array;
+	}
+
+	/**
+	 * Process SQL query string.
+	 *
+	 * @param   string  $string   SQL query string
+	 * @return  string|bool
+	 */
+	private function process_query_string($string)
+	{
+		// System macro
+		$macros = [
+			'_request_'     => str_replace(array('%', '_'), '', $this->request),
+			'_client_ip_'   => $this->client->get_address(),
+			'_client_port_' => $this->client->get_port(),
+		];
+
+		// Storage response macro
+		if (is_array($this->result_array) AND !empty($this->result_array))
+		{
+			$macros += $this->result_array;
+		}
+
+		foreach ($macros as $macro => $value)
+		{
+			if (strpos($string, '{'.$macro.'}') !== FALSE)
+			{
+				$string = str_replace('{'.$macro.'}', $this->db->real_escape_string($value), $string);
+			}
+		}
+
+		return !preg_match('/\{\w+\}/', $string) ? $string : FALSE;
+	}
+
+} // end of class MysqlProvider

+ 26 - 0
src/include/Storage/StorageInterface.php

@@ -0,0 +1,26 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd\Storage;
+
+/**
+ * Storage Interface.
+ */
+interface StorageInterface {
+
+	/**
+	 * Gets storage search result.
+	 *
+	 * @param   string  $request  Search string
+	 * @return  array|bool
+	 */
+	public function get($request);
+
+
+} // end of interface StorageInterface

+ 123 - 0
src/include/Worker.php

@@ -0,0 +1,123 @@
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+namespace pWhoisd;
+
+use pWhoisd\Application;
+use pWhoisd\Request;
+use RuntimeException;
+
+/**
+ * Worker class.
+ */
+class Worker {
+
+	/*
+	 * @var  object  Instance of Client class
+	 */
+	private $client;
+
+	/*
+	 * @var  object  Instance of Request class
+	 */
+	private $request;
+
+
+	/**
+	 * Assigning class properties.
+	 *
+	 * @param   object  $client    Instance of Client class
+	 * @return  void
+	 */
+	public function __construct(Client $client)
+	{
+		$this->client   = $client;
+		$this->request  = new Request($client);
+	}
+
+	/**
+	 * Runs a worker to client request processing.
+	 *
+	 * @return  bool
+	 */
+	public function loop()
+	{
+		$time = time() + 3;
+
+		while ($time > time())
+		{
+			$read = $this->client->read();
+
+			if ($read === NULL)
+			{
+				continue;
+			}
+
+			try
+			{
+				if (Application::$security->get_action() == 'drop')
+				{
+					Application::$log->warning('Connection dropped by security');
+
+					return TRUE;
+				}
+
+				$this->request->set_request($read);
+				$this->request->process();
+
+				if ($response = $this->request->get_response())
+				{
+					$this->client->send($response);
+				}
+			}
+			catch (\Exception $e)
+			{
+				$this->client->send('Internal error! Please try again later.');
+
+				throw new RuntimeException($e->getMessage());
+			}
+
+			return TRUE;
+		}
+
+		Application::$log->warning('Request is not readed from client socket');
+
+		return FALSE;
+	}
+
+	/**
+	 * Waits on or returns the status of a forked worker process.
+	 *
+	 * @return  int
+	 */
+	public function wait()
+	{
+		return pcntl_waitpid(-1, $status, WNOHANG);
+	}
+
+	/**
+	 * Forks the currently running worker process.
+	 *
+	 * @return  int
+	 */
+	public function fork()
+	{
+		$pid = pcntl_fork();
+
+		if ($pid == -1)
+		{
+			$this->client->close();
+
+			exit;
+		}
+
+		return $pid;
+	}
+
+} // end of class Worker

+ 22 - 0
src/pwhoisd

@@ -0,0 +1,22 @@
+#!/usr/bin/env php
+<?php
+/**
+ * HSDN PHP Whois Server Daemon
+ *
+ * @author      HSDN Team
+ * @copyright   (c) 2015, Information Networks Ltd.
+ * @link        http://www.hsdn.org
+ */
+
+(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') and die('This program cannot be run in Windows environment.');
+(PHP_SAPI === 'cli') or die('This program running available in CLI mode only.');
+
+set_time_limit(0);
+define('BINARY_PATH', realpath(dirname(__FILE__)));
+define('INCLUDE_PATH', BINARY_PATH.DIRECTORY_SEPARATOR.'include');
+chdir(BINARY_PATH.DIRECTORY_SEPARATOR);
+
+require_once INCLUDE_PATH.DIRECTORY_SEPARATOR.'Autoloader.php';
+
+\pWhoisd\Autoloader::register();
+\pWhoisd\Application::factory()->run();

+ 76 - 0
tests/rate.php

@@ -0,0 +1,76 @@
+<?php
+
+// -------------------- USER CONFIGURABLE --------------------
+
+$whois_server_ip = "127.0.0.1";
+$whois_server_port = 43;
+
+# Set the variable below to 1 to print the replies to the screen otherwise
+# zero.
+$print_replies = FALSE;
+$query_for = "ya.ru";
+
+// ----------------END OF USER CONFIGURABLE ------------------
+
+$cnt = 1;
+$s_time = time();
+$reply = '';
+
+while ($cnt < 150) 
+{
+	if (!$fp = fsockopen($whois_server_ip, $whois_server_port, $errnum, $errstr, 10))
+	{
+		die('connect: '.$errstr);
+	}
+
+	fputs($fp, $query_for."\n");
+
+	while (!feof($fp))
+	{
+		$reply .= fgets($fp, 1024);
+	}
+
+	if (strlen($reply))
+	{
+		if ($print_replies)
+		{
+			echo '['.$cnt."]\n".$reply;
+		}
+		else
+		{
+			echo '.';
+		}
+
+		$reply = '';
+	}
+	else
+	{
+		if((time() - $s_time) == 0) 
+		{
+			$rate = 0;
+		}
+		else
+		{
+			$rate = $cnt / (time() - $s_time);
+		}
+
+		var_dump($reply);
+
+		echo "\n";
+		echo 'Stopped at query number '.$cnt."\n";
+		echo 'Average rate is '.$rate." queries per second\n";
+		echo "Time: ".(time() - $s_time)."\n";
+
+		exit;
+	}
+
+	fclose($fp);
+
+	$cnt++;
+}
+
+$rate = $cnt / (time() - $s_time);
+
+echo "\n";
+echo 'Stopped at query number '.$cnt."\n";
+echo 'Average rate is '.$rate." queries per second\n";