Доброго времени суток!
Уже около недели ищу информацию, касающуюся обновления полюбившегося Линукса. Времени прошло много, много воды утекло - устаревают версии лавинообразно... Поэтому решил поступить так: установлю дистр более модерновый - в нём версии по-новее. Решение несколько кардинальное, но имеет и свои жирные плюсы. Сразу и оптом решу на какое-то время возникшие проблемы. Достойный и современный дистрибутив уже выбрал, теперь вот безуспешно продолжаю думать о том, как же сделать так, чтоб всё, что содержится в логическом разделе /home плавно перекочевало под нового протектора. Да, именно в логическом:
[antony@jvek ~]$ df -h
Файловая система Разм Исп Дост Исп% смонтирована на
/dev/hda5 4,9G 3,2G 1,5G 69% /
/dev/hda3 16M 6,9M 7,6M 48% /boot
/dev/hda6 31G 26G 3,1G 90% /home
Там у меня, насколько внимательно я это дело изучал много полезного: папки мною любимой Opera, Evolution, Gaim... И прочее прочее... Ещё хочу, чтоб это всё впоследствии работало, как ни в чём не бывало!!!
Заранее признателен за конкретные дельные предложения. Может кто уже поступал подобным образом???
java script:emoticon(':tongue:', 'smid_16')
Пытаюсь перейти from RHEL4 to FC6! (Как по умному перенести наработанную информацию?)
Модератор: Bizdelnick
-
arkhnchul
- Сообщения: 2284
- Статус: Толчковый инженер
- ОС: Debian, Fedora
Re: Пытаюсь перейти from RHEL4 to FC6!
сначала при установке FC home никуда не монтируешь. Потом создаешь юзверей с теми же именами, какие были, и монтируешь.
Или: переименовываем папки юзверей, скажем, из user_name в user_name_tmp, ставим все, создаем юзеров, потом переименовывваем обратно.
Или: гуглим про акаунты и конфиги списка юзеров и групп, долго думаем, в конце концов вообще юзеров не создаем/не изменяем, только копируем оные конфиги туда-сюда.
ЗЫ: во втором пункте когда он спросит, форматировать ли раздел, на который смонтирован home - не надо этого делать))
Или: переименовываем папки юзверей, скажем, из user_name в user_name_tmp, ставим все, создаем юзеров, потом переименовывваем обратно.
Или: гуглим про акаунты и конфиги списка юзеров и групп, долго думаем, в конце концов вообще юзеров не создаем/не изменяем, только копируем оные конфиги туда-сюда.
ЗЫ: во втором пункте когда он спросит, форматировать ли раздел, на который смонтирован home - не надо этого делать))
Losing is fun!
-
Antony
- Сообщения: 22
- ОС: Edgy Eft
Re: Пытаюсь перейти from RHEL4 to FC6!
При помощи Acronis Disc Director выделил для выбранного дистра место на жёстком диске:
[root@jvek ~]# df
Файловая система 1K-блоков Исп Доступно Исп% смонтирована на
/dev/hda4 4646972 3336564 1078060 76% /
/dev/hda5 42655724 26931036 13555108 67% /home
Причем, для swap я выделил всего 200Мб в конце диска. Потому, что чаще всего, судя по сообщениям системы:
total used free shared buffers cached
Mem: 515232 482176 33056 0 29196 254980
-/+ buffers/cache: 198000 317232
Swap: 208804 0 208804
Несмотря на то, что /home я увеличивал в размерах в обе стороны, после того, как отказался (но как-то не очень явно: повиновался воле установщика) от форматирования разделов (это я сделал предварительно) всё прошло гладко, как никогда. Информация осталась доступна вплоть до бита! Единственное, что не очень хорошо - не удалось мне таки методом подстановки имени юзера пользоваться ей, как своей собственной: не пускает система на такую наглость. Поэтому в ближайшем будущем планирую вырезать и вставить во вновь созданные каталоги пользователей. Из-за специфики устройства VPN возникли очередные проблемы с подключением к Инету, хотя локальные подключения пошли прямо из коробки. Потратил несколько дней на установку и настройку pptpconfig, в итоге остановился на версии pptpconfig-20060410-1.fc5.noarch.rpm, (пробовал ещё и 20060821 - не работал!) НО! Никак не могу пустить столь нужную прогу не от root! Причем GUI нормально поднимается, но при попытке запуска соединения выскакивает ошибка.
sh: pptp: command not found
couldn't get channel number: Input/Output error
pptpconfig: pppd process terminated by signal 1 (failed)
pptpconfig: SIGNUP
Очевидно, что надо править этот pptpconfig-20060410-1.fc5.noarch.rpm, написан он, как мне подсказывает интуиция, на PHP, пробовал я там вместо pptp ставить /usr/sbin/pptp - тогда отказыватеся работать вообще!
Что можно предпринять-то? Сидеть под root несерьёзно!
[root@jvek ~]# df
Файловая система 1K-блоков Исп Доступно Исп% смонтирована на
/dev/hda4 4646972 3336564 1078060 76% /
/dev/hda5 42655724 26931036 13555108 67% /home
Причем, для swap я выделил всего 200Мб в конце диска. Потому, что чаще всего, судя по сообщениям системы:
total used free shared buffers cached
Mem: 515232 482176 33056 0 29196 254980
-/+ buffers/cache: 198000 317232
Swap: 208804 0 208804
Несмотря на то, что /home я увеличивал в размерах в обе стороны, после того, как отказался (но как-то не очень явно: повиновался воле установщика) от форматирования разделов (это я сделал предварительно) всё прошло гладко, как никогда. Информация осталась доступна вплоть до бита! Единственное, что не очень хорошо - не удалось мне таки методом подстановки имени юзера пользоваться ей, как своей собственной: не пускает система на такую наглость. Поэтому в ближайшем будущем планирую вырезать и вставить во вновь созданные каталоги пользователей. Из-за специфики устройства VPN возникли очередные проблемы с подключением к Инету, хотя локальные подключения пошли прямо из коробки. Потратил несколько дней на установку и настройку pptpconfig, в итоге остановился на версии pptpconfig-20060410-1.fc5.noarch.rpm, (пробовал ещё и 20060821 - не работал!) НО! Никак не могу пустить столь нужную прогу не от root! Причем GUI нормально поднимается, но при попытке запуска соединения выскакивает ошибка.
sh: pptp: command not found
couldn't get channel number: Input/Output error
pptpconfig: pppd process terminated by signal 1 (failed)
pptpconfig: SIGNUP
Очевидно, что надо править этот pptpconfig-20060410-1.fc5.noarch.rpm, написан он, как мне подсказывает интуиция, на PHP, пробовал я там вместо pptp ставить /usr/sbin/pptp - тогда отказыватеся работать вообще!
Что можно предпринять-то? Сидеть под root несерьёзно!
-
Juliette
- Сообщения: 5058
- Статус: ROSA Lab
- ОС: Ubuntu LTS, Mandriva 2011
Re: Пытаюсь перейти from RHEL4 to FC6!
ну вы же под рутом не полностью, вы только тырнет из-под рута запускаете
иметь секс с правами доступа или с sudo - оно вам надо? а рут умный и все важные вещи под него настроены, зачем перекраивать? Запускайте тырнет из-под рута, всё остальное делайте из-под юзера. 
-
Antony
- Сообщения: 22
- ОС: Edgy Eft
Re: Пытаюсь перейти from RHEL4 to FC6!
Хорошо-то оно хорошо, но! В книгах по безопасности такие манёвры с распространением налево и направо пароля root не рекомендуются. Да и здравый смысл подсказывает, что надо ограничивать права пользователей. А то они такого могут натворить от нечем себя занять
Да, действительно работает и по этой, небезопасной схеме, но в RHEL я всё это делал более безопасно! Пароль суперпользователя знал только суперпользователь. Хочется и в FC6 добиться того же!
Вот только как это можно сделать? 
Да, действительно работает и по этой, небезопасной схеме, но в RHEL я всё это делал более безопасно! Пароль суперпользователя знал только суперпользователь. Хочется и в FC6 добиться того же!
-
Juliette
- Сообщения: 5058
- Статус: ROSA Lab
- ОС: Ubuntu LTS, Mandriva 2011
Re: Пытаюсь перейти from RHEL4 to FC6!
но всё-таки вы не забывайте, что и рут и пользователь - это вы один, любимый
себе-то вы доверяете? а то так и до раздвоения личности недалеко...
...или это я чего-то не догоняю...
...или это я чего-то не догоняю...
-
fed71
- Сообщения: 2480
- ОС: Ubuntu
Re: Пытаюсь перейти from RHEL4 to FC6!
Юзер не идет потому что сменился дескриптор пользователя (попросту описание) - имя то же, а дескриптор другой
Так может все-таки проще будет сохранить куда- нибудь свои данные и наработки и потратить полчаса на установку новой оси и потом еще чуть на настройку?
Я не знаю кто я. Не помню ни серии своей, ни инвентарного номера...
Мой блог http://fed71.livejournal.com
Мой блог http://fed71.livejournal.com
-
Ali1
- Сообщения: 2250
-
Antony
- Сообщения: 22
- ОС: Edgy Eft
Re: Пытаюсь перейти from RHEL4 to FC6!
Не стал я углубляться в эти дебри. Потенциально возможно всё, но на практике я принёс в жертву около 200 Мб Opera cash, что в общем-то не так уже и ценно. Создав в новой системе нового пользователя банально вставил в его домашнюю папку нужную информацию из папки, оставшейся от RH. Поэтому считаю свой опыт удавшимся. Как обычно - не так, как хотелось бы в идеале, но лучшее - враг хорошего.
А вот с поднятием pptpconfig от пользователя обстановка та же, напряжённая. Для ускорения и упрощения конфигурирования скрипта помещаю пациента для всеобщего обозрения:
А вот с поднятием pptpconfig от пользователя обстановка та же, напряжённая. Для ускорения и упрощения конфигурирования скрипта помещаю пациента для всеобщего обозрения:
Код:
#!/bin/php4-pcntl -q
<?php
#
# $Id: pptpconfig.php,v 1.8 2006/04/06 06:22:26 quozl Exp $
#
# pptpconfig.php, PPTP configuration and management GUI
# Copyright © 2002-2004 James Cameron (quozl@us.netrek.org)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# our program name
$me = 'pptpconfig';
$id = "
# $Id: pptpconfig.php,v 1.8 2006/04/06 06:22:26 quozl Exp $
";
# load the php-gtk functions
dl("php_gtk.so");
# paths and files
# root path, change to ./ for non-root testing
if (!defined('PATH_ROOT'))
define('PATH_ROOT', '/');
# where pppd places linkname pid files
if (!defined('PATH_RUN'))
define('PATH_RUN', PATH_ROOT.'var/run/');
# our program's configuration file directory
if (!defined('PATH_OURS'))
define('PATH_OURS', PATH_ROOT.'etc/'.$me.'/');
# our program's XML file directory
if (!defined('PATH_LIB'))
define('PATH_LIB', PATH_ROOT.'usr/share/'.$me.'/');
# silently try to create our configuration file directory
if (!is_dir(PATH_OURS)) {
@mkdir(PATH_OURS, 0750);
}
# directory in which data is to be put
if (!defined('FILE_TUNNELS'))
define('FILE_TUNNELS', PATH_OURS.'tunnels');
# file for locking access to tunnels file
if (!defined('FILE_LOCK'))
define('FILE_LOCK', PATH_OURS.'lock');
# file to use for new file before renaming to FILE_TUNNELS
if (!defined('FILE_NEW'))
define('FILE_NEW', PATH_OURS.'new');
# place where pppd keeps stuff
if (!defined('PATH_PPP'))
define('PATH_PPP', PATH_ROOT.'etc/ppp/');
if (!defined('PATH_PEERS'))
define('PATH_PEERS', PATH_PPP.'peers/');
if (!defined('FILE_CHAP_SECRETS'))
define('FILE_CHAP_SECRETS', PATH_PPP.'chap-secrets');
if (!defined('FILE_CHAP_SECRETS'))
define('FILE_CHAP_SECRETS', PATH_PPP.'pap-secrets');
# signal handler
function null($signo) {
}
# catch SIGINT ourselves, otherwise when we kill() pppd we get it too
# note: php must have been configured with "configure --enable-pcntl"
if (!defined('SIGINT')) {
echo "pptpconfig: this PHP is not built with configure --enable-pcntl\n";
echo "pptpconfig: stopping a tunnel may result in application exit\n";
# also dies in pcntl_wifexited() call on tunnel start
} else {
pcntl_signal(SIGINT, 'null');
}
# define text highlight colours
$colours['no'] = &new GdkColor(0, 0, 0);
$colours['me'] = &new GdkColor(32768, 0, 32768);
$colours['tx'] = &new GdkColor(0, 32768, 32768);
$colours['rx'] = &new GdkColor(32768, 32768, 0);
$colours['uh'] = &new GdkColor(32768, 0, 0);
$colours['ok'] = &new GdkColor(0, 32768, 0);
$colours['red'] = &new GdkColor(65535, 32768, 32768);
$colours['green'] = &new GdkColor(32768, 65535, 32768);
$colours['blue'] = &new GdkColor(32768, 32768, 65535);
$colours['red-selected'] = &new GdkColor(0x9c9c, 0, 0);
$colours['green-selected'] = &new GdkColor(0, 0x7070, 0);
$colours['blue-selected'] = &new GdkColor(0, 0, 0x9c9c);
# point at the glade file containing the widget tree
$xml = $me.'.xml';
if (!@is_readable($xml)) $xml = PATH_LIB.$me.'.xml';
# open the main window
on_main_setup_activate(0);
# load the tunnels file
tunnels_load();
# for each tunnel loaded, put on screen, set state, and autostart
if (count($tunnels) > 0) {
foreach ($tunnels as $tunnel) {
# add to the list on screen
setup_list_insert($tunnel);
# set the current running/stopped state
$name = $tunnel['name'];
setup_list_set_state($name, pid_state($name));
# if an autostart is requested, start it now
if ($tunnel['autostart']) {
start($name);
}
}
}
# execute the GTK+ main loop
Gtk::main();
# version number we are
function id() {
global $me, $id;
list(, , , $revision, $date, $time) = explode(' ', trim($id));
return $me.' '.$revision.' '.$date.' '.$time;
}
# utility functions, instantiate a window from widget tree
function open_window($name) {
global $xml;
$gx = &new GladeXML($xml, $name);
$gx->signal_autoconnect();
return $gx;
}
# utility functions, hide a window
function hide_window($widget) {
$window = $widget->get_toplevel();
$window->hide();
}
# utility functions, kill a window
function kill_window($widget) {
$window = $widget->get_toplevel();
$window->destroy();
}
# utility functions, shutdown the program
function shutdown() {
Gtk::main_quit();
}
# mark widget insensitive, non-responsive
function insensitive($gx, $name) {
$widget = $gx->get_widget($name);
return $widget->set_sensitive(0);
}
# mark widget sensitive, responsive
function sensitive($gx, $name) {
$widget = $gx->get_widget($name);
return $widget->set_sensitive(1);
}
# widget to grab default
function has_default_on($gx, $name) {
$widget = $gx->get_widget($name);
return $widget->grab_default();
}
function has_default_off($gx, $name) {
$widget = $gx->get_widget($name);
# no apparent way to do this ;-(
}
# encode a tunnel name to filesystem and shell name
function munge($name) {
return rawurlencode($name);
}
# functions for status bar on main window
function bar_initialise($name, $widget) {
global $bars;
$bars[$name]['widget'] = $widget;
$bars[$name]['id'] = $widget->get_context_id('text');
}
function bar_show($name, $text) {
global $bars;
if (!isset($bars[$name])) return;
$bars[$name]['widget']->pop($bars[$name]['id']);
$bars[$name]['widget']->push($bars[$name]['id'], $text);
}
# tunnels database management
function tunnels_save() {
global $tunnels;
# obtain interlock
if (!($lock = fopen(FILE_LOCK, 'a+'))) {
message('tunnels save lock open fail', 'Failed to open '.FILE_LOCK.'
information entered has not been saved.');
return 0;
}
if (!flock($lock, 2)) {
message('tunnels save lock fail', 'Failed to lock '.FILE_LOCK.'
information entered has not been saved.');
fclose($lock);
return 0;
}
# open the file
if (!($fp = fopen(FILE_NEW, 'w'))) {
message('tunnels save open fail', 'Failed to open '.FILE_NEW.'
information entered has not been saved.');
fclose($lock);
return 0;
}
# protect the file against ordinary users (it has passwords)
if (!chmod(FILE_NEW, 0750)) {
message('tunnels save chmod fail', 'Failed to chmod '.FILE_NEW.'
all tunnel information entered has been lost.');
fclose($lock);
fclose($fp);
unlink(FILE_NEW);
return 0;
}
# write the array to the file
if (!fwrite($fp,serialize($tunnels))) {
message('tunnels save write fail', 'Failed to write to '.FILE_NEW."
after opening it for write
information entered has not been saved.");
fclose($fp);
fclose($lock);
return 0;
}
# close the file
if (!fclose($fp)) {
message('tunnels save close fail', 'Failed to close '.FILE_NEW."
after writing to it
information entered may not have been saved.");
fclose($lock);
return 0;
}
# rename the new file into place
if (!rename(FILE_NEW, FILE_TUNNELS)) {
message('tunnels save move fail', 'Failed to move '.FILE_NEW.' into place as '.FILE_TUNNELS."
changes have been lost");
fclose($lock);
return 0;
}
# release the lock and return success
fclose($lock);
return 1;
}
function tunnels_load() {
global $tunnels;
# if no file is there, no worries
if (!@is_file(FILE_TUNNELS)) {
return 1;
}
# if the file is there but is not readable, give an error
if (!@is_readable(FILE_TUNNELS)) {
message('tunnels load not readable', FILE_TUNNELS.' is not readable.
this program is designed to be run as root');
return 0;
}
# open the file
if (!($fp = fopen(FILE_TUNNELS, 'r'))) {
message('tunnels load open fail', FILE_TUNNELS.' could not be opened');
return 0;
}
# read the file
$tunnels = unserialize(fread($fp, filesize(FILE_TUNNELS)));
# close the file
fclose($fp);
return 1;
}
# create files from tunnel definition
function files_save_peers($tunnel) {
global $me;
# peers file, add file per tunnel
$file = PATH_PEERS.munge($tunnel['name']);
if (!$fp=fopen($file, 'w')) {
message('peers save open fail', 'failed to create peers file '.$file);
return 0;
}
$x = '';
$x .= "# tunnel ".$tunnel['name'].", written by $me \$Revision: 1.8 $\n\n";
$x .= "# name of tunnel, used to select lines in secrets files\n";
$x .= "remotename ".munge($tunnel['name'])."\n\n";
$x .= "# name of tunnel, used to name /var/run pid file\n";
$x .= "linkname ".munge($tunnel['name'])."\n\n";
$x .= "# name of tunnel, passed to ip-up scripts\n";
$x .= "ipparam ".munge($tunnel['name'])."\n\n";
$x .= "# data stream for pppd to use\n";
$x .= "pty \"pptp ".$tunnel['server'].
" --nolaunchpppd ".$tunnel['pptp-options']."\"\n\n";
$x .= "# domain and username, used to select lines in secrets files\n";
if ($tunnel['domain'] != '') {
$x .= "name ".$tunnel['domain']."\\\\".$tunnel['username']."\n\n";
} else {
$x .= "name ".$tunnel['username']."\n\n";
}
if ($tunnel['usepeerdns']) { $x .= "usepeerdns\n"; }
if ($tunnel['require-mppe']) { $x .= "require-mppe\n"; }
if ($tunnel['nomppe-40']) { $x .= "nomppe-40\n"; }
if ($tunnel['nomppe-128']) { $x .= "nomppe-128\n"; }
if ($tunnel['mppe-stateful']) { $x .= "mppe-stateful\n"; }
if ($tunnel['refuse-eap']) { $x .= "refuse-eap\n"; }
if ($tunnel['persist']) { $x .= "persist\n"; }
if ($tunnel['debug']) { $x .= "debug dump\n"; }
$x .= "\n# do not require the server to authenticate to our client\n";
$x .= "noauth\n\n";
if (@is_readable('/etc/ppp/options.pptp')) {
$x .= "# adopt defaults from the pptp-linux package\n";
$x .= "file /etc/ppp/options.pptp\n\n";
}
if ($tunnel['pppd-options'] != '') {
$x .= "# user specified pppd options\n".$tunnel['pppd-options']."\n\n";
}
$x .= "# end of tunnel file\n";
if (!@fputs($fp, $x)) {
message('peers save write fail', 'Failed to write to peers file '.$file."
data has been lost, tunnel may not function.");
return 0;
}
if (!@fclose($fp)) {
message('peers save close fail', 'Failed to close peers file '.$file."
data may have been lost, tunnel may not function.");
return 0;
}
return 1;
}
function tunnel_to_secret($tunnel) {
global $me;
$head = '# +++ '.$me.' added for tunnel '.$tunnel['name'];
$tail = '# --- '.$me.' added for tunnel '.$tunnel['name'];
if ($tunnel['domain'] == '') {
$body = $tunnel['username']." ".
munge($tunnel['name'])." ".$tunnel['password']." *";
} else {
$body = $tunnel['domain']."\\\\".$tunnel['username']." ".
munge($tunnel['name'])." ".$tunnel['password']." *";
}
return "\n".$head."\n".$body."\n".$tail."\n";
}
# remove a secret from a secrets file
function secret_elide($tunnel, $text) {
global $me;
$pattern = "# \+\+\+ ".ereg_replace("-", "\-", $me)." added for tunnel ".$tunnel['name'].
"\n\S*\s\S*\s\S*\s\S*\n".
"# \-\-\- ".ereg_replace("-", "\-", $me)." added for tunnel ".$tunnel['name']."\n";
$new = preg_replace("/$pattern\n/","",$text);
$new = preg_replace("/$pattern/","",$new);
return $new;
}
function files_save_secrets_name($file) {
return PATH_PPP.$file;
}
function secrets_load($file) {
$name = files_save_secrets_name($file);
if (@is_dir($name)) {
message('secrets load not directory', "Unable to open secrets file for read
$name is unexpectedly a directory.");
return 0;
}
if (@is_link($name)) {
message('secrets load not file', "Unable to open secrets file for read
$name is unexpectedly a link.");
return 0;
}
# if no file is there, no worries
if (@is_file($name)) {
# if the file is there but is not readable, give an error
if (!@is_readable($name)) {
message('secrets load not readable', "Unable to open secrets file for read
$name is not readable
Are you running as root?");
return 0;
}
# open the file
if (!($fp = fopen($name, 'r'))) {
message('secrets load open fail', "Unable to open secrets file for read
$name");
return 0;
}
# read the file
$text = fread($fp, filesize($name));
# close the file
fclose($fp);
} else {
# file not there, initialise text
$text = "# Secrets for authentication
# client server secret IP addresses
";
}
return $text;
}
function secrets_save($file, $text) {
$name = files_save_secrets_name($file);
if (!($fp = fopen($name, 'w'))) {
message('secrets save open fail',
"Unable to open secrets file for write
$name");
return 0;
}
if (!fwrite($fp, $text)) {
message('secrets save write fail', "Unable to write to secrets file after opening it.
$name
Warning: you have lost the contents of that file,
which may have included passwords for
dial-up connections or incoming tunnels");
fclose($fp);
return 0;
}
if (!fclose($fp)) {
message('secrets save close fail', "Unable to close secrets file after writing to it.
$name
Warning: you may have lost the contents of that file,
which may have included passwords for
dial-up connections or incoming tunnels");
return 0;
}
return 1;
}
function files_save_secrets($tunnel, $file) {
$text = secrets_load($file);
if ($text === 0) return 0;
$text = secret_elide($tunnel, $text);
$text .= tunnel_to_secret($tunnel);
return secrets_save($file, $text);
}
function files_save($tunnel) {
if (!files_save_peers($tunnel)) return 0;
if (!files_save_secrets($tunnel, "chap-secrets")) return 0;
if (!files_save_secrets($tunnel, "pap-secrets")) return 0;
return 1;
}
function files_remove_secrets($tunnel, $file) {
$text = secrets_load($file);
if ($text === 0) return 0;
$text = secret_elide($tunnel, $text);
return secrets_save($file, $text);
}
function files_remove($tunnel) {
$name = PATH_PEERS.munge($tunnel['name']);
if (!unlink($name)) {
message('files remove', "Unable to remove peers file for tunnel
$name.");
return 0;
}
if (!files_remove_secrets($tunnel, "chap-secrets")) return 0;
if (!files_remove_secrets($tunnel, "pap-secrets")) return 0;
return 1;
}
function on_main_setup_activate($widget) {
global $gx;
if (!isset($gx['setup'])) {
$gx['setup'] = open_window('pptpconfig-setup');
setup_initialise();
# grab a context id for the status bar
bar_initialise('setup', $gx['setup']->get_widget('statusbar'));
bar_show('setup', 'Welcome to '.id());
# disable buttons that depend on context to be enabled
insensitive($gx['setup'], 'update');
insensitive($gx['setup'], 'delete');
insensitive($gx['setup'], 'start');
insensitive($gx['setup'], 'stop');
# enable column auto sizing
$clist = $gx['setup']->get_widget('tunnels');
$clist->set_column_auto_resize(0, TRUE);
$clist->set_column_auto_resize(1, TRUE);
$clist->set_column_auto_resize(2, TRUE);
$clist->set_column_auto_resize(3, TRUE);
# enable table sort by user, click a column heading to sort
# todo: reimplement. it is currently disabled because row
# numbers are changed by sort, invalidating $rows[] array
# $clist->connect('click_column', 'clist_click_column');
# $clist->set_reorderable(TRUE);
# disable buttons not implemented
# iconify depends on support in GTK+ 1.3 or later
$iconify = $gx['setup']->get_widget('iconify');
$iconify->hide();
}
}
# tunnel table sort by user
function clist_click_column($clist, $column) {
# toggle the sort type on each click
if ($clist->sort_type == GTK_SORT_ASCENDING)
$clist->set_sort_type(GTK_SORT_DESCENDING);
else
$clist->set_sort_type(GTK_SORT_ASCENDING);
# choose sort column and perform sort
$clist->set_sort_column($column);
$clist->sort();
# todo: rebuild $rows[]
}
# window pptpconfig-setup
function setup_initialise() {
global $setup;
$setup =
array(
# text entry fields setup notebook
'texts' => array('name', 'server', 'domain', 'username',
'password', 'pppd-options', 'pptp-options',
'resolv', 'dns-options'),
# radio buttons on setup notebook
'radios' => array('routing' => array('routing_interface_only',
'routing_client_to_lan',
'routing_all_to_tunnel',
'routing_lan_to_lan')),
# checkboxes on setup notebook
'checks' => array('usepeerdns', 'require-mppe',
'nomppe-40', 'nomppe-128', 'refuse-eap',
'mppe-stateful', 'autostart', 'iconify',
'persist', 'debug'),
# referenced subwindows, named data on main window
'refs' => array('client-to-lan')
);
}
function setup_get_text($name) {
global $gx;
$widget = $gx['setup']->get_widget($name);
return $widget->get_text();
}
function setup_get_button($name) {
global $gx;
$widget = $gx['setup']->get_widget($name);
return $widget->get_active();
}
# read data from the setup widgets and return a tunnel array
function setup_get() {
global $setup, $gx;
$texts = $setup['texts'];
foreach ($texts as $name) $tunnel[$name] = setup_get_text($name);
$radios = $setup['radios'];
foreach ($radios as $key => $buttons) {
foreach ($buttons as $name) {
if (setup_get_button($name))
$tunnel[$key] = $name;
}
}
$buttons = $setup['checks'];
foreach ($buttons as $name) {
$tunnel[$name] = setup_get_button($name);
}
$window = $gx['setup']->get_widget('pptpconfig-setup');
$refs = $setup['refs'];
foreach ($refs as $name) $tunnel[$name] = $window->get_data($name);
return $tunnel;
}
function setup_set_text($name, $value) {
global $gx;
$widget = $gx['setup']->get_widget($name);
return $widget->set_text($value);
}
function setup_set_button($name, $value) {
global $gx;
$widget = $gx['setup']->get_widget($name);
return $widget->set_active($value);
}
# given a tunnel array, write it to the setup widgets
function setup_set($tunnel) {
global $setup, $gx;
$texts = $setup['texts'];
foreach ($texts as $name) setup_set_text($name, $tunnel[$name]);
$radios = $setup['radios'];
foreach ($radios as $key => $buttons) {
foreach ($buttons as $name) {
if ($tunnel[$key] == $name)
setup_set_button($name, 1);
}
}
$buttons = $setup['checks'];
foreach ($buttons as $name) {
setup_set_button($name, $tunnel[$name]);
}
$window = $gx['setup']->get_widget('pptpconfig-setup');
$refs = $setup['refs'];
foreach ($refs as $name) $window->set_data($name, $tunnel[$name]);
}
function setup_clear_text($name) {
global $gx;
$widget = $gx['setup']->get_widget($name);
return $widget->set_text('');
}
# clear the setup widgets
function setup_clear() {
global $setup, $gx;
$texts = $setup['texts'];
foreach ($texts as $name) setup_clear_text($name);
$radios = $setup['radios'];
foreach ($radios as $key => $buttons) {
foreach ($buttons as $name) {
setup_set_button($name, 0);
}
}
$buttons = $setup['checks'];
foreach ($buttons as $name) {
setup_set_button($name, 0);
}
$window = $gx['setup']->get_widget('pptpconfig-setup');
$refs = $setup['refs'];
foreach ($refs as $name) $window->set_data($name, '');
}
function setup_iconify() {
global $gx;
$window = $gx['setup']->get_widget('pptpconfig-setup');
$window->iconify();
}
function routing($routing) {
$array = array('routing_interface_only' => '(no routing)', 'routing_client_to_lan' => '(client to LAN)', 'routing_all_to_tunnel' => '(all to tunnel)', 'routing_lan_to_lan' => '(LAN to LAN)');
return $array[$routing];
}
# process input from pipe attached to an asynchronous command
function command_async_reader($ignore1, $ignore2, $mine) {
global $me, $gtk_inputs;
$pipe = $mine['pipe'];
$context = $mine['context'];
$line = fgets($pipe, 1024);
if ($line === false) {
gtk::input_remove($gtk_inputs[$pipe]);
$status = pclose($pipe);
if ($status != 0) {
scribe($context, $me.": command failed, exit code $status\n");
}
return FALSE;
}
scribe($context, $line);
return TRUE;
}
# issue a command to a subshell to complete asynchronously
function command_async($context, $command) {
global $gtk_inputs;
scribe($context, $command."\n");
$mine['context'] = $context;
$mine['pipe'] = popen($command.' 2>&1', 'r');
stream_set_blocking($mine['pipe'], false);
$gtk_inputs[$mine['pipe']] = gtk::input_add($mine['pipe'], GDK_INPUT_READ, 'command_async_reader', $mine);
}
function command($context, $command) {
global $me;
scribe($context, $command."\n");
$pipe = popen($command.' 2>&1', 'r');
stream_set_blocking($pipe, true);
while (!feof($pipe)) {
while(Gtk::events_pending()) Gtk::main_iteration();
$text .= fgets($pipe, 2048);
}
$status = pclose($pipe);
if ($status != 0) {
scribe($context, $text."\n");
scribe($context, $me.": command failed, exit code $status\n");
}
return array('status' => $status, 'text' => $text);
}
function resolv_start($context, $interface) {
global $tunnels, $me, $undo;
$name = $context['name'];
$tunnel = $tunnels[$name];
$on = '/etc/resolv.conf';
$sn = '/etc/resolv.conf.orig.'.munge($tunnel['name']);
$fn = '';
if ($tunnel['usepeerdns']) {
$fn = '/var/run/ppp/resolv.conf';
if (!@is_readable($fn)) $fn = '/etc/ppp/resolv.conf';
if (!@is_readable($fn)) {
$fn = '';
scribe($context, $me.": usepeerdns was set, but /{var/run,etc}/ppp/resolv.conf was not readable\n");
}
} else {
if ($tunnel['resolv'] != '') {
$fn = '/etc/resolv.conf.'.munge($tunnel['name']);
$fp = fopen($fn, 'w');
$dnss = split(' ', $tunnel['resolv']);
foreach ($dnss as $dns) {
fwrite($fp, 'nameserver '.$dns."\n");
}
fclose($fp);
}
}
if ($fn != '') {
if ($tunnel['dns-options'] != '') {
$fp = fopen($fn, 'a');
$options = split(';', $tunnel['dns-options']);
foreach ($options as $option) {
fwrite($fp, $option."\n");
}
fclose($fp);
}
$resolvconf = '/sbin/resolvconf';
if (@is_executable($resolvconf)) {
$resolvconf_command = $resolvconf.' -a '.$interface.' < '.$fn;
$array = command($context, $resolvconf_command);
if ($array['status'] != 0) {
scribe($context, $me.": DNS changes were not done, resolvconf failed\n");
} else {
scribe($context, $me.": DNS changes made using resolvconf\n");
$undo[] = '/sbin/resolvconf -d '.$interface;
}
} else {
if (!@rename($on, $sn)) {
scribe($context, $me.": failed to save $on as $sn\n");
scribe($context, $me.": DNS changes were not done\n");
} else {
if (!@rename($fn, $on)) {
scribe($context, $me.": failed to move $fn to $on\n");
scribe($context, $me.": DNS changes were not done\n");
rename($sn, $on);
} else {
scribe($context, $me.": DNS changes made to $on\n");
$undo[] = 'mv '.$sn.' '.$on;
}
}
}
}
}
function iconify_start($context, $window) {
global $tunnels;
$name = $context['name'];
$tunnel = $tunnels[$name];
if ($tunnel['iconify']) {
$window->iconify();
setup_iconify();
}
}
function routing_start($context, $interface) {
global $tunnels, $me, $undo;
$name = $context['name'];
$tunnel = $tunnels[$name];
# add a route to the server via the interface it used to require
$server_ip = $context['ip'];
if ($server_ip != '') {
$command = 'ip route replace '.$context['route'];
$array = command($context, $command);
if ($array['status'] != 0) $ok = 0;
$undo[] = ereg_replace('route replace', 'route del', $command);
}
# if interface only routing is requested, do nothing else
# http://pptpclient.sourceforge.net/routing....lient-to-server
if ($tunnel['routing'] == 'routing_interface_only') return;
$interface = escapeshellarg($interface);
# add routes to each network requested
# http://pptpclient.sourceforge.net/routing....l#client-to-lan
$ok = 1;
$networks = unserialize($tunnel['client-to-lan']);
if (is_array($networks)) foreach ($networks as $network => $name) {
$network = escapeshellarg($network);
$command = 'ip route add '.$network.' dev '.$interface;
$array = command($context, $command);
if ($array['status'] != 0) $ok = 0;
}
if ($ok) scribe($context, $me.": routes added to remote networks\n");
if ($tunnel['routing'] == 'routing_client_to_lan') return;
# perform all to tunnel routing
# http://pptpclient.sourceforge.net/routing....l#all-to-tunnel
if ($tunnel['routing'] == 'routing_all_to_tunnel') {
# obtain current default route
$default = trim(`ip route list | grep default`);
# restore it later
$undo[] = 'ip route replace '.$default;
# replace with default route through the tunnel
$command = 'ip route replace default dev '.$interface;
$array = command($context, $command);
scribe($context, $me.": default route changed to use tunnel\n");
}
# perform lan to lan routing
# http://pptpclient.sourceforge.net/routing.phtml#lan-to-lan
if ($tunnel['routing'] == 'routing_lan_to_lan') {
if (count($networks) > 0)
foreach ($networks as $network => $name) {
$network = $network;
command($context, $command);
$command = 'iptables --insert OUTPUT 1 --source 0.0.0.0/0.0.0.0 --destination '.$network.' --jump ACCEPT --out-interface '.$interface;
command($context, $command);
$command = 'iptables --insert INPUT 1 --source '.$network.' --destination 0.0.0.0/0.0.0.0 --jump ACCEPT --in-interface '.$interface;
command($context, $command);
$command = 'iptables --insert FORWARD 1 --source 0.0.0.0/0.0.0.0 --destination '.$network.' --jump ACCEPT --out-interface '.$interface;
command($context, $command);
$command = 'iptables --insert FORWARD 1 --source '.$network.' --destination 0.0.0.0/0.0.0.0 --jump ACCEPT';
command($context, $command);
} # foreach ($networks as $network => $name)
$command = 'iptables --table nat --append POSTROUTING --out-interface '.$interface.' --jump MASQUERADE';
command($context, $command);
$command = 'iptables --append FORWARD --protocol tcp --tcp-flags SYN,RST SYN --jump TCPMSS --clamp-mss-to-pmtu';
command($context, $command);
} # ($tunnel['routing'] == 'routing_lan_to_lan')
}
function undo_execute($context) {
global $undo, $me;
$undo_success = 1;
scribe($context, $me.": restoring routing and DNS configuration\n");
if (is_array($undo)) foreach ($undo as $number => $command) {
$array = command($context, $command);
unset($undo[$number]);
if ($array['status'] != 0) $undo_success = 0;
}
if ($undo_success) {
scribe($context, $me.": routing and DNS configuration restored\n");
} else {
scribe($context, $me.": routing and DNS configuration partly restored\n");
}
unset($undo);
}
function undo_name($name) {
return PATH_RUN.'pptpconfig.'.$name.'.undo';
}
function undo_save($name) {
global $undo;
# todo: no interlock is attempted here, multiple users of gui may clash
# open the file
$file = undo_name($name);
if (!($fp = fopen($file, 'w'))) {
message('undo save open fail', 'Failed to open '.$file);
return 0;
}
# write the array to the file
if (!fwrite($fp,serialize($undo))) {
message('undo save write fail', 'Failed to write to '.$file."
after opening it for write");
fclose($fp);
return 0;
}
# close the file
if (!fclose($fp)) {
message('undo save close fail', 'Failed to close '.$file."
after writing to it");
return 0;
}
return 1;
}
function undo_load($name) {
global $undo;
$file = undo_name($name);
$undo = array();
# if no file is there, no worries
if (!@is_file($file)) {
message('undo load not there', $file.' is not present,
though it was expected to have been written by this program earlier.');
return 1;
}
# open the file
if (!($fp = fopen($file, 'r'))) {
message('undo load open fail', $file.' could not be opened');
return 0;
}
# read the file
$undo = unserialize(fread($fp, filesize($file)));
# close the file
fclose($fp);
return 1;
}
function undo_remove($name) {
$file = undo_name($name);
if (!unlink($file)) {
message('undo remove', "Unable to remove undo file $file");
return 0;
}
}
function details($tunnel) {
if ($tunnel['domain'] != '') {
$text = $tunnel['username'].'@'.$tunnel['domain'];
} else {
$text = $tunnel['username'];
}
$text .= ' '.routing($tunnel['routing']);
return $text;
}
function setup_list_encode($tunnel) {
global $statii;
$status = $statii[$tunnel['name']];
if ($status == '') $status = 'stopped';
return array($tunnel['name'],
$tunnel['server'],
details($tunnel),
$status);
}
function setup_list_insert($tunnel) {
global $gx, $rows;
$clist = $gx['setup']->get_widget('tunnels');
$row = $clist->append(setup_list_encode($tunnel));
$key = $tunnel['name'];
$rows[$key] = $row;
}
function setup_list_set_state($name, $state) {
global $gx, $colours, $statii, $rows;
if ($statii[$name] == $state) return;
$statii[$name] = $state;
$clist = $gx['setup']->get_widget('tunnels');
$style = $clist->style;
$style = $style->copy();
if ($state == 'stopped') {
$normal = $colours['blue'];
$selected = $colours['blue-selected'];
} else if ($state == 'running') {
$normal = $colours['green'];
$selected = $colours['green-selected'];
} else {
$normal = $colours['red'];
$selected = $colours['red-selected'];
}
$style->base[GTK_STATE_NORMAL] = $normal;
$style->bg[GTK_STATE_SELECTED] = $selected;
$key = $name;
$clist->set_text($rows[$key], 3, $state);
$clist->set_row_style($rows[$key], $style);
}
function setup_list_replace($tunnel, $row) {
global $gx, $rows;
$name = $tunnel['name'];
$clist = $gx['setup']->get_widget('tunnels');
$key = $clist->get_text($row, 0);
unset($rows[$key]);
$key = $name;
$rows[$key] = $row;
$array = setup_list_encode($tunnel);
$column = 0;
foreach ($array as $value) {
$clist->set_text($row, $column++, $value);
}
}
function setup_list_delete($row) {
global $gx;
$clist = $gx['setup']->get_widget('tunnels');
$clist->remove($row);
}
function on_setup_delete_event() {
shutdown();
}
function on_setup_close_clicked($widget) {
shutdown();
}
function notebook_reset() {
global $gx;
$notebook = $gx['setup']->get_widget('notebook');
$notebook->set_page(0);
}
function on_setup_select_row($widget, $row) {
global $gx, $selected, $tunnels;
$selected['row'] = $row;
$selected['name'] = $widget->get_text($row, 0);
if ($selected['name'] == '') {
message('on_setup_select_row inconsistency 1', "You selected a blank entry, but I should not have put one in the list.");
return;
}
if (!isset($tunnels[$selected['name']])) {
message('on_setup_select_row inconsistency 2', "You selected a tunnel but it is not in the internal tunnel array\n");
return;
}
setup_set($tunnels[$selected['name']]);
sensitive($gx['setup'], 'update');
sensitive($gx['setup'], 'delete');
sensitive($gx['setup'], 'start');
sensitive($gx['setup'], 'stop');
has_default_on($gx['setup'], 'start');
bar_show('setup', '');
}
function on_setup_unselect_row($widget, $row) {
global $gx, $selected;
unset($selected);
insensitive($gx['setup'], 'update');
insensitive($gx['setup'], 'delete');
insensitive($gx['setup'], 'start');
insensitive($gx['setup'], 'stop');
has_default_off($gx['setup'], 'start');
setup_clear();
}
function on_setup_press_row($widget, $event) {
global $gx;
if ($event->button == 3) {
list($row, $column) = $widget->get_selection_info($event->x, $event->y);
if (is_int($row) && is_int($column)) {
$widget->select_row($row, $column);
bar_show('setup', '');
$gx['setup-popup'] = open_window('pptpconfig-setup-popup');
$menu = $gx['setup-popup']->get_widget('pptpconfig-setup-popup');
$menu->popup(NULL, NULL, NULL, $event->button, $event->time);
# todo: need to destroy this on popdown
}
}
if ($event->button == 1) {
if ($event->type == GDK_2BUTTON_PRESS) {
on_setup_start_clicked($widget);
}
}
}
function on_setup_popup_start_activate($widget) {
on_setup_start_clicked($widget);
}
function on_setup_popup_stop_activate($widget) {
on_setup_stop_clicked($widget);
}
# show a particular stats value
function stats_show($tree, $name, $value) {
global $stats, $colours, $stos, $styles;
# but not if it has not changed
if ($stats[$name] == $value) return;
$stats[$name] = $value;
# set the label's new value
$widget = $tree->get_widget($name);
$widget->set_text(sprintf('%8d', $value));
return;
}
# update stats in the tunnel window
function stats($context) {
global $x;
$window = $context['window'];
$interface = $window->get_data('interface');
# read the linux kernel device status table
$fp = fopen('/proc/net/dev', 'r');
if (!$fp) {
message('stats open fail', "Cannot open /proc/net/dev
Interface statistics will not be reported");
return FALSE;
}
while (!ereg($interface, $line)) {
$line = fgets($fp, 1024);
if (feof($fp)) { fclose($fp); return TRUE; }
}
fclose($fp);
# pull apart the line into fields, and display
$regs = split(':| *',$line);
$tree = $context['tree'];
stats_show($tree, 'bytes-in', $regs[3]);
stats_show($tree, 'packets-in', $regs[4]);
stats_show($tree, 'bytes-out', $regs[11]);
stats_show($tree, 'packets-out', $regs[12]);
return TRUE;
}
# translate a pppd exit code to text
# see man pppd, heading EXIT STATUS
function pppd_strerrno($status) {
switch ($status) {
case 1: return 'immediately fatal error';
case 2: return 'error detected processing pppd options';
case 3: return 'pppd is not setuid-root and you are not root';
case 4: return 'kernel lacks support for pppd';
case 5: return 'pppd terminated due to SIGINT, SIGTERM or SIGHUP signal';
case 6: return 'port could not be locked';
case 7: return 'port could not be opened';
case 8: return 'connect script failed';
case 9: return 'pptp could not be run';
case 10: return 'PPP negotiation failed';
case 11: return 'peer failed (or refused) to authenticate itself';
case 12: return 'link terminated because it was idle';
case 13: return 'link terminated because the connect time limit was reached';
case 14: return 'callback was negotiated and incoming call expected';
case 15: return 'link terminated because peer is not responding to echo requests';
case 16: return 'link terminated by PPTP connection closure';
case 17: return 'negotiation failed due to loopback';
case 18: return 'initialisation script failed';
case 19: return 'we failed to authenticate ourselves to the peer';
}
return 'untranslatable exit status';
}
function strsignal($signal) {
switch ($signal) {
case SIGHUP: return 'SIGHUP';
case SIGINT: return 'SIGINT';
case SIGQUIT: return 'SIGQUIT';
case SIGILL: return 'SIGILL';
case SIGABRT: return 'SIGABRT';
case SIGFPE: return 'SIGFPE';
case SIGKILL: return 'SIGKILL';
case SIGSEGV: return 'SIGSEGV';
case SIGPIPE: return 'SIGPIPE';
case SIGALRM: return 'SIGALRM';
case SIGTERM: return 'SIGTERM';
case SIGUSR1: return 'SIGUSR1';
case 16: return 'SIGUSR1';
case SIGUSR2: return 'SIGUSR2';
case 17: return 'SIGUSR2';
case SIGCHLD: return 'SIGCHLD';
case SIGCONT: return 'SIGCONT';
case SIGSTOP: return 'SIGSTOP';
case SIGTSTP: return 'SIGTSTP';
case SIGTTIN: return 'SIGTTIN';
case SIGTTOU: return 'SIGTTOU';
}
return 'signal '.$signal;
}
# colour and display messages in text widget
function scribe($context, $line) {
global $colours, $me;
$colour = $colours['no'];
if (ereg('^sent', $line)) $colour = $colours['tx'];
if (ereg('^rcvd', $line)) $colour = $colours['rx'];
if (ereg('^Using interface ppp', $line)) $colour = $colours['ok'];
if (ereg('^Connect: ppp', $line)) $colour = $colours['ok'];
if (ereg('succeeded', $line)) $colour = $colours['ok'];
if (ereg('compression enabled', $line)) $colour = $colours['ok'];
if (ereg('^local IP address', $line)) $colour = $colours['ok'];
if (ereg('^remote IP address', $line)) $colour = $colours['ok'];
if (ereg('^primary DNS address', $line)) $colour = $colours['ok'];
if (ereg('^secondary DNS address', $line)) $colour = $colours['ok'];
if (ereg('failed', $line)) $colour = $colours['uh'];
if (ereg('^anon warn', $line)) $colour = $colours['uh'];
if (ereg('^anon fatal', $line)) $colour = $colours['uh'];
if (ereg('^'.$me, $line)) $colour = $colours['me'];
$context['text']->insert(NULL, $colour, NULL, $line);
}
# input handler for pppd pipe, displays what pppd says, with our comments
function reader($ignore, $ignore, $context) {
global $me, $gtk_inputs;
$line = fgets($context['pipe'], 1024);
if (!($line === false)) {
scribe($context, $line);
if (ereg("Using interface (ppp[0-9]*)", $line, $regs)) {
$timeout = gtk::timeout_add(500, 'stats', $context);
$window = $context['window'];
$window->set_data('timeout', $timeout);
$window->set_data('interface', $regs[1]);
# todo, if end of $line is not newline, add one here
scribe($context, "$me: monitoring interface ".$regs[1]."\n");
}
if (ereg('^remote IP address ([0-9.]*)', $line, $regs)) {
$window = $context['window'];
$window->set_data('remoteip', $regs[1]);
}
return TRUE;
}
gtk::input_remove($gtk_inputs[$context['pipe']]);
$status = pclose($context['pipe']);
# decode status, per "man wait"
if (pcntl_wifexited($status)) {
$reason = 'exit status';
$status = pcntl_wexitstatus($status);
}
if (pcntl_wifsignaled($status)) {
$reason = 'terminated by signal';
$status = pcntl_wtermsig($status);
}
if (pcntl_wifstopped($status)) {
$reason = 'stopped by signal';
$status = pcntl_wstopsig($status);
}
if (tunnel_name_to_debug($context['name'])) {
scribe($context, "# route -n (after pppd exit)\n" . `route -n`);
}
$diagnosis = ($status == 0) ? "started" : "failed";
scribe($context, "$me: pppd process $reason $status ($diagnosis)\n");
$window = $context['window'];
$window->set_data('exit', $status);
$window->set_data('reason', $reason);
$statusbar = $window->get_data('statusbar');
$statusbar->pop($window->get_data('id'));
$stop = $window->get_data('stop');
$ping = $window->get_data('ping');
$start = $window->get_data('start');
if ($status == 0) {
$state = $window->get_data('state');
if ($state == 'stopping') {
$statusbar->push($window->get_data('id'), 'Stopped');
$window->set_data('state', 'stopped');
setup_list_set_state($context['name'], 'stopped');
scribe($context, "$me: stopped\n");
$stop->set_sensitive(0);
$ping->set_sensitive(0);
$start->set_sensitive(1);
} else {
$interface = $window->get_data('interface');
routing_start($context, $interface);
resolv_start($context, $interface);
undo_save($context['name']);
$statusbar->push($window->get_data('id'), 'Connected');
$window->set_data('state', 'running');
setup_list_set_state($context['name'], 'running');
scribe($context, "$me: connected\n");
$ping->set_sensitive(1);
iconify_start($context, $window);
}
} else {
if ($reason == 'exit status') {
$text = pppd_strerrno($status);
} else {
$text = strsignal($status);
}
scribe($context, "$me: $text\n");
$window->set_data('state', 'stopped');
setup_list_set_state($context['name'], 'stopped');
$statusbar->push($window->get_data('id'), 'Stopped, '.$text);
$stop->set_sensitive(0);
$ping->set_sensitive(0);
$start->set_sensitive(1);
}
if (tunnel_name_to_debug($context['name'])) {
scribe($context, "# route -n (after completion)\n" . `route -n`);
}
return FALSE;
}
function on_setup_start_clicked($widget) {
global $selected;
if ($selected['name'] == '') {
message('start unselected', "Cannot Start.
No tunnel is selected from the list.
Please select a tunnel and try again.");
return;
}
start($selected['name']);
bar_show('setup', '');
}
# return the pppd pid file path for a tunnel name
function pid_name($name) {
return PATH_RUN.'ppp-'.munge($name).'.pid';
}
# return the tunnel state based on existence of pppd pid file
function pid_state($name) {
return is_file(pid_name($name)) ? 'running' : 'stopped';
}
function set_style($gx, $name, $style) {
$widget = $gx->get_widget($name);
$widget->set_style($style);
}
# create a tunnel window (on start, or stop)
function tunnel_window_create($name) {
global $gx;
$gx[$name] = open_window('pptpconfig-tunnel');
$window = $gx[$name]->get_widget('pptpconfig-tunnel');
$window->set_title('pptpconfig tunnel '.$name);
$window->set_data('name', $name);
$window->set_data('state', 'initialising');
setup_list_set_state($name, 'initialising');
$text = $gx[$name]->get_widget('text');
$style = &new GtkStyle;
$style->font = gdk::font_load('-*-fixed-medium-r-normal--15-*-*-*-*-*-iso8859-*');
set_style($gx[$name], 'text', $style);
set_style($gx[$name], 'bytes-in', $style);
set_style($gx[$name], 'bytes-out', $style);
set_style($gx[$name], 'packets-in', $style);
set_style($gx[$name], 'packets-out', $style);
$statusbar = $gx[$name]->get_widget('statusbar');
$window->set_data('id', $statusbar->get_context_id('text'));
$window->set_data('statusbar', $statusbar);
$start = $gx[$name]->get_widget('start');
$window->set_data('start', $start);
$start->set_data('name', $name);
$stop = $gx[$name]->get_widget('stop');
$window->set_data('stop', $stop);
$stop->set_data('name', $name);
$ping = $gx[$name]->get_widget('ping');
$window->set_data('ping', $ping);
$ping->set_data('name', $name);
$copy = $gx[$name]->get_widget('tunnel_copy');
$window->set_data('tunnel_copy', $copy);
$copy->set_data('name', $name);
# todo: this feature doesn't work properly yet, see on_tunnel_copy_activate
$copy->hide();
$save_as = $gx[$name]->get_widget('tunnel_save_as');
$window->set_data('tunnel_save_as', $save_as);
$save_as->set_data('name', $name);
$close = $gx[$name]->get_widget('tunnel_close');
$close->set_data('name', $name);
return $window;
}
function kill_name($name) {
$pidfile = pid_name($name);
if (!is_file($pidfile)) {
message('stop no pidfile', "Tunnel $name not running,-
Liksys
- Сообщения: 2910
Re: Пытаюсь перейти from RHEL4 to FC6!
Ужас! В аттач в следующий раз 
-
Antony
- Сообщения: 22
- ОС: Edgy Eft
Re: Пытаюсь перейти from RHEL4 to FC6!
P.S. Там в тексте я красненьким выделил подозрительный комментарий, который, как мне казалось, может мне помочь при решении возникшей проблемы. Но что делать с ./? Я куда только не подставлял в этом абзаце... Не помогает: скрипт отказывается работать вообще!
Заранее спасибо за посильную помощь!
Заранее спасибо за посильную помощь!
-
arkhnchul
- Сообщения: 2284
- Статус: Толчковый инженер
- ОС: Debian, Fedora
Re: Пытаюсь перейти from RHEL4 to FC6!
Antony
твайумать.. зачем СТОЛЬКО постить?
насчет прав рута: man sudoers, man sudo... и будет пароль рута знать только рут, и команда пускаться.
твайумать.. зачем СТОЛЬКО постить?
насчет прав рута: man sudoers, man sudo... и будет пароль рута знать только рут, и команда пускаться.
Losing is fun!
-
Antony
- Сообщения: 22
- ОС: Edgy Eft
Re: Пытаюсь перейти from RHEL4 to FC6!
насчет прав рута: man sudoers, man sudo... и будет пароль рута знать только рут, и команда пускаться.
Уважаемый, это понятно даже мне...
Вот что у меня при попытке запустить /usr/sbin/pptpconfig из сеанса пользователя (само собой, что в /etc/sudoers я прописал этот скрипт именно этому пользователю пускать без всякого PASSWORD):
Причем GUI нормально поднимается, но при попытке запуска соединения выскакивает ошибка.
sh: pptp: command not found
couldn't get channel number: Input/Output error
pptpconfig: pppd process terminated by signal 1 (failed)
pptpconfig: SIGNUP
Таким образом нетрудно сделать вывод, что надо править текст скрипта...
Мануалы прочту ещё разочек, тут спору нет...