add_lang('acp/modules');
$this->tpl_name = 'acp_modules';
// module class
$this->module_class = $mode;
if ($this->module_class == 'ucp')
{
$user->add_lang('ucp');
}
else if ($this->module_class == 'mcp')
{
$user->add_lang('mcp');
}
if ($module->p_class != $this->module_class)
{
$module->add_mod_info($this->module_class);
}
$this->page_title = strtoupper($this->module_class);
$this->parent_id = request_var('parent_id', 0);
$module_id = request_var('m', 0);
$action = request_var('action', '');
$errors = array();
switch ($action)
{
case 'delete':
if (!$module_id)
{
trigger_error($user->lang['NO_MODULE_ID'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
if (confirm_box(true))
{
// Make sure we are not directly within a module
if ($module_id == $this->parent_id)
{
$sql = 'SELECT parent_id
FROM ' . MODULES_TABLE . '
WHERE module_id = ' . $module_id;
$result = $db->sql_query($sql);
$this->parent_id = (int) $db->sql_fetchfield('parent_id');
$db->sql_freeresult($result);
}
$errors = $this->delete_module($module_id);
if (!sizeof($errors))
{
$this->remove_cache_file();
trigger_error($user->lang['MODULE_DELETED'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id));
}
}
else
{
confirm_box(false, 'DELETE_MODULE', build_hidden_fields(array(
'i' => $id,
'mode' => $mode,
'parent_id' => $this->parent_id,
'module_id' => $module_id,
'action' => $action,
)));
}
break;
case 'enable':
case 'disable':
if (!$module_id)
{
trigger_error($user->lang['NO_MODULE_ID'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$sql = 'SELECT *
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND module_id = $module_id";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
trigger_error($user->lang['NO_MODULE'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$sql = 'UPDATE ' . MODULES_TABLE . '
SET module_enabled = ' . (($action == 'enable') ? 1 : 0) . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND module_id = $module_id";
$db->sql_query($sql);
add_log('admin', 'LOG_MODULE_' . strtoupper($action), $this->lang_name($row['module_langname']));
$this->remove_cache_file();
break;
case 'move_up':
case 'move_down':
if (!$module_id)
{
trigger_error($user->lang['NO_MODULE_ID'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$sql = 'SELECT *
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND module_id = $module_id";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
trigger_error($user->lang['NO_MODULE'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$move_module_name = $this->move_module_by($row, $action, 1);
if ($move_module_name !== false)
{
add_log('admin', 'LOG_MODULE_' . strtoupper($action), $this->lang_name($row['module_langname']), $move_module_name);
$this->remove_cache_file();
}
break;
case 'quickadd':
$quick_install = request_var('quick_install', '');
if (confirm_box(true))
{
if (!$quick_install || strpos($quick_install, '::') === false)
{
break;
}
list($module_basename, $module_mode) = explode('::', $quick_install);
// Check if module name and mode exist...
$fileinfo = $this->get_module_infos($module_basename);
$fileinfo = $fileinfo[$module_basename];
if (isset($fileinfo['modes'][$module_mode]))
{
$module_data = array(
'module_basename' => $module_basename,
'module_enabled' => 0,
'module_display' => (isset($fileinfo['modes'][$module_mode]['display'])) ? $fileinfo['modes'][$module_mode]['display'] : 1,
'parent_id' => $this->parent_id,
'module_class' => $this->module_class,
'module_langname' => $fileinfo['modes'][$module_mode]['title'],
'module_mode' => $module_mode,
'module_auth' => $fileinfo['modes'][$module_mode]['auth'],
);
$errors = $this->update_module_data($module_data);
if (!sizeof($errors))
{
$this->remove_cache_file();
trigger_error($user->lang['MODULE_ADDED'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id));
}
}
}
else
{
confirm_box(false, 'ADD_MODULE', build_hidden_fields(array(
'i' => $id,
'mode' => $mode,
'parent_id' => $this->parent_id,
'action' => 'quickadd',
'quick_install' => $quick_install,
)));
}
break;
case 'edit':
if (!$module_id)
{
trigger_error($user->lang['NO_MODULE_ID'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$module_row = $this->get_module_row($module_id);
// no break
case 'add':
if ($action == 'add')
{
$module_row = array(
'module_basename' => '',
'module_enabled' => 0,
'module_display' => 1,
'parent_id' => 0,
'module_langname' => utf8_normalize_nfc(request_var('module_langname', '', true)),
'module_mode' => '',
'module_auth' => '',
);
}
$module_data = array();
$module_data['module_basename'] = request_var('module_basename', (string) $module_row['module_basename']);
$module_data['module_enabled'] = request_var('module_enabled', (int) $module_row['module_enabled']);
$module_data['module_display'] = request_var('module_display', (int) $module_row['module_display']);
$module_data['parent_id'] = request_var('module_parent_id', (int) $module_row['parent_id']);
$module_data['module_class'] = $this->module_class;
$module_data['module_langname'] = utf8_normalize_nfc(request_var('module_langname', (string) $module_row['module_langname'], true));
$module_data['module_mode'] = request_var('module_mode', (string) $module_row['module_mode']);
$submit = (isset($_POST['submit'])) ? true : false;
if ($submit)
{
if (!$module_data['module_langname'])
{
trigger_error($user->lang['NO_MODULE_LANGNAME'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
$module_type = request_var('module_type', 'category');
if ($module_type == 'category')
{
$module_data['module_basename'] = $module_data['module_mode'] = $module_data['module_auth'] = '';
$module_data['module_display'] = 1;
}
if ($action == 'edit')
{
$module_data['module_id'] = $module_id;
}
// Adjust auth row
if ($module_data['module_basename'] && $module_data['module_mode'])
{
$fileinfo = $this->get_module_infos($module_data['module_basename']);
$module_data['module_auth'] = $fileinfo[$module_data['module_basename']]['modes'][$module_data['module_mode']]['auth'];
}
$errors = $this->update_module_data($module_data);
if (!sizeof($errors))
{
$this->remove_cache_file();
trigger_error((($action == 'add') ? $user->lang['MODULE_ADDED'] : $user->lang['MODULE_EDITED']) . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id));
}
}
// Category/not category?
$is_cat = (!$module_data['module_basename']) ? true : false;
// Get module information
$module_infos = $this->get_module_infos();
// Build name options
$s_name_options = $s_mode_options = '';
foreach ($module_infos as $option => $values)
{
if (!$module_data['module_basename'])
{
$module_data['module_basename'] = $option;
}
// Name options
$s_name_options .= '';
$template->assign_block_vars('m_names', array('NAME' => $option, 'A_NAME' => addslashes($option)));
// Build module modes
foreach ($values['modes'] as $m_mode => $m_values)
{
if ($option == $module_data['module_basename'])
{
$s_mode_options .= '';
}
$template->assign_block_vars('m_names.modes', array(
'OPTION' => $m_mode,
'VALUE' => $this->lang_name($m_values['title']),
'A_OPTION' => addslashes($m_mode),
'A_VALUE' => addslashes($this->lang_name($m_values['title'])))
);
}
}
$s_cat_option = '';
$template->assign_vars(array_merge(array(
'S_EDIT_MODULE' => true,
'S_IS_CAT' => $is_cat,
'S_CAT_OPTIONS' => $s_cat_option . $this->make_module_select($module_data['parent_id'], ($action == 'edit') ? $module_row['module_id'] : false, false, false, false, true),
'S_MODULE_NAMES' => $s_name_options,
'S_MODULE_MODES' => $s_mode_options,
'U_BACK' => $this->u_action . '&parent_id=' . $this->parent_id,
'U_EDIT_ACTION' => $this->u_action . '&parent_id=' . $this->parent_id,
'L_TITLE' => $user->lang[strtoupper($action) . '_MODULE'],
'MODULENAME' => $this->lang_name($module_data['module_langname']),
'ACTION' => $action,
'MODULE_ID' => $module_id,
),
array_change_key_case($module_data, CASE_UPPER))
);
if (sizeof($errors))
{
$template->assign_vars(array(
'S_ERROR' => true,
'ERROR_MSG' => implode('
', $errors))
);
}
return;
break;
}
// Default management page
if (sizeof($errors))
{
if ($request->is_ajax())
{
$json_response = new phpbb_json_response;
$json_response->send(array(
'MESSAGE_TITLE' => $user->lang('ERROR'),
'MESSAGE_TEXT' => implode('
', $errors),
));
}
$template->assign_vars(array(
'S_ERROR' => true,
'ERROR_MSG' => implode('
', $errors))
);
}
if (!$this->parent_id)
{
$navigation = strtoupper($this->module_class);
}
else
{
$navigation = '' . strtoupper($this->module_class) . '';
$modules_nav = $this->get_module_branch($this->parent_id, 'parents', 'descending');
foreach ($modules_nav as $row)
{
$langname = $this->lang_name($row['module_langname']);
if ($row['module_id'] == $this->parent_id)
{
$navigation .= ' -> ' . $langname;
}
else
{
$navigation .= ' -> ' . $langname . '';
}
}
}
// Jumpbox
$module_box = $this->make_module_select($this->parent_id, false, false, false, false);
$sql = 'SELECT *
FROM ' . MODULES_TABLE . "
WHERE parent_id = {$this->parent_id}
AND module_class = '" . $db->sql_escape($this->module_class) . "'
ORDER BY left_id";
$result = $db->sql_query($sql);
if ($row = $db->sql_fetchrow($result))
{
do
{
$langname = $this->lang_name($row['module_langname']);
if (!$row['module_enabled'])
{
$module_image = '
';
}
else
{
$module_image = (!$row['module_basename'] || $row['left_id'] + 1 != $row['right_id']) ? '
' : '
';
}
$url = $this->u_action . '&parent_id=' . $this->parent_id . '&m=' . $row['module_id'];
$template->assign_block_vars('modules', array(
'MODULE_IMAGE' => $module_image,
'MODULE_TITLE' => $langname,
'MODULE_ENABLED' => ($row['module_enabled']) ? true : false,
'MODULE_DISPLAYED' => ($row['module_display']) ? true : false,
'S_ACP_CAT_SYSTEM' => ($this->module_class == 'acp' && $row['module_langname'] == 'ACP_CAT_SYSTEM') ? true : false,
'S_ACP_MODULE_MANAGEMENT' => ($this->module_class == 'acp' && ($row['module_basename'] == 'modules' || $row['module_langname'] == 'ACP_MODULE_MANAGEMENT')) ? true : false,
'U_MODULE' => $this->u_action . '&parent_id=' . $row['module_id'],
'U_MOVE_UP' => $url . '&action=move_up',
'U_MOVE_DOWN' => $url . '&action=move_down',
'U_EDIT' => $url . '&action=edit',
'U_DELETE' => $url . '&action=delete',
'U_ENABLE' => $url . '&action=enable',
'U_DISABLE' => $url . '&action=disable')
);
}
while ($row = $db->sql_fetchrow($result));
}
else if ($this->parent_id)
{
$row = $this->get_module_row($this->parent_id);
$url = $this->u_action . '&parent_id=' . $this->parent_id . '&m=' . $row['module_id'];
$template->assign_vars(array(
'S_NO_MODULES' => true,
'MODULE_TITLE' => $langname,
'MODULE_ENABLED' => ($row['module_enabled']) ? true : false,
'MODULE_DISPLAYED' => ($row['module_display']) ? true : false,
'U_EDIT' => $url . '&action=edit',
'U_DELETE' => $url . '&action=delete',
'U_ENABLE' => $url . '&action=enable',
'U_DISABLE' => $url . '&action=disable')
);
}
$db->sql_freeresult($result);
// Quick adding module
$module_infos = $this->get_module_infos();
// Build quick options
$s_install_options = '';
foreach ($module_infos as $option => $values)
{
// Name options
$s_install_options .= '';
}
$template->assign_vars(array(
'U_SEL_ACTION' => $this->u_action,
'U_ACTION' => $this->u_action . '&parent_id=' . $this->parent_id,
'NAVIGATION' => $navigation,
'MODULE_BOX' => $module_box,
'PARENT_ID' => $this->parent_id,
'S_INSTALL_OPTIONS' => $s_install_options,
)
);
}
/**
* Get row for specified module
*/
function get_module_row($module_id)
{
global $db, $user;
$sql = 'SELECT *
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND module_id = $module_id";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
trigger_error($user->lang['NO_MODULE'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
return $row;
}
/**
* Get available module information from module files
*/
function get_module_infos($module = '', $module_class = false)
{
global $phpbb_root_path, $phpEx;
$module_class = ($module_class === false) ? $this->module_class : $module_class;
$directory = $phpbb_root_path . 'includes/' . $module_class . '/info/';
$fileinfo = array();
if (!$module)
{
global $phpbb_extension_manager;
$finder = $phpbb_extension_manager->get_finder();
$modules = $finder
->extension_suffix('_module')
->extension_directory("/$module_class")
->core_path("includes/$module_class/info/")
->core_prefix($module_class . '_')
->get_classes();
foreach ($modules as $module)
{
$info_class = preg_replace('/_module$/', '_info', $module);
// If the class does not exist it might be following the old
// format. phpbb_acp_info_acp_foo needs to be turned into
// acp_foo_info and the respective file has to be included
// manually because it does not support auto loading
if (!class_exists($info_class))
{
$info_class = str_replace("phpbb_{$module_class}_info_", '', $module) . '_info';
if (file_exists($directory . $info_class . '.' . $phpEx))
{
include($directory . $info_class . '.' . $phpEx);
}
}
if (class_exists($info_class))
{
$info = new $info_class();
$module_info = $info->module();
$main_class = (isset($module_info['filename'])) ? $module_info['filename'] : $module;
$fileinfo[$main_class] = $module_info;
}
}
ksort($fileinfo);
}
else
{
$info_class = preg_replace('/_module$/', '_info', $module);
if (!class_exists($info_class))
{
if (file_exists($directory . $module . '.' . $phpEx))
{
include($directory . $module . '.' . $phpEx);
}
$info_class = $module . '_info';
}
// Get module title tag
if (class_exists($info_class))
{
$info = new $info_class();
$module_info = $info->module();
$main_class = (isset($module_info['filename'])) ? $module_info['filename'] : $module;
$fileinfo[$main_class] = $module_info;
}
}
return $fileinfo;
}
/**
* Simple version of jumpbox, just lists modules
*/
function make_module_select($select_id = false, $ignore_id = false, $ignore_acl = false, $ignore_nonpost = false, $ignore_emptycat = true, $ignore_noncat = false)
{
global $db, $user, $auth, $config;
$sql = 'SELECT module_id, module_enabled, module_basename, parent_id, module_langname, left_id, right_id, module_auth
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
ORDER BY left_id ASC";
$result = $db->sql_query($sql);
$right = $iteration = 0;
$padding_store = array('0' => '');
$module_list = $padding = '';
while ($row = $db->sql_fetchrow($result))
{
if ($row['left_id'] < $right)
{
$padding .= ' ';
$padding_store[$row['parent_id']] = $padding;
}
else if ($row['left_id'] > $right + 1)
{
$padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : '';
}
$right = $row['right_id'];
if (!$ignore_acl && $row['module_auth'])
{
// We use zero as the forum id to check - global setting.
if (!p_master::module_auth($row['module_auth'], 0))
{
continue;
}
}
// ignore this module?
if ((is_array($ignore_id) && in_array($row['module_id'], $ignore_id)) || $row['module_id'] == $ignore_id)
{
continue;
}
// empty category
if (!$row['module_basename'] && ($row['left_id'] + 1 == $row['right_id']) && $ignore_emptycat)
{
continue;
}
// ignore non-category?
if ($row['module_basename'] && $ignore_noncat)
{
continue;
}
$selected = (is_array($select_id)) ? ((in_array($row['module_id'], $select_id)) ? ' selected="selected"' : '') : (($row['module_id'] == $select_id) ? ' selected="selected"' : '');
$langname = $this->lang_name($row['module_langname']);
$module_list .= '';
$iteration++;
}
$db->sql_freeresult($result);
unset($padding_store);
return $module_list;
}
/**
* Get module branch
*/
function get_module_branch($module_id, $type = 'all', $order = 'descending', $include_module = true)
{
global $db;
switch ($type)
{
case 'parents':
$condition = 'm1.left_id BETWEEN m2.left_id AND m2.right_id';
break;
case 'children':
$condition = 'm2.left_id BETWEEN m1.left_id AND m1.right_id';
break;
default:
$condition = 'm2.left_id BETWEEN m1.left_id AND m1.right_id OR m1.left_id BETWEEN m2.left_id AND m2.right_id';
break;
}
$rows = array();
$sql = 'SELECT m2.*
FROM ' . MODULES_TABLE . ' m1
LEFT JOIN ' . MODULES_TABLE . " m2 ON ($condition)
WHERE m1.module_class = '" . $db->sql_escape($this->module_class) . "'
AND m2.module_class = '" . $db->sql_escape($this->module_class) . "'
AND m1.module_id = $module_id
ORDER BY m2.left_id " . (($order == 'descending') ? 'ASC' : 'DESC');
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
if (!$include_module && $row['module_id'] == $module_id)
{
continue;
}
$rows[] = $row;
}
$db->sql_freeresult($result);
return $rows;
}
/**
* Remove modules cache file
*/
function remove_cache_file()
{
global $cache;
// Sanitise for future path use, it's escaped as appropriate for queries
$p_class = str_replace(array('.', '/', '\\'), '', basename($this->module_class));
$cache->destroy('_modules_' . $p_class);
// Additionally remove sql cache
$cache->destroy('sql', MODULES_TABLE);
}
/**
* Return correct language name
*/
function lang_name($module_langname)
{
global $user;
return (!empty($user->lang[$module_langname])) ? $user->lang[$module_langname] : $module_langname;
}
/**
* Update/Add module
*
* @param bool $run_inline if set to true errors will be returned and no logs being written
*/
function update_module_data(&$module_data, $run_inline = false)
{
global $db, $user;
if (!isset($module_data['module_id']))
{
// no module_id means we're creating a new category/module
if ($module_data['parent_id'])
{
$sql = 'SELECT left_id, right_id
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($module_data['module_class']) . "'
AND module_id = " . (int) $module_data['parent_id'];
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
if (!$row)
{
if ($run_inline)
{
return 'PARENT_NO_EXIST';
}
trigger_error($user->lang['PARENT_NO_EXIST'] . adm_back_link($this->u_action . '&parent_id=' . $this->parent_id), E_USER_WARNING);
}
// Workaround
$row['left_id'] = (int) $row['left_id'];
$row['right_id'] = (int) $row['right_id'];
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id + 2, right_id = right_id + 2
WHERE module_class = '" . $db->sql_escape($module_data['module_class']) . "'
AND left_id > {$row['right_id']}";
$db->sql_query($sql);
$sql = 'UPDATE ' . MODULES_TABLE . "
SET right_id = right_id + 2
WHERE module_class = '" . $db->sql_escape($module_data['module_class']) . "'
AND {$row['left_id']} BETWEEN left_id AND right_id";
$db->sql_query($sql);
$module_data['left_id'] = (int) $row['right_id'];
$module_data['right_id'] = (int) $row['right_id'] + 1;
}
else
{
$sql = 'SELECT MAX(right_id) AS right_id
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($module_data['module_class']) . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$module_data['left_id'] = (int) $row['right_id'] + 1;
$module_data['right_id'] = (int) $row['right_id'] + 2;
}
$sql = 'INSERT INTO ' . MODULES_TABLE . ' ' . $db->sql_build_array('INSERT', $module_data);
$db->sql_query($sql);
$module_data['module_id'] = $db->sql_nextid();
if (!$run_inline)
{
add_log('admin', 'LOG_MODULE_ADD', $this->lang_name($module_data['module_langname']));
}
}
else
{
$row = $this->get_module_row($module_data['module_id']);
if ($module_data['module_basename'] && !$row['module_basename'])
{
// we're turning a category into a module
$branch = $this->get_module_branch($module_data['module_id'], 'children', 'descending', false);
if (sizeof($branch))
{
return array($user->lang['NO_CATEGORY_TO_MODULE']);
}
}
if ($row['parent_id'] != $module_data['parent_id'])
{
$this->move_module($module_data['module_id'], $module_data['parent_id']);
}
$update_ary = $module_data;
unset($update_ary['module_id']);
$sql = 'UPDATE ' . MODULES_TABLE . '
SET ' . $db->sql_build_array('UPDATE', $update_ary) . "
WHERE module_class = '" . $db->sql_escape($module_data['module_class']) . "'
AND module_id = " . (int) $module_data['module_id'];
$db->sql_query($sql);
if (!$run_inline)
{
add_log('admin', 'LOG_MODULE_EDIT', $this->lang_name($module_data['module_langname']));
}
}
return array();
}
/**
* Move module around the tree
*/
function move_module($from_module_id, $to_parent_id)
{
global $db;
$moved_modules = $this->get_module_branch($from_module_id, 'children', 'descending');
$from_data = $moved_modules[0];
$diff = sizeof($moved_modules) * 2;
$moved_ids = array();
for ($i = 0; $i < sizeof($moved_modules); ++$i)
{
$moved_ids[] = $moved_modules[$i]['module_id'];
}
// Resync parents
$sql = 'UPDATE ' . MODULES_TABLE . "
SET right_id = right_id - $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id < " . (int) $from_data['right_id'] . '
AND right_id > ' . (int) $from_data['right_id'];
$db->sql_query($sql);
// Resync righthand side of tree
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id - $diff, right_id = right_id - $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id > " . (int) $from_data['right_id'];
$db->sql_query($sql);
if ($to_parent_id > 0)
{
$to_data = $this->get_module_row($to_parent_id);
// Resync new parents
$sql = 'UPDATE ' . MODULES_TABLE . "
SET right_id = right_id + $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND " . (int) $to_data['right_id'] . ' BETWEEN left_id AND right_id
AND ' . $db->sql_in_set('module_id', $moved_ids, true);
$db->sql_query($sql);
// Resync the righthand side of the tree
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id + $diff, right_id = right_id + $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id > " . (int) $to_data['right_id'] . '
AND ' . $db->sql_in_set('module_id', $moved_ids, true);
$db->sql_query($sql);
// Resync moved branch
$to_data['right_id'] += $diff;
if ($to_data['right_id'] > $from_data['right_id'])
{
$diff = '+ ' . ($to_data['right_id'] - $from_data['right_id'] - 1);
}
else
{
$diff = '- ' . abs($to_data['right_id'] - $from_data['right_id'] - 1);
}
}
else
{
$sql = 'SELECT MAX(right_id) AS right_id
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND " . $db->sql_in_set('module_id', $moved_ids, true);
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$diff = '+ ' . (int) ($row['right_id'] - $from_data['left_id'] + 1);
}
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id $diff, right_id = right_id $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND " . $db->sql_in_set('module_id', $moved_ids);
$db->sql_query($sql);
}
/**
* Remove module from tree
*/
function delete_module($module_id)
{
global $db, $user;
$row = $this->get_module_row($module_id);
$branch = $this->get_module_branch($module_id, 'children', 'descending', false);
if (sizeof($branch))
{
return array($user->lang['CANNOT_REMOVE_MODULE']);
}
// If not move
$diff = 2;
$sql = 'DELETE FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND module_id = $module_id";
$db->sql_query($sql);
$row['right_id'] = (int) $row['right_id'];
$row['left_id'] = (int) $row['left_id'];
// Resync tree
$sql = 'UPDATE ' . MODULES_TABLE . "
SET right_id = right_id - $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id < {$row['right_id']} AND right_id > {$row['right_id']}";
$db->sql_query($sql);
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id - $diff, right_id = right_id - $diff
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id > {$row['right_id']}";
$db->sql_query($sql);
add_log('admin', 'LOG_MODULE_REMOVED', $this->lang_name($row['module_langname']));
return array();
}
/**
* Move module position by $steps up/down
*/
function move_module_by($module_row, $action = 'move_up', $steps = 1)
{
global $db;
/**
* Fetch all the siblings between the module's current spot
* and where we want to move it to. If there are less than $steps
* siblings between the current spot and the target then the
* module will move as far as possible
*/
$sql = 'SELECT module_id, left_id, right_id, module_langname
FROM ' . MODULES_TABLE . "
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND parent_id = " . (int) $module_row['parent_id'] . '
AND ' . (($action == 'move_up') ? 'right_id < ' . (int) $module_row['right_id'] . ' ORDER BY right_id DESC' : 'left_id > ' . (int) $module_row['left_id'] . ' ORDER BY left_id ASC');
$result = $db->sql_query_limit($sql, $steps);
$target = array();
while ($row = $db->sql_fetchrow($result))
{
$target = $row;
}
$db->sql_freeresult($result);
if (!sizeof($target))
{
// The module is already on top or bottom
return false;
}
/**
* $left_id and $right_id define the scope of the nodes that are affected by the move.
* $diff_up and $diff_down are the values to substract or add to each node's left_id
* and right_id in order to move them up or down.
* $move_up_left and $move_up_right define the scope of the nodes that are moving
* up. Other nodes in the scope of ($left_id, $right_id) are considered to move down.
*/
if ($action == 'move_up')
{
$left_id = (int) $target['left_id'];
$right_id = (int) $module_row['right_id'];
$diff_up = (int) ($module_row['left_id'] - $target['left_id']);
$diff_down = (int) ($module_row['right_id'] + 1 - $module_row['left_id']);
$move_up_left = (int) $module_row['left_id'];
$move_up_right = (int) $module_row['right_id'];
}
else
{
$left_id = (int) $module_row['left_id'];
$right_id = (int) $target['right_id'];
$diff_up = (int) ($module_row['right_id'] + 1 - $module_row['left_id']);
$diff_down = (int) ($target['right_id'] - $module_row['right_id']);
$move_up_left = (int) ($module_row['right_id'] + 1);
$move_up_right = (int) $target['right_id'];
}
// Now do the dirty job
$sql = 'UPDATE ' . MODULES_TABLE . "
SET left_id = left_id + CASE
WHEN left_id BETWEEN {$move_up_left} AND {$move_up_right} THEN -{$diff_up}
ELSE {$diff_down}
END,
right_id = right_id + CASE
WHEN right_id BETWEEN {$move_up_left} AND {$move_up_right} THEN -{$diff_up}
ELSE {$diff_down}
END
WHERE module_class = '" . $db->sql_escape($this->module_class) . "'
AND left_id BETWEEN {$left_id} AND {$right_id}
AND right_id BETWEEN {$left_id} AND {$right_id}";
$db->sql_query($sql);
$this->remove_cache_file();
return $this->lang_name($target['module_langname']);
}
}
80' href='#n780'>780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
#!/usr/bin/perl
# A very simple perl web server used by Webmin
# Require basic libraries
package miniserv;
use Socket;
use POSIX;
use Sys::Hostname;
# Find and read config file
if (@ARGV != 1) {
die "Usage: miniserv.pl <config file>";
}
if ($ARGV[0] =~ /^\//) {
$conf = $ARGV[0];
}
else {
chop($pwd = `pwd`);
$conf = "$pwd/$ARGV[0]";
}
open(CONF, $conf) || die "Failed to open config file $conf : $!";
while(<CONF>) {
s/\r|\n//g;
if (/^#/ || !/\S/) { next; }
/^([^=]+)=(.*)$/;
$name = $1; $val = $2;
$name =~ s/^\s+//g; $name =~ s/\s+$//g;
$val =~ s/^\s+//g; $val =~ s/\s+$//g;
$config{$name} = $val;
}
close(CONF);
# Check is SSL is enabled and available
if ($config{'ssl'}) {
eval "use Net::SSLeay";
if (!$@) {
$use_ssl = 1;
# These functions only exist for SSLeay 1.0
eval "Net::SSLeay::SSLeay_add_ssl_algorithms()";
eval "Net::SSLeay::load_error_strings()";
if (defined(&Net::SSLeay::X509_STORE_CTX_get_current_cert) &&
defined(&Net::SSLeay::CTX_load_verify_locations) &&
defined(&Net::SSLeay::CTX_set_verify)) {
$client_certs = 1;
}
}
}
# Check if the syslog module is available to log hacking attempts
if ($config{'syslog'}) {
eval "use Sys::Syslog qw(:DEFAULT setlogsock)";
if (!$@) {
$use_syslog = 1;
}
}
# check if the PAM module is available to authenticate
eval "use Authen::PAM";
if (!$@) {
# check if the PAM authentication can be used by opening a handle
if (! ref($pamh = new Authen::PAM("miniserv", "root", \&pam_conv_func))) {
print STDERR "PAM module available, but error during init !\n";
print STDERR "Disabling PAM functions.\n";
}
else {
$use_pam = 1;
}
}
# check if the TCP-wrappers module is available
if ($config{'libwrap'}) {
eval "use Authen::Libwrap qw(hosts_ctl STRING_UNKNOWN)";
if (!$@) {
$use_libwrap = 1;
}
}
# Get miniserv's perl path and location
$miniserv_path = $0;
open(SOURCE, $miniserv_path);
<SOURCE> =~ /^#!(\S+)/; $perl_path = $1;
close(SOURCE);
@miniserv_argv = @ARGV;
# Check vital config options
%vital = ("port", 80,
"root", "./",
"server", "MiniServ/0.01",
"index_docs", "index.html index.htm index.cgi",
"addtype_html", "text/html",
"addtype_txt", "text/plain",
"addtype_gif", "image/gif",
"addtype_jpg", "image/jpeg",
"addtype_jpeg", "image/jpeg",
"realm", "MiniServ",
"session_login", "/session_login.cgi"
);
foreach $v (keys %vital) {
if (!$config{$v}) {
if ($vital{$v} eq "") {
die "Missing config option $v";
}
$config{$v} = $vital{$v};
}
}
if (!$config{'sessiondb'}) {
$config{'pidfile'} =~ /^(.*)\/[^\/]+$/;
$config{'sessiondb'} = "$1/sessiondb";
}
die "Session authentication cannot be used in inetd mode"
if ($config{'inetd'} && $config{'session'});
# init days and months for http_date
@weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" );
@month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" );
# Change dir to the server root
chdir($config{'root'});
$user_homedir = (getpwuid($<))[7];
# Read users file
if ($config{'userfile'}) {
open(USERS, $config{'userfile'});
while(<USERS>) {
s/\r|\n//g;
local @user = split(/:/, $_);
$users{$user[0]} = $user[1];
$certs{$user[0]} = $user[3] if ($user[3]);
if ($user[4] =~ /^allow\s+(.*)/) {
$allow{$user[0]} = [ &to_ipaddress(split(/\s+/, $1)) ];
}
elsif ($user[4] =~ /^deny\s+(.*)/) {
$deny{$user[0]} = [ &to_ipaddress(split(/\s+/, $1)) ];
}
}
close(USERS);
}
# Setup SSL if possible and if requested
if ($use_ssl) {
$ssl_ctx = Net::SSLeay::CTX_new() ||
die "Failed to create SSL context : $!";
$client_certs = 0 if (!$config{'ca'} || !%certs);
if ($client_certs) {
Net::SSLeay::CTX_load_verify_locations(
$ssl_ctx, $config{'ca'}, "");
Net::SSLeay::CTX_set_verify(
$ssl_ctx, &Net::SSLeay::VERIFY_PEER, \&verify_client);
}
Net::SSLeay::CTX_use_RSAPrivateKey_file(
$ssl_ctx, $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM) || die "Failed to open SSL key";
Net::SSLeay::CTX_use_certificate_file(
$ssl_ctx, $config{'keyfile'},
&Net::SSLeay::FILETYPE_PEM);
}
# Setup syslog support if possible and if requested
if ($use_syslog) {
eval { openlog("miniserv", "cons,pid,ndelay", "daemon") };
$use_syslog = 0 if ($@);
}
# Read MIME types file and add extra types
if ($config{"mimetypes"} ne "") {
open(MIME, $config{"mimetypes"});
while(<MIME>) {
chop; s/#.*$//;
if (/^(\S+)\s+(.*)$/) {
$type = $1; @exts = split(/\s+/, $2);
foreach $ext (@exts) {
$mime{$ext} = $type;
}
}
}
close(MIME);
}
foreach $k (keys %config) {
if ($k !~ /^addtype_(.*)$/) { next; }
$mime{$1} = $config{$k};
}
# get the time zone
if ($config{'log'}) {
local(@gmt, @lct, $days, $hours, $mins);
@make_date_marr = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
@gmt = gmtime(time());
@lct = localtime(time());
$days = $lct[3] - $gmt[3];
$hours = ($days < -1 ? 24 : 1 < $days ? -24 : $days * 24) +
$lct[2] - $gmt[2];
$mins = $hours * 60 + $lct[1] - $gmt[1];
$timezone = ($mins < 0 ? "-" : "+"); $mins = abs($mins);
$timezone .= sprintf "%2.2d%2.2d", $mins/60, $mins%60;
}
if ($config{'inetd'}) {
# We are being run from inetd - go direct to handling the request
$SIG{'HUP'} = 'IGNORE';
$SIG{'TERM'} = 'DEFAULT';
$SIG{'PIPE'} = 'DEFAULT';
open(SOCK, "+>&STDIN");
# Check if it is time for the logfile to be cleared
if ($config{'logclear'}) {
local $write_logtime = 0;
local @st = stat("$config{'logfile'}.time");
if (@st) {
if ($st[9]+$config{'logtime'}*60*60 < time()){
# need to clear log
$write_logtime = 1;
unlink($config{'logfile'});
}
}
else { $write_logtime = 1; }
if ($write_logtime) {
open(LOGTIME, ">$config{'logfile'}.time");
print LOGTIME time(),"\n";
close(LOGTIME);
}
}
# Initialize SSL for this connection
if ($use_ssl) {
$ssl_con = Net::SSLeay::new($ssl_ctx);
Net::SSLeay::set_fd($ssl_con, fileno(SOCK));
#Net::SSLeay::use_RSAPrivateKey_file(
# $ssl_con, $config{'keyfile'},
# &Net::SSLeay::FILETYPE_PEM);
#Net::SSLeay::use_certificate_file(
# $ssl_con, $config{'keyfile'},
# &Net::SSLeay::FILETYPE_PEM);
Net::SSLeay::accept($ssl_con) || exit;
}
# Work out the hostname for this web server
if (!$config{'host'}) {
($myport, $myaddr) =
unpack_sockaddr_in(getsockname(SOCK));
$myname = gethostbyaddr($myaddr, AF_INET);
if ($myname eq "") {
$myname = inet_ntoa($myaddr);
}
$host = $myname;
}
else { $host = $config{'host'}; }
$port = $config{'port'};
while(&handle_request(getpeername(SOCK), getsockname(SOCK))) { }
close(SOCK);
exit;
}
# Open main socket
$proto = getprotobyname('tcp');
socket(MAIN, PF_INET, SOCK_STREAM, $proto) ||
die "Failed to open main socket : $!";
setsockopt(MAIN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
$baddr = $config{"bind"} ? inet_aton($config{"bind"}) : INADDR_ANY;
for($i=0; $i<5; $i++) {
last if (bind(MAIN, sockaddr_in($config{port}, $baddr)));
sleep(1);
}
die "Failed to bind port $config{port} : $!" if ($i == 5);
listen(MAIN, SOMAXCONN);
if ($config{'listen'}) {
# Open the socket that allows other miniserv servers to find this one
$proto = getprotobyname('udp');
if (socket(LISTEN, PF_INET, SOCK_DGRAM, $proto)) {
setsockopt(LISTEN, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));
bind(LISTEN, sockaddr_in($config{'listen'}, INADDR_ANY));
listen(LISTEN, SOMAXCONN);
}
else {
print STDERR "Failed to open listening socket : $!\n";
$config{'listen'} = 0;
}
}
# Split from the controlling terminal
if (fork()) { exit; }
setsid();
# write out the PID file
open(PIDFILE, "> $config{'pidfile'}");
printf PIDFILE "%d\n", getpid();
close(PIDFILE);
# Start the log-clearing process, if needed. This checks every minute
# to see if the log has passed its reset time, and if so clears it
if ($config{'logclear'}) {
if (!($logclearer = fork())) {
while(1) {
local $write_logtime = 0;
local @st = stat("$config{'logfile'}.time");
if (@st) {
if ($st[9]+$config{'logtime'}*60*60 < time()){
# need to clear log
$write_logtime = 1;
unlink($config{'logfile'});
}
}
else { $write_logtime = 1; }
if ($write_logtime) {
open(LOGTIME, ">$config{'logfile'}.time");
print LOGTIME time(),"\n";
close(LOGTIME);
}
sleep(5*60);
}
exit;
}
push(@childpids, $logclearer);
}
# Setup the logout time dbm if needed
if ($config{'session'}) {
eval "use SDBM_File";
dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
eval { $sessiondb{'1111111111'} = 'foo bar' };
if ($@) {
dbmclose(%sessiondb);
eval "use NDBM_File";
dbmopen(%sessiondb, $config{'sessiondb'}, 0700);
}
}
# Run the main loop
$SIG{'HUP'} = 'miniserv::trigger_restart';
$SIG{'TERM'} = 'miniserv::term_handler';
$SIG{'PIPE'} = 'IGNORE';
@deny = &to_ipaddress(split(/\s+/, $config{"deny"}));
@allow = &to_ipaddress(split(/\s+/, $config{"allow"}));
$p = 0;
while(1) {
# wait for a new connection, or a message from a child process
undef($rmask);
vec($rmask, fileno(MAIN), 1) = 1;
if ($config{'passdelay'} || $config{'session'}) {
for($i=0; $i<@passin; $i++) {
vec($rmask, fileno($passin[$i]), 1) = 1;
}
}
vec($rmask, fileno(LISTEN), 1) = 1 if ($config{'listen'});
local $sel = select($rmask, undef, undef, 10);
if ($need_restart) { &restart_miniserv(); }
local $time_now = time();
# Clean up finished processes
local($pid);
do { $pid = waitpid(-1, WNOHANG);
@childpids = grep { $_ != $pid } @childpids;
} while($pid > 0);
# run the unblocking procedure to check if enough time has passed to
# unblock hosts that heve been blocked because of password failures
if ($config{'blockhost_failures'}) {
$i = 0;
while ($i <= $#deny) {
if ($blockhosttime{$deny[$i]} && $config{'blockhost_time'} != 0 &&
($time_now - $blockhosttime{$deny[$i]}) >= $config{'blockhost_time'}) {
# the host can be unblocked now
$hostfail{$deny[$i]} = 0;
splice(@deny, $i, 1);
}
$i++;
}
}
if ($config{'session'}) {
# Remove sessions with more than 7 days of inactivity
foreach $s (keys %sessiondb) {
local ($user, $ltime) = split(/\s+/, $sessiondb{$s});
if ($time_now - $ltime > 7*24*60*60) {
delete($sessiondb{$s});
}
}
}
next if ($sel <= 0);
if (vec($rmask, fileno(MAIN), 1)) {
# got new connection
$acptaddr = accept(SOCK, MAIN);
if (!$acptaddr) { next; }
# create pipes
if ($config{'passdelay'} || $config{'session'}) {
$PASSINr = "PASSINr$p"; $PASSINw = "PASSINw$p";
$PASSOUTr = "PASSOUTr$p"; $PASSOUTw = "PASSOUTw$p";
$p++;
pipe($PASSINr, $PASSINw);
pipe($PASSOUTr, $PASSOUTw);
select($PASSINw); $| = 1; select($PASSINr); $| = 1;
select($PASSOUTw); $| = 1; select($PASSOUTw); $| = 1;
}
select(STDOUT);
# Check username of connecting user
local ($peerp, $peera) = unpack_sockaddr_in($acptaddr);
$localauth_user = undef;
if ($config{'localauth'} && inet_ntoa($peera) eq "127.0.0.1") {
if (open(TCP, "/proc/net/tcp")) {
# Get the info direct from the kernel
while(<TCP>) {
s/^\s+//;
local @t = split(/[\s:]+/, $_);
if ($t[1] eq '0100007F' &&
$t[2] eq sprintf("%4.4X", $peerp)) {
$localauth_user = getpwuid($t[11]);
last;
}
}
close(TCP);
}
else {
# Call lsof for the info
local $lsofpid = open(LSOF,
"$config{'localauth'} -i TCP\@127.0.0.1:$peerp |");
while(<LSOF>) {
if (/^(\S+)\s+(\d+)\s+(\S+)/ &&
$2 != $$ && $2 != $lsofpid) {
$localauth_user = $3;
}
}
close(LSOF);
}
}
# fork the subprocess
if (!($handpid = fork())) {
# setup signal handlers
$SIG{'TERM'} = 'DEFAULT';
$SIG{'PIPE'} = 'DEFAULT';
#$SIG{'CHLD'} = 'IGNORE';
$SIG{'HUP'} = 'IGNORE';
# Initialize SSL for this connection
if ($use_ssl) {
$ssl_con = Net::SSLeay::new($ssl_ctx);
Net::SSLeay::set_fd($ssl_con, fileno(SOCK));
#Net::SSLeay::use_RSAPrivateKey_file(
# $ssl_con, $config{'keyfile'},
# &Net::SSLeay::FILETYPE_PEM);
#Net::SSLeay::use_certificate_file(
# $ssl_con, $config{'keyfile'},
# &Net::SSLeay::FILETYPE_PEM);
Net::SSLeay::accept($ssl_con) || exit;
}
# close useless pipes
if ($config{'passdelay'} || $config{'session'}) {
foreach $p (@passin) { close($p); }
foreach $p (@passout) { close($p); }
close($PASSINr); close($PASSOUTw);
}
close(MAIN);
# Work out the hostname for this web server
if (!$config{'host'}) {
($myport, $myaddr) =
unpack_sockaddr_in(getsockname(SOCK));
$myname = gethostbyaddr($myaddr, AF_INET);
if ($myname eq "") {
$myname = inet_ntoa($myaddr);
}
$host = $myname;
}
else { $host = $config{'host'}; }
$port = $config{'port'};
local $switched = 0;
if ($config{'remoteuser'} && $localauth_user && !$<) {
# Switch to the UID of the remote user
local @u = getpwnam($localauth_user);
if (@u) {
$( = $u[3]; $) = "$u[3] $u[3]";
$< = $> = $u[2];
$switched = 1;
}
}
if ($config{'switchuser'} && !$< && !$switched) {
# Switch to the UID of server user
local @u = getpwnam($config{'switchuser'});
if (@u) {
$( = $u[3]; $) = "$u[3] $u[3]";
$< = $> = $u[2];
}
}
while(&handle_request($acptaddr, getsockname(SOCK))) { }
shutdown(SOCK, 1);
close(SOCK);
close($PASSINw); close($PASSOUTw);
exit;
}
push(@childpids, $handpid);
if ($config{'passdelay'} || $config{'session'}) {
close($PASSINw); close($PASSOUTr);
push(@passin, $PASSINr); push(@passout, $PASSOUTw);
}
close(SOCK);
}
if ($config{'listen'} && vec($rmask, fileno(LISTEN), 1)) {
# Got UDP packet from another miniserv server
local $rcvbuf;
local $from = recv(LISTEN, $rcvbuf, 1024, 0);
next if (!$from);
local $fromip = inet_ntoa((unpack_sockaddr_in($from))[1]);
local $toip = inet_ntoa((unpack_sockaddr_in(
getsockname(LISTEN)))[1]);
if ((!@deny || !&ip_match($fromip, $toip, @deny)) &&
(!@allow || &ip_match($fromip, $toip, @allow))) {
send(LISTEN, "$config{'host'}:$config{'port'}:".
"$use_ssl", 0, $from);
}
}
# check for password-timeout messages from subprocesses
for($i=0; $i<@passin; $i++) {
if (vec($rmask, fileno($passin[$i]), 1)) {
# this sub-process is asking about a password
$infd = $passin[$i]; $outfd = $passout[$i];
$inline = <$infd>;
if ($inline =~ /^delay\s+(\S+)\s+(\S+)\s+(\d+)/) {
# Got a delay request from a subprocess.. for
# valid logins, there is no delay (to prevent
# denial of service attacks), but for invalid
# logins the delay increases with each failed
# attempt.
if ($3) {
# login OK.. no delay
print $outfd "0 0\n";
$hostfail{$2} = 0;
}
else {
# login failed..
$hostfail{$2}++;
# add the host to the block list if necessary
if ($config{'blockhost_failures'} &&
$hostfail{$2} >= $config{'blockhost_failures'}) {
push(@deny, $2);
$blockhosttime{$2} = $time_now;
$blocked = 1;
if ($use_syslog) {
local $logtext = "Security alert: Host $2 ".
"blocked after $config{'blockhost_failures'} ".
"failed logins for user $1";
syslog("crit", $logtext);
}
}