Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 1812

Přidáno uživatelem Ondřej Fibich před více než 11 roky(ů)

Novinky:
- fixes #342: Ziskani MAC adresy skrze SNMP
- system trid pro implementaci ruzne funkcnosti nad SNMP
- zavyslost freenetisu na baliku php5-snmp

Zobrazit rozdíly:

freenetis/branches/1.1/application/i18n/cs_CZ/help.php
'connection_request_info' => 'Pro připojení neregistrované přípojky/zařízení vyplňte prosím tento formulář.<br/>Rozhodnutí o vyhovění/zamítnutí Vaší žádosti Vám bude zasláno na Vaši e-mailovou adresu.',
'connection_request_info_short' => 'Pro připojení neregistrované přípojky/zařízení vyplňte prosím tento formulář.',
'connection_request_user_pre_info' => 'V naší síti není přípojka (zařízení), kterou aktuálně používáte, zaregistrována a tudíž z ní nebude povolen přístup na internet, přejete si %s?',
'connection_request_mac_address' => 'Fyzická adresa zařízení, se kterým se snažíte přistoupit na internet (PC, notebook, mobil). Pokud nedokážete tuto vlastnost zjistit, použijte tlačítko u políčka, které se pokusí adresu načíst automaticky.',
'connection_request_mac_address' => 'Fyzická adresa zařízení, se kterým se snažíte přistoupit na internet (PC, notebook, mobil).',
'content_of_message' => 'Obsah zprávy pro přesměrování je možno díky zabudovanému editoru měnit jak ručně, tak s pomocí jeho palety formátování. V textu lze využít několik speciálních tagů ve složených závorkách, které se zobrazí podle IP adresy přesměrovaného člena. {member_name} zobrazí jméno člena, {member_id} ID člena, {ip_address} IP adresu, {subnet_name} název podsítě, {variable_symbol} variabilní symbol, {balance} zůstatek, {comment} osobní komentář.',
'credit_subaccounts' => 'Kreditní podúčty jsou jinde ve Freenetisu zmíněny jako kreditní účty, ovšem z pohledu účetního, jde spíše o podúčty. Z pohledu účetního jde stále o jeden účet 221100. Zde jsou ovšem vypsány podúčty, které vyjadřují vnitřní rozdělení peněz na účtu a jde o peníze na účtech jednotlivých členů.',
'current_credit' => 'Aktuální stav vašeho kreditu. Z vašeho účtu je každý měsíc strháván členský příspěvek. V případě, že se blížíte k nule, nebo jste se dostali do mínusu, je třeba kredit dobít zaplacením členského příspěvku.',
freenetis/branches/1.1/application/i18n/en_US/help.php
'connection_request_info' => 'To connect unregistered connections/device please fill out this form.<br/>Decision on the pass/rejection of your request will be sent to your e-mail address.',
'connection_request_info_short' => 'To connect unregistered connections/device please fill out this form.',
'connection_request_user_pre_info' => 'In our network the connection (device) that you are currently using is not registered and therefore it is not allowed to access the internet with it. Would you like to %s?',
'connection_request_mac_address' => 'The physical address of the device that you are trying to access the internet (PC, laptop, mobile, ...). If you can not find this property, use the button near the field that tries to automatically load the address.',
'connection_request_mac_address' => 'The physical address of the device that you are trying to access the internet (PC, laptop, mobile, ...).',
'content_of_message' => 'The content of the message for redirection is possible thanks to the built-in editor to modify both manually and with its variety of formatting. In the text you can use some special tags in curly brackets, which are displayed by IP address redirected member. {member_name} display member\'s name, {member_id} Member ID, {ip_address} IP address, {subnet_name} subnet name, {variable_symbol} variable symbol, {balance} balance, {comment} personal commentary.',
'credit_subaccounts' => 'Credit sub-accounts are elsewhere in Freenetisu mentioned as credit accounts, but in terms of accounting, but rather a sub-accounts. From the perspective of accounting is still a single account 221100. Here, however, are sub-listed, which express the internal distribution of money in the account and the money goes to the accounts of individual members.',
'current_credit' => 'The current status of your credit. Membership fee is deducted monthly from account. In the event that you are approaching zero, or you get to minus, you need to recharge your credit by paying the membership fee.',
freenetis/branches/1.1/application/vendors/deb/freenetis/control
Priority: optional
Section: web
Pre-Depends: debconf (>= 0.5) | debconf-2.0
Depends: coreutils, wget, grep, apache2, php5, php5-curl, libapache2-mod-php5, php5-mysql | php5-mysqli, mysql-client, php5-mcrypt, php5-gd
Depends: coreutils, wget, grep, apache2, php5, php5-curl, libapache2-mod-php5, php5-mysql | php5-mysqli, mysql-client, php5-mcrypt, php5-gd, php5-snmp
Suggests: mysql-server (>= 5.0.0), mysql-client
Architecture: all
Maintainer: Ondrej Fibich <ondrej.fibich@gmail.com>
freenetis/branches/1.1/application/helpers/text.php
}
/**
* Check if first string ends with second
*
* @author Ondřej Fibich
* @param string $str String
* @param string $end End
* @return bool true if first string ends with second
*/
public static function ends_with($str, $end)
{
return strcmp(mb_substr($str, mb_strlen($str) - mb_strlen($end)), $end) == 0;
}
/**
* Pushes object properties into given format string
*
* @author Ondřej Fibich
freenetis/branches/1.1/application/models/ip_address.php
return ($result && $result->current()) ? $result->current() : FALSE;
}
/**
* Function gets gateway of gievn subnet
*
* @param string $network_address
* @return Ip_address_Model
*/
public function get_dhcp_of_subnet($subnet_id)
{
$result = $this->db->query("
SELECT * FROM ip_addresses ip
WHERE dhcp = 1 AND subnet_id = ?
LIMIT 0,1
", $subnet_id);
return ($result && $result->current()) ? $result->current() : FALSE;
}
/**
* Gets all allowed IP addresses.
freenetis/branches/1.1/application/controllers/connection_requests.php
$types[NULL] = '----- '.__('Select type').' -----';
asort($types);
// get MAC address using SNMP to DHCP server
if ($this->session->get('connection_request_mac'))
{
$ip_address_model = new Ip_address_Model();
$dhcp_device = $ip_address_model->get_gateway_of_subnet($subnet_id);
if ($dhcp_device)
{
$snmp = Snmp_Factory::factoryForDevice($dhcp_device->ip_address);
try
{
$mac_address = $snmp->getMacAddressOf($ip_address);
$this->session->set('connection_request_mac', $mac_address);
}
catch (Exception $e)
{
Log::add_exception($e);
status::mwarning($e->getMessage());
}
}
}
// form
$form = new Forge();
......
->style('width:200px');
}
$form->input('mac_address')
->label('MAC address of device')
->rules('required|valid_mac_address')
->help('connection_request_mac_address');
if (!$this->session->get('connection_request_mac') ||
$this->acl_check_new('Devices_Controller', 'devices'))
{ // admin or not detected
$form->input('mac_address')
->label('MAC address of device')
->value($this->session->get('connection_request_mac'))
->rules('required|valid_mac_address')
->help('connection_request_mac_address');
}
$form->textarea('note');
......
$cr_model->added_user_id = $this->user_id;
$cr_model->created_at = date('Y-m-d H:i:s');
$cr_model->ip_address = $ip_address;
$cr_model->mac_address = $form_data['mac_address'];
if (!$this->session->get('connection_request_mac') ||
$this->acl_check_new('Devices_Controller', 'devices'))
{
$cr_model->mac_address = $form_data['mac_address'];
}
else
{
$cr_model->mac_address = $this->session->get('connection_request_mac');
}
$cr_model->subnet_id = $subnet_model->id;
$cr_model->device_type_id = $form_data['device_type_id'];
$cr_model->device_template_id = $form_data['device_template_id'];
......
$this->acl_check_new('Devices_Controller', 'devices'))
{
// redirect to add form
$this->session->del('connection_request_mac');
url::redirect('connection_requests/approve_request/' . $cr_model->id);
}
else
......
FALSE
);
$this->session->del('connection_request_mac');
$this->redirect('connection_requests/show/', $cr_model->id);
}
}
freenetis/branches/1.1/application/libraries/Snmp_Factory.php
<?php defined('SYSPATH') or die('No direct script access.');
/*
* This file is part of open source system FreenetIS
* and it is released under GPLv3 licence.
*
* More info about licence can be found:
* http://www.gnu.org/licenses/gpl-3.0.html
*
* More info about project can be found:
* http://www.freenetis.org/
*
*/
define("SNMP_CLASS_PATH", APPPATH . 'libraries/snmp/');
require_once SNMP_CLASS_PATH . 'Abstract_Snmp.php';
require_once SNMP_CLASS_PATH . 'Mikrotik_Snmp.php';
require_once SNMP_CLASS_PATH . 'Linux_Snmp.php';
/**
* factory for creating of SNMP handlers.
*
* @author Ondrej Fibich
*/
class Snmp_Factory
{
/**
* Mikrotik driver name
*/
const MIKROTIK = 'mikrotik';
/**
* List of available drivers.
* Key contains name of driver.
* Value contains information about driver such as version (version of SNMP)
* and class (class of driver). (more oprtions will be added in future)
*
* @var array
*/
public static $DRIVERS = array
(
'mikrotik' => array
(
'version' => 2,
'class' => 'Mikrotik_Snmp'
),
'linux' => array
(
'version' => 2,
'class' => 'Linux_Snmp'
)
);
/**
* Creates SNMP driver with the given name.
*
* @param string $driver Driver name
* @return Abstract_SNMP Creates driver
* @throws InvalidArgumentException On invalid driver name (unknown)
*/
public static function factory($driver)
{
if (array_key_exists($driver, self::$DRIVERS))
{
return new self::$DRIVERS[$driver]['class'];
}
// driver not exists
$m = 'Driver ' . $driver . ' does not exists.';
throw new InvalidArgumentException($m);
}
/**
* Creates SNMP driver for the device from the given IP address.
*
* @param string $device_ip Device IP address
* @return Abstract_Snmp
* @throws InvalidArgumentException If no driver suits the given device
*/
public static function factoryForDevice($device_ip)
{
foreach (self::$DRIVERS as $key => $val)
{
$snmp = self::factory($key);
if ($snmp->isCompactibleDriverWith($device_ip))
{
$snmp->setDeviceIp($device_ip);
return $snmp;
}
}
// not founded
$m = 'There is no driver for the device on ' . $device_ip;
throw new InvalidArgumentException($m);
}
}
freenetis/branches/1.1/application/libraries/snmp/Linux_Snmp.php
<?php defined('SYSPATH') or die('No direct script access.');
/*
* This file is part of open source system FreenetIS
* and it is released under GPLv3 licence.
*
* More info about licence can be found:
* http://www.gnu.org/licenses/gpl-3.0.html
*
* More info about project can be found:
* http://www.freenetis.org/
*
*/
/**
* Linux SNMP driver.
* This class MUST not be initialized directly, use Snmp_Factory!
*
* @author Ondrej Fibich
* @see Abstract_Snmp
*/
class Linux_Snmp extends Abstract_Snmp
{
public function isCompactibleDriverWith($device_ip)
{
if (!valid::ip($device_ip))
{
throw new InvalidArgumentException('Wrong IP address of the device');
}
try
{
$this->startErrorHandler();
$row = snmp2_get(
$device_ip, $this->comunity, 'iso.3.6.1.2.1.1.1.0',
$this->timeout, $this->retries
);
$this->stopErrorHandler();
}
catch (Exception $e)
{
return FALSE;
}
// parse result
$matches = array();
if (preg_match('/STRING: "(.*)"/', $row, $matches) > 0)
{
return text::starts_with($matches[1], 'Linux');
}
else
{
return FALSE;
}
}
/**
* @todo it currently using ARP table, so it does not work with bridged
* clients
*/
public function getMacAddressOf($device_ip)
{
if (!valid::ip($device_ip))
{
throw new InvalidArgumentException('Wrong IP address of the device');
}
// obtain
$this->startErrorHandler();
$arp_table = snmp2_real_walk(
$this->deviceIp, $this->comunity, 'iso.3.6.1.2.1.3.1.1.2',
$this->timeout, $this->retries
);
$this->stopErrorHandler();
// parse result
$regex = '/Hex-STRING: (([0-9a-fA-F]{2}\s){5}[0-9a-fA-F]{2})/';
$matches = array();
foreach ($arp_table as $key => $val)
{
if (text::ends_with($key, '.' . $device_ip) &&
preg_match($regex, $val, $matches))
{
return mb_strtolower(str_replace(' ', ':', $matches[1]));
}
}
throw new Exception('Given IP address ' . $device_ip
. ' not in ARP table on ' . $this->deviceIp);
}
}
freenetis/branches/1.1/application/libraries/snmp/Abstract_Snmp.php
<?php defined('SYSPATH') or die('No direct script access.');
/*
* This file is part of open source system FreenetIS
* and it is released under GPLv3 licence.
*
* More info about licence can be found:
* http://www.gnu.org/licenses/gpl-3.0.html
*
* More info about project can be found:
* http://www.freenetis.org/
*
*/
/**
* Abstract SNMP library. This class contains all function that are available
* for each driver.
*
* A driver may be created using Snmp_Factory.
* Each driver is connected to a single device that is reprezented by it's IP.
*
* @author Ondrej Fibich
*/
abstract class Abstract_Snmp
{
/**
* The number of microseconds until the first timeout.
*
* @var int
*/
protected $timeout = 1000000;
/**
* The number of times to retry if timeouts occur.
*
* @var int
*/
protected $retries = 5;
/**
* The read community.
*
* @var string
*/
protected $comunity = 'public';
/**
* Indicates whether the error handling is started or not.
*
* @var bool
*/
protected $error_handler_started = FALSE;
/**
* IP address of device.
*
* @var string
*/
protected $deviceIp;
/**
* Checks if the driver is compactible with the driver.
*
* @param string $device_ip Device IP address
* @return bool Is compactible?
*/
public abstract function isCompactibleDriverWith($device_ip);
/**
* Obtaint MAC address of a device with the given IP address.
* This function also must work even if the bridged elements occurs
* in the network (ARP tabla cannot be used).
*
* The device IP is DHCP server for the given device IP.
*
* @param string $device_ip IP address of the device (we would like to know his MAC)
* @return string MAC address in format xx:xx:xx:xx:xx:xx
* @throws Exception On SNMP error or wrong SNMP response
* @throws InvalidArgumentException On wrong IP address
*/
public abstract function getMacAddressOf($device_ip);
/**
* Gets the current number of microseconds until the first timeout.
*
* @return int
*/
public function getTimeout()
{
return $this->timeout;
}
/**
* Sets the number of microseconds until the first timeout.
*
* @param int $timeout Timeout in microseconds
*/
public function setTimeout($timeout)
{
$this->timeout = $timeout;
}
/**
* Gets the number of times to retry if timeouts occur.
*
* @return int
*/
public function getRetries()
{
return $this->retries;
}
/**
* Sets the number of times to retry if timeouts occur.
*
* @param int $retries
*/
public function setRetries($retries)
{
$this->retries = $retries;
}
/**
* Gets the read community.
*
* @return string The read comunity (e.g. "public")
*/
public function getComunity()
{
return $this->comunity;
}
/**
* Sets the read community.
*
* @param string $comunity The read comunity (e.g. "public")
*/
public function setComunity($comunity)
{
$this->comunity = $comunity;
}
/**
* Sets device IP.
*
* @param string $device_ip New IP address
* @throws InvalidArgumentException If ip address is invalid
*/
public function setDeviceIp($device_ip)
{
if (!valid::ip($device_ip))
{
throw new InvalidArgumentException('Wrong or empty IP address');
}
$this->deviceIp = $device_ip;
}
/**
* Gets device IP address.
*
* @return string
*/
public function getDeviceIp()
{
return $this->deviceIp;
}
/**
* Handles errors (throws exceptions)
*
* @param int $errno
* @param string $errstr
* @param int $errfile
* @param int $errline
* @throws Exception
*/
public function errorHandler($errno, $errstr, $errfile, $errline)
{
$this->stopErrorHandler();
throw new Exception($errstr, $errno);
}
/**
* Starts handling PHP errors as Exceptions (if not already started)
*/
protected function startErrorHandler()
{
if (!$this->error_handler_started)
{
$this->error_handler_started = TRUE;
set_error_handler(array($this, 'errorHandler'));
}
}
/**
* Stops handling PHP errors as Exceptions (if not alreasy stopped)
*/
protected function stopErrorHandler()
{
if ($this->error_handler_started)
{
$this->error_handler_started = FALSE;
restore_error_handler();
}
}
}
freenetis/branches/1.1/application/libraries/snmp/Mikrotik_Snmp.php
<?php defined('SYSPATH') or die('No direct script access.');
/*
* This file is part of open source system FreenetIS
* and it is released under GPLv3 licence.
*
* More info about licence can be found:
* http://www.gnu.org/licenses/gpl-3.0.html
*
* More info about project can be found:
* http://www.freenetis.org/
*
*/
/**
* Mikrotik SNMP driver.
* This class MUST not be initialized directly, use Snmp_Factory!
*
* @author Ondrej Fibich
* @see Abstract_Snmp
*/
class Mikrotik_Snmp extends Abstract_Snmp
{
public function isCompactibleDriverWith($device_ip)
{
if (!valid::ip($device_ip))
{
throw new InvalidArgumentException('Wrong IP address of the device');
}
try
{
$this->startErrorHandler();
$row = snmp2_get(
$device_ip, $this->comunity, 'iso.3.6.1.2.1.1.1.0',
$this->timeout, $this->retries
);
$this->stopErrorHandler();
}
catch (Exception $e)
{
return FALSE;
}
// parse result
$matches = array();
if (preg_match('/STRING: "(.*)"/', $row, $matches) > 0)
{
return text::starts_with($matches[1], 'RouterOS');
}
else
{
return FALSE;
}
}
public function getMacAddressOf($device_ip)
{
if (!valid::ip($device_ip))
{
throw new InvalidArgumentException('Wrong IP address of the device');
}
// obtain
$this->startErrorHandler();
$row = snmp2_get(
$this->deviceIp, $this->comunity,
'iso.3.6.1.2.1.9999.1.1.6.4.1.8.' . $device_ip,
$this->timeout, $this->retries
);
$this->stopErrorHandler();
// parse result
$regex = '/Hex-STRING: (([0-9a-fA-F]{2}\s){5}[0-9a-fA-F]{2})/';
$matches = array();
if (preg_match($regex, $row, $matches) > 0)
{
return mb_strtolower(str_replace(' ', ':', $matches[1]));
}
else
{
throw new Exception('Invalid SMNP output during obtaning of MAC address: ' . $row);
}
}
}
freenetis/branches/1.1/application/views/js/connection_requests_add.php
<?php
/**
* JavaScript funcionality for adding of request for connection.
*
* @author Ondřej Fibich
*/
// IDE complementation
if (FALSE): ?><script type='text/javascript'><?php endif
?>
// add button for auto loading of MAC address
$('#mac_address').after(
$('<a>').attr('href', '#').css('padding', '5px')
.attr('title', '<?php echo __('Automatically load MAC address') ?>')
.html('<?php echo html::image('/media/images/icons/refresh.gif') ?>')
);

Také k dispozici: Unified diff