2009-02-24

Анонсирован выход Bash 4.0, лицензия изменена на GPLv3

Спустя 5 лет с момента выхода предыдущей ветки, представлен новый релиз командного интерпретатора Bash - 4.0. Исходные тексты программы, начиная с данного релиза, распространяются под лицензией GPLv3.

Из новых возможностей, появившихся в bash 4.0 с момента выпуска прошлого релиза bash 3.2, можно отметить:

* Реализована новая опция "autocd", при включении которой появляется возможность быстрого перехода в директории через ввод имени директории вместо команды (т.е. выполнение в интерактивной оболочке "dir" будет эквивалентно запуску "cd dir");
* Если заданная команда не найдена, оболочка теперь пытается выполнить shell функцию с именем "command_not_found_handle", в которую в качестве аргументов передаются параметры не найденной команды;
* Добавлена реализация поддержки ассоциативных массивов, которые могут быть созданы при помощи декларатора "-A". Формат: name[subscript]=value, обращение к элементу ${name[subscript]};
* Изменен формат встроенной документации, который теперь напоминает man-страницы. Изменен метод сортировки вывода в команде help. К команду help добавлены опции "-d" (вывод короткого списка описаний) и "-m" (вывод в помощи в формате man-страниц);
* Система автодополнения претерпела ряд небольших усовершенствований, например, добавлена начальная поддержка дополнения глобальных переменных в командах. Новая опция "dirspell" позволяет включить механизм корректировки орфографии при автодополнении имен файлов и директорий. Расширены возможности программирования обработчиков автодополнения;
* Изменено поведение встроенной функции read в момент истечения заданного таймаута, который можно задать через опцию "-t". Теперь при этом возвращается код ошибки больше 128 и сохраняются частично полученные до таймаута данные. Кроме того, таймаут теперь может принимать дробные значения. Дополнительно в read добавлена новая опция "-i", которая позволяет при использовании readline поместить введенный текст в буфер ответа (reply buffer);
* Новая опция "checkjobs" для проверки наличия активных или приостановленных заданий перед выходом и вывода предупреждения, если такие имеются;
* В переменной $BASHPID теперь сохраняется идентификатор (pid) текущего процесса.
* Если из-за недостатка ресурсов bash не удалось создать дочерний процесс, то перед выводом ошибки осуществляется еще несколько попыток;
* Размер блока для опций "-c" и "-f" команды ulimit приведен в соответствие с Posix и теперь равен 512 байтам при активном Posix режиме. В ulimit добавлены новые опции -b (размер буфера сокета) и -T (число нитей);
* Добавлена новая встроенная команда "mapfile" (плюс добавлен синоним "readarray") для заполнения массива на основе строк указанного файла;
* Реализована новая опция "globstar", при включении которой под маску "**" подпадают все директории и файлы с использованием рекурсивного перебора;
* Добавлен новый оператор редиректа "&>>", который добавляет стандартный вывод и стандартный поток ошибок к заданному файлу;
* Для дополнения передаваемого следующему процессу стандартного вывода потоком ошибок, вместо конструкции "2>&1 теперь можно использовать синоним "|&";
* Реализовано несколько новых терминирующих конструкций в системе обработки "case" списков: ";&" (запустить действие приписанное к следующему шаблону) и ";;&" (продолжить проверку следующих шаблонов).
* Оболочка распознает новую команду для обрезание длинных путей PROMPT_DIRTRIM. В качестве значения указывается длина пути. После превышения заданной длины в приглашении ввода будет осуществлено обрезание длинных путей, заменяя конец на "...";
* Новые средства для приведения определенных символов в строке к верхнему или нижнему регистру: uppercase (^[^]) и lowercase (,[,]). В команде declare появилась поддержка преобразования регистра через указание опций -l (lowercase) и -u (uppercase);
* Для управления асинхронным выполнением команд добавлено ключевое слово "coproc";
* Ощутимо расширены возможность библиотеки readline и shell биндинга к ней, добавлено около десятка новых функций.

2009-02-20

TIFF, Old Jpeg и Linux

Недавно нам на работе скинули сканированную документацию, собранную в один многостраничный TIFF, да еще сжатый Old Jpeg. Evince и GQview показывали только пустые страницы. GIMP ругался при открытии:

unknown field with tag 513 (0x201) encountered


и при открытии также показывал пустые страницы. Указанную ошибку выдавали также и утилиты из пакета libtiff-utils. KDEшные утилиты не пробовал, ибо не использую. Поиск в интернете выявил причину ошибки - компрессию Old Jpeg, которая в настоящее время не используется из-за найденных уязвимостей, и все библиотеки собраны без поддержки оной. Поставщик решения предложил нам для открытия этих файлов использовать Irfan View 3.95, что, естественно, нас не устраивало :) Дальнейший поиск в интернете навел на утилиту foremost, которая, наконец, избавила нас от головной боли, и спокойно распаковала jpg-файлы из TIFF в папку, попутно исправляя их заголовки. Теперь дело за малым - собрать картинки для удобства просмотра в PS- или PDF-файл. Но это уже другая история :)

2009-02-16

Реализация глобального меню для GNOME и KDE

Вышла новая версия (0.7.3) проекта gnome2-globalmenu, в рамках которого ведется разработка реализации глобального меню для GNOME, при котором меню текущего приложения перенесено из окна программы в верхнюю строку экрана, как это реализовано в Mac OS X. Ранее проект требовал модификации Gtk+, но теперь работает без внесения дополнительных патчей в библиотеки и может быть установлен как обычный GNOME апплет. Одно из еще не решенных ограничений программы - "глобализация" меню возможна только для Gtk+ приложений. Энтузиасты, заинтересованные в проекте, пытаются добиться включения данного апплета в стандартную поставку GNOME, а также проводят акцию по сбору голосов за активацию апплета в Ubuntu.

Стоит отметить, что разработка аналогичного глобального меню ведется и для KDE.

Ссылка

CakeBilling. Установка web-сервера и web-интерфейса.

Установка web-сервера для вывода статистики.

Можно поставить Tomcat из репозитория, но он так нормально и не заработал (хотя, если повозиться, заставить работать можно). Сами же разработчики биллинга советуют ставить resin. Скачивать надо .deb-пакет в строке для обычной версии (не Pro). Инсталляция с помощью dpkg тривиальна. Дальнейшая настройка описана на этой странице, но следует учесть, что часть действий уже проделана скриптами инсталляции .deb-пакета.


Установка web-app администраторского интерфейса

Скачиваем war архив с web-app интерфейсом cake-1.03-UTF8-v2.war отсюда.

Копируем war архив в /var/www/resin/webapps, он будет автоматически распакован.
Конфигурируем web-app посредством правки файла webapps/cake/WEB-INF/cake.xml

db_user="cake"
db_password="yourpassword"
db_charset="UTF-8"
db_driver="org.postgresql.Driver"
db_connstr="jdbc:postgresql://localhost/cake"


Перезапускаем Resin

root@cake$ /etc/init.d/resin restart

Проверяем, вводим в браузере что то типа http://igate/cake, где igate -- это наш шлюз в интернет.
Note: login: admin password: 1234

Администрируем, работаем.

На этом все об этом биллинге. Все дальнейшие вопросы в группы Google и инет.

Настройка работы с Агент.mail.ru через транспорт в Pidgin

Понадобилось внести в контакт чела, из-за нестабильной связи по ICQ, вот и озаботился. Тут нашел рекомендации, которые и привожу:

Вот 1-й вариант:

Для того чтобы подключить майл агент к pidgin, кроме майл-аккаунта и самого pidgin необходимы еще 2 вещи:
1. Аккаунт Jabber (регимся на jabber.ru, получаем аккаунт ник@jabber.ru);
2. Ставим jabber-направленный клиент (не Pidgin), например psi (я делал через bombus на телефоне).

Далее запускаем jabber-клиент (http://www.jabber.ru/node/671) и подключаем аккаунт ник@jabber.ru.
Когда все работаем идем в tools(инструменты) ->Service discovery (обзор сервисов), выбираем транспорт mrim.jabber.ru,
вводим адрес электронной почты имя@mail.ru и пароль. Получаем контакты майл-агента в виде
имя%mail.ru@mrim.jabber.ru.
Теперь отключаем jabber-клиент и включаем pidgin, логинимся под ник@jabber.ru и получаем контакты майл-агента (возможно все контакты будут автоматически запрашивать авторизацию). Если этого не произошло необходимо вручную добавить контакты типа имя% mail.ru@mrim.jabber.ru.

P.S. Pidgin - не является специализированным jabber-клиентом, и настройка транспортов в нем не реализована как в других jabber-клиентах, по причине того что в него уже включены многие из тех протоколов для которых эти транспорты и существуют.
При этом Pidgin является открытой программой, и непосредственное подключение протокола майл-агента можно создать самому (при владении навыков программирования), единственной причиной (по-моему) того, что этого, до сих пор не было сделано, является, наличие обильного спама как в почте так и в агенте.
Само использование Pidgin для общения по майл-агенту может быть обусловленно, только необходимостью использования нескольких протоколов одновременно.


2-й вариант:

Я настроил так(на jabber.ru):
1)Выбрал протокол XMPP
2)Имя пользователя - имя пользователя на Jabber.ru (например user@jabber.ru)
3)Домен - jabber.ru
4)Ресурс - почтовый_логин% mail.ru@mrim.jabber.ru
5)Пароль - пароль к jabber.ru

На вкладке дополнительно:

Соединять на порт 443
Соединение с сервером allports.jabber.ru

Все прекрасно работает.


Воспользовался 1-ым вариантом, ибо и так стоял Gajim параллельно с Pidgin'ом. Все получилось...

2009-02-15

Вышел релиз Debian GNU/Linux 5.0 (Lenny). Обзор новшеств

После почти двух лет разработки выпущен долгожданный релиз Debian GNU/Linux 5.0 (Lenny). Для установки доступны несколько дисковых образов:

* CD для установки по сети.
* Полный CD (650 MB), варианты с GNOME, KDE и LXDE + Xfce
* DVD
* Образ Blu-ray диска
* CD в формате бизнес-карты. По умолчанию используется окружение на базе LXDE, Xfce оставлен в качестве альтернативного варианта

Основные новшества:

* Обновление программного обеспечения: Linux ядро 2.6.26, Gnome 2.22 (из-за проблем с интеграцией gvfs Nautilus и панель взяты из версии 2.20), KDE 3.5.10 (в бэкпортах доступна сборка KDE 4.1.4), XFCE 4.2, LXDE 0.3.2.1, Xorg 7.3, OpenOffice.org 2.4, Firefox 3, Apache 2.2.9, MySQL 5.0.51, PHP 5.2.6, Ruby 1.8 и 1.9, Python 2.5.2. Всего в репозитории Debian Lenny насчитывается около 22 тыс. пакетов.
* В состав дистрибутива решено включить спорные проприетарные бинарные компонены (firmware). Работа по проверке и чистке неоднозначных бинарных вставок отложена на неопределенный срок. Напомню, что правила проекта Debian запрещают помещение в состав дистрибутива компонент для которых отсутствуют исходные тексты, в то время как у большого числа драйверов из состава Linux ядра имеется привязка к проприетарным бинарным прошивкам, для которых исходные тексты недоступны. Также в репозитории main появились программы с лицензией AGPLv3 (GNU Affero General Public License);
* Init-скрипты переведены на новую систему инициализации с учетом зависимостей, позволяющую организовать параллельный запуск сервисов;
* В состав Lenny, вместо старой архитектуры ARM, включена новая реализация "ARMEL". Порт "Armel" (EABI) теперь предлагается по умолчанию, кроме того Lenny последний релиз Debian в котором поддерживается старый порт "Arm" (ABI).
* Дистрибутив переведен сборку пакетов при помощи GCC-4.3, который теперь используется как компилятор по умолчанию для всех архитектур;
* Осуществлен переход на использование Python 2.5 и Perl 5.10 (изменено более 400 связанных с Perl пакетов). Обновлены версии пакетов ocaml и gcc-defaults. Проведена замена g77 на gfortran реализацию языке Фортран;
* Дистрибутив полностью подготовлен для использования в качестве /bin/sh оболочки dash. Но решено еще не использовать dash в качестве shell по умолчанию, переключиться на dash можно опционально;
* Полностью реализована поддержка интернационализации (I18n) в системе управления конфигурацией Debian, пакеты использующие подсистему debconf полностью поддерживают перевод сообщений на разные языки. Файлы changelog и control во всех пакетах переведены на использование кодировки UTF-8;
* Осуществлен полный уход от использования debmake. Все пакеты в репозиторие 'main' теперь связаны рекомендательными зависимостями только внутри 'main', не ссылаясь на дополнительные репозитории;
* Во всех приложениях которые могут работать через IPv4 добавлена полная поддержка IPv6;
* Проведен аудит приложений на предмет устранения ограничений на размер обрабатываемых файлов (некоторые программы не читали файлы больше 2/4 Гб).
* Добавлена поддержка NFS v4;
* В "main" репозиторий включены бинарные пакеты qmail и djbdns, которые ранее были доступны для пользователей Debian только в исходных текстах или через сторонние репозитории пакетов, из-за лицензионной политики автора;
* Улучшения связанные с безопасностью
o Stack protector - сборка пакетов с включенной в GCC опцией "-fstack-protector" для защиты от атак, направленных на переполнение буфера и стека.
o Fortify Source - активация средства glibc ("-D_FORTIFY_SOURCE=2" ) для дополнительной внутренней проверки выхода за пределы буфера функций, таких как strcpy.
o Format warnings - защита от атак через параметры форматирования строки (format-string), обеспечивается сборкой с параметрами "-Wformat" и "-Wformat-security".
o Address Space Layout Randomization - случайный выбор позиции для размещения стека и области выделяемой через mmap памяти;
o relro - переключение определенных областей памяти, после загрузки исполняемого приложения, в режим только для чтения. Включается через сборку с "-Wl,zrelro";
* Улучшение в инсталляторе:
o В образ установочного компакт диска добавлены модули для PATA/IDE устройств (частично решает проблемы с установкой на машины с дисковыми контроллерами Marvell);
o Улучшена поддержка BRLTTY устройств (точечные дисплеи для слепых);
o Добавлена поддержка загрузки прошивок (firmware) с дополнительных носителей информации (например, с USB Flash или SD/MMC карты) в процессе установки дистрибутива;
o Полная поддержка установки на зашифрованные разделы. Улучшена поддержка работы с шифрованными разделами в режиме восстановления после сбоя;
o Из состава CD удалена директория tools/, в которой были такие утилиты, как loadlin, unzip, gzip.
o Добавлена поддержка создания SATA RAID через dmraid;
o Возможность обновления пакетов, содержащих уязвимости, на ранней стадии установки;
o Для архитектур i386 и amd64 реализовано новое интерактивное меню, выдаваемое при загрузке (syslinux vesamenu);
o Возможность установки из Windows при помощи ПО win32-loader;
o Реализована поддержка установки системы на NAS серверы, основанные на платформе Marvell Orion, базирующейся на архитектуре ARMv5 (например QNAP TS-109, TS-209 и TS-409, HP Media Vault mv2120, Buffalo Kurobox Pro).
o В графическом инсталляторе увеличено удобство выбора языка для локализации: улучшена наглядность, добавлена возможность перехода между диалоговыми окнами, страны разбиты на блоки, привязанные к континентам. При выборе языка, для которого перевод установочных сообщений не доведен до конца, теперь выводится предупреждение с возможностью выбора второго языка, на котором будут выводиться непереведенные тексты;
o Доведено до рабочего состояния монтирование файловых систем в режиме relatime, появившемся в Linux ядре 2.6.20 и в отличии от монтирования ФС с noatime флагом, учет времени чтения файла производится только если прошлый atime старее чем mtime (время изменения) или ctime (время создания);
o Возможность выбора дополнительных действий при использовании установочных образов с KDE или Xfce CD.
o Возможность подключения дополнительных репозиториев с CD/DVD дисков, убранная в “etch”, вновь вернулась в lenny. Это значительно улучшит поддержку i18n в инсталляторе, т.к. не все языковые пакеты умещались на первом CD;
o Установщик, в случае, если сконфигурировано сетевое подключение, будет теперь пытаться синхронизировать часы компьютера с одним из доступных ntp-серверов;
o Прекращена поддержка DECstation (mips), RiscPC (arm) и sparc32 машин.

Ссылка


Да, изменений много, и многое надо в этом перечне осмыслить. Например, как работает новая система инициализации с учетом зависимостей, позволяющая организовать параллельный запуск сервисов.

2009-02-12

CakeBilling. Установка и настройка PPP и PPTPD.

Установка PPP и PPTPD.

# apt-get install ppp
# apt-get install pptpd
# apt-get install radiusclient1

Первым настроим radiusclient для работы с нашим FreeRADIUS сервером.

Добавляем в /etc/radiusclient/servers наш RADIUS сервер.
localhost test

Изменяем в /etc/radiusclient/radiusclient.conf сервер для авторизации и аккаунтинга.

authserver localhost:1812
acctserver localhost:1813

Также надо добавить в /etc/radiusclient/dictionary те же аттрибуты, которые добавлены в /etc/freeradius/dictionary:

ATTRIBUTE Acct-Interim-Interval 85 integer
ATTRIBUTE Session-Octets-Limit 227 integer
ATTRIBUTE Octets-Direction 228 integer

ATTRIBUTE PPPD-Upstream-Speed-Limit 230 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit 231 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-1 232 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-1 233 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-2 234 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-2 235 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-3 236 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-3 237 integer

Изменяем файл /etc/ppp/pptpd-options:
# Authentication

# Name of the local system for authentication purposes
# (must match the second field in /etc/ppp/chap-secrets entries)
name pptpd

# Optional: domain name to use for authentication
# domain mydomain.net

# Strip the domain prefix from the username before authentication.
# (applies if you use pppd with chapms-strip-domain patch)
#chapms-strip-domain

auth

# Encryption
# Debian: on systems with a kernel built with the package
# kernel-patch-mppe >= 2.4.2 and using ppp >= 2.4.2, ...
# {{{
refuse-pap
require-chap
require-mschap
# Require the peer to authenticate itself using MS-CHAPv2 [Microsoft
# Challenge Handshake Authentication Protocol, Version 2] authentication.
require-mschap-v2
# Require MPPE 128-bit encryption
# (note that MPPE requires the use of MSCHAP-V2 during authentication)
#require-mppe-128
nomppe
# }}}

silent


# Network and Routing

# If pppd is acting as a server for Microsoft Windows clients, this
# option allows pppd to supply one or two DNS (Domain Name Server)
# addresses to the clients. The first instance of this option
# specifies the primary DNS address; the second instance (if given)
# specifies the secondary DNS address.
# Attention! This information may not be taken into account by a Windows
# client. See KB311218 in Microsoft's knowledge base for more information.
#ms-dns 10.0.0.1
#ms-dns 10.0.0.2
ms-dns 192.168.1.1

# If pppd is acting as a server for Microsoft Windows or "Samba"
# clients, this option allows pppd to supply one or two WINS (Windows
# Internet Name Services) server addresses to the clients. The first
# instance of this option specifies the primary WINS address; the
# second instance (if given) specifies the secondary WINS address.
#ms-wins 10.0.0.3
#ms-wins 10.0.0.4

# Add an entry to this system's ARP [Address Resolution Protocol]
# table with the IP address of the peer and the Ethernet address of this
# system. This will have the effect of making the peer appear to other
# systems to be on the local ethernet.
# (you do not need this if your PPTP server is responsible for routing
# packets to the clients -- James Cameron)
proxyarp

# Debian: do not replace the default route
#nodefaultroute


# Logging

# Enable connection debugging facilities.
# (see your syslog configuration for where pppd sends to)
#debug

# Print out all the option values which have been set.
# (often requested by mailing list to verify options)
#dump


# Miscellaneous

# Create a UUCP-style lock file for the pseudo-tty to ensure exclusive
# access.
lock

# Disable BSD-Compress compression
nobsdcomp

nodeflate

nologfd

plugin /usr/lib/pppd/2.4.4/radius.so


ms-dns - ваш DNS сервер или DNS сервер провайдера.
ppp будет принимать запросы только с типом авторизации chap mschap mschap-v2,
pap отключен в связи с тем что передает пароль в открытом виде.
nomppe nomppc - отключаем компрессию и шифрование.
silent - работать пассивно. Ожидаем запросы от клиента. В противном случае сервер начинает запрашивать параметры у клиента. В результате чего windows VPN работает не стабильно.
nodeflate nobsdcomp - отключаем компрессию.
plugin /usr/lib/pppd/2.4.4/radius.so - подключаем плагин radius.so. Если у вас не 2.4.4 версия измените путь так чтоб он соответствовал вашей версии.
На этом настройка ppp для pptpd закончена.

Переходим к pptpd.

Редактируем файл /etc/pptpd.conf:

option /etc/ppp/pptpd-options
localip 192.168.0.1
remoteip 192.168.0.2-254
option /etc/ppp/pptpd-options - указываем файл с опциями для ppp при поднятии инкапсуляции. localip 192.168.0.1 - ip адрес сервера VPN сети. remoteip 192.168.0.2-254 - ip адреса клиентов VPN сети.

2009-02-11

CakeBilling. Установка и настройка FreeRADIUS.

Установка FreeRADIUS:

# apt-get install freeradius // собственно сервер
# apt-get install freeradius-postgresql // модуль для связи с PostgreSQL

Все переменные что не описаны в файлах удалите. Они не требуются для работы FreeRADIUS с pppd.

Сначала редактируем файл /etc/freeradius/radiusd.conf:

##
## radiusd.conf -- FreeRADIUS server configuration file.
##
## http://www.freeradius.org/
## $Id: radiusd.conf.in,v 1.188.2.4.2.18 2007/07/16 10:53:13 pnixon Exp $
##

# The location of other config files and
# logfiles are declared in this file
#
# Also general configuration for modules can be done
# in this file, it is exported through the API to
# modules that ask for it.
#
# The configuration variables defined here are of the form ${foo}
# They are local to this file, and do not change from request to
# request.
#
# The per-request variables are of the form %{Attribute-Name}, and
# are taken from the values of the attribute in the incoming
# request. See 'doc/variables.txt' for more information.

prefix = /usr
exec_prefix = /usr
sysconfdir = /etc
localstatedir = /var
sbindir = ${exec_prefix}/sbin
logdir = /var/log/freeradius
raddbdir = /etc/freeradius
radacctdir = ${logdir}/radacct

# Location of config and logfiles.
confdir = ${raddbdir}
run_dir = ${localstatedir}/run/freeradius

#
# The logging messages for the server are appended to the
# tail of this file.
#
log_file = ${logdir}/radius.log

#
# libdir: Where to find the rlm_* modules.
#
# This should be automatically set at configuration time.
#
# If the server builds and installs, but fails at execution time
# with an 'undefined symbol' error, then you can use the libdir
# directive to work around the problem.
#
# The cause is usually that a library has been installed on your
# system in a place where the dynamic linker CANNOT find it. When
# executing as root (or another user), your personal environment MAY
# be set up to allow the dynamic linker to find the library. When
# executing as a daemon, FreeRADIUS MAY NOT have the same
# personalized configuration.
#
# To work around the problem, find out which library contains that symbol,
# and add the directory containing that library to the end of 'libdir',
# with a colon separating the directory names. NO spaces are allowed.
#
# e.g. libdir = /usr/local/lib:/opt/package/lib
#
# You can also try setting the LD_LIBRARY_PATH environment variable
# in a script which starts the server.
#
# If that does not work, then you can re-configure and re-build the
# server to NOT use shared libraries, via:
#
# ./configure --disable-shared
# make
# make install
#
libdir = /usr/lib/freeradius

# pidfile: Where to place the PID of the RADIUS server.
#
# The server may be signalled while it's running by using this
# file.
#
# This file is written when ONLY running in daemon mode.
#
# e.g.: kill -HUP `cat /var/run/freeradius/freeradius.pid`
#
pidfile = ${run_dir}/freeradius.pid


# user/group: The name (or #number) of the user/group to run radiusd as.
#
# If these are commented out, the server will run as the user/group
# that started it. In order to change to a different user/group, you
# MUST be root ( or have root privleges ) to start the server.
#
# We STRONGLY recommend that you run the server with as few permissions
# as possible. That is, if you're not using shadow passwords, the
# user and group items below should be set to 'nobody'.
#
# On SCO (ODT 3) use "user = nouser" and "group = nogroup".
#
# NOTE that some kernels refuse to setgid(group) when the value of
# (unsigned)group is above 60000; don't use group nobody on these systems!
#
# On systems with shadow passwords, you might have to set 'group = shadow'
# for the server to be able to read the shadow password file. If you can
# authenticate users while in debug mode, but not in daemon mode, it may be
# that the debugging mode server is running as a user that can read the
# shadow info, and the user listed below can not.
#
user = freerad
group = freerad

# max_request_time: The maximum time (in seconds) to handle a request.
#
# Requests which take more time than this to process may be killed, and
# a REJECT message is returned.
#
# WARNING: If you notice that requests take a long time to be handled,
# then this MAY INDICATE a bug in the server, in one of the modules
# used to handle a request, OR in your local configuration.
#
# This problem is most often seen when using an SQL database. If it takes
# more than a second or two to receive an answer from the SQL database,
# then it probably means that you haven't indexed the database. See your
# SQL server documentation for more information.
#
# Useful range of values: 5 to 120
#
max_request_time = 30

# delete_blocked_requests: If the request takes MORE THAN 'max_request_time'
# to be handled, then maybe the server should delete it.
#
# If you're running in threaded, or thread pool mode, this setting
# should probably be 'no'. Setting it to 'yes' when using a threaded
# server MAY cause the server to crash!
#
delete_blocked_requests = no

# cleanup_delay: The time to wait (in seconds) before cleaning up
# a reply which was sent to the NAS.
#
# The RADIUS request is normally cached internally for a short period
# of time, after the reply is sent to the NAS. The reply packet may be
# lost in the network, and the NAS will not see it. The NAS will then
# re-send the request, and the server will respond quickly with the
# cached reply.
#
# If this value is set too low, then duplicate requests from the NAS
# MAY NOT be detected, and will instead be handled as seperate requests.
#
# If this value is set too high, then the server will cache too many
# requests, and some new requests may get blocked. (See 'max_requests'.)
#
# Useful range of values: 2 to 10
#
cleanup_delay = 5

# max_requests: The maximum number of requests which the server keeps
# track of. This should be 256 multiplied by the number of clients.
# e.g. With 4 clients, this number should be 1024.
#
# If this number is too low, then when the server becomes busy,
# it will not respond to any new requests, until the 'cleanup_delay'
# time has passed, and it has removed the old requests.
#
# If this number is set too high, then the server will use a bit more
# memory for no real benefit.
#
# If you aren't sure what it should be set to, it's better to set it
# too high than too low. Setting it to 1000 per client is probably
# the highest it should be.
#
# Useful range of values: 256 to infinity
#
max_requests = 65536

# bind_address: Make the server listen on a particular IP address, and
# send replies out from that address. This directive is most useful
# for machines with multiple IP addresses on one interface.
#
# It can either contain "*", or an IP address, or a fully qualified
# Internet domain name. The default is "*"
#
# As of 1.0, you can also use the "listen" directive. See below for
# more information.
#
bind_address = *

# port: Allows you to bind FreeRADIUS to a specific port.
#
# The default port that most NAS boxes use is 1645, which is historical.
# RFC 2138 defines 1812 to be the new port. Many new servers and
# NAS boxes use 1812, which can create interoperability problems.
#
# The port is defined here to be 0 so that the server will pick up
# the machine's local configuration for the radius port, as defined
# in /etc/services.
#
# If you want to use the default RADIUS port as defined on your server,
# (usually through 'grep radius /etc/services') set this to 0 (zero).
#
# A port given on the command-line via '-p' over-rides this one.
#
# As of 1.0, you can also use the "listen" directive. See below for
# more information.
#
port = 0

# hostname_lookups: Log the names of clients or just their IP addresses
# e.g., www.freeradius.org (on) or 206.47.27.232 (off).
#
# The default is 'off' because it would be overall better for the net
# if people had to knowingly turn this feature on, since enabling it
# means that each client request will result in AT LEAST one lookup
# request to the nameserver. Enabling hostname_lookups will also
# mean that your server may stop randomly for 30 seconds from time
# to time, if the DNS requests take too long.
#
# Turning hostname lookups off also means that the server won't block
# for 30 seconds, if it sees an IP address which has no name associated
# with it.
#
# allowed values: {no, yes}
#
hostname_lookups = no

# Core dumps are a bad thing. This should only be set to 'yes'
# if you're debugging a problem with the server.
#
# allowed values: {no, yes}
#
allow_core_dumps = no

# Regular expressions
#
# These items are set at configure time. If they're set to "yes",
# then setting them to "no" turns off regular expression support.
#
# If they're set to "no" at configure time, then setting them to "yes"
# WILL NOT WORK. It will give you an error.
#
regular_expressions = yes
extended_expressions = yes

# Log the full User-Name attribute, as it was found in the request.
#
# allowed values: {no, yes}
#
log_stripped_names = no

# Log authentication requests to the log file.
#
# allowed values: {no, yes}
#
log_auth = yes

# Log passwords with the authentication requests.
# log_auth_badpass - logs password if it's rejected
# log_auth_goodpass - logs password if it's correct
#
# allowed values: {no, yes}
#
log_auth_badpass = yes
log_auth_goodpass = no

# usercollide: Turn "username collision" code on and off. See the
# "doc/duplicate-users" file
#
# WARNING
# !!!!!!! Setting this to "yes" may result in the server behaving
# !!!!!!! strangely. The "username collision" code will ONLY work
# !!!!!!! with clear-text passwords. Even then, it may not do what
# !!!!!!! you want, or what you expect.
# !!!!!!!
# !!!!!!! We STRONGLY RECOMMEND that you do not use this feature,
# !!!!!!! and that you find another way of acheiving the same goal.
# !!!!!!!
# !!!!!!! e,g. module fail-over. See 'doc/configurable_failover'
# WARNING
#
usercollide = no

# lower_user / lower_pass:
# Lower case the username/password "before" or "after"
# attempting to authenticate.
#
# If "before", the server will first modify the request and then try
# to auth the user. If "after", the server will first auth using the
# values provided by the user. If that fails it will reprocess the
# request after modifying it as you specify below.
#
# This is as close as we can get to case insensitivity. It is the
# admin's job to ensure that the username on the auth db side is
# *also* lowercase to make this work
#
# Default is 'no' (don't lowercase values)
# Valid values = "before" / "after" / "no"
#
lower_user = no
lower_pass = no

# nospace_user / nospace_pass:
#
# Some users like to enter spaces in their username or password
# incorrectly. To save yourself the tech support call, you can
# eliminate those spaces here:
#
# Default is 'no' (don't remove spaces)
# Valid values = "before" / "after" / "no" (explanation above)
#
nospace_user = no
nospace_pass = no

# The program to execute to do concurrency checks.
checkrad = ${sbindir}/checkrad

# SECURITY CONFIGURATION
#
# There may be multiple methods of attacking on the server. This
# section holds the configuration items which minimize the impact
# of those attacks
#
security {
#
# max_attributes: The maximum number of attributes
# permitted in a RADIUS packet. Packets which have MORE
# than this number of attributes in them will be dropped.
#
# If this number is set too low, then no RADIUS packets
# will be accepted.
#
# If this number is set too high, then an attacker may be
# able to send a small number of packets which will cause
# the server to use all available memory on the machine.
#
# Setting this number to 0 means "allow any number of attributes"
max_attributes = 200

#
# reject_delay: When sending an Access-Reject, it can be
# delayed for a few seconds. This may help slow down a DoS
# attack. It also helps to slow down people trying to brute-force
# crack a users password.
#
# Setting this number to 0 means "send rejects immediately"
#
# If this number is set higher than 'cleanup_delay', then the
# rejects will be sent at 'cleanup_delay' time, when the request
# is deleted from the internal cache of requests.
#
# Useful ranges: 1 to 5
reject_delay = 1

#
# status_server: Whether or not the server will respond
# to Status-Server requests.
#
# Normally this should be set to "no", because they're useless.
# See: http://www.freeradius.org/rfc/rfc2865.html#Keep-Alives
#
# However, certain NAS boxes may require them.
#
# When sent a Status-Server message, the server responds with
# an Access-Accept packet, containing a Reply-Message attribute,
# which is a string describing how long the server has been
# running.
#
status_server = no
}

# CLIENTS CONFIGURATION
#
# Client configuration is defined in "clients.conf".
#

# The 'clients.conf' file contains all of the information from the old
# 'clients' and 'naslist' configuration files. We recommend that you
# do NOT use 'client's or 'naslist', although they are still
# supported.
#
# Anything listed in 'clients.conf' will take precedence over the
# information from the old-style configuration files.
#
$INCLUDE ${confdir}/clients.conf


# SNMP CONFIGURATION
#
# Snmp configuration is only valid if SNMP support was enabled
# at compile time.
#
# To enable SNMP querying of the server, set the value of the
# 'snmp' attribute to 'yes'
#
snmp = no
$INCLUDE ${confdir}/snmp.conf


# THREAD POOL CONFIGURATION
#
# The thread pool is a long-lived group of threads which
# take turns (round-robin) handling any incoming requests.
#
# You probably want to have a few spare threads around,
# so that high-load situations can be handled immediately. If you
# don't have any spare threads, then the request handling will
# be delayed while a new thread is created, and added to the pool.
#
# You probably don't want too many spare threads around,
# otherwise they'll be sitting there taking up resources, and
# not doing anything productive.
#
# The numbers given below should be adequate for most situations.
#
thread pool {
# Number of servers to start initially --- should be a reasonable
# ballpark figure.
start_servers = 5

# Limit on the total number of servers running.
#
# If this limit is ever reached, clients will be LOCKED OUT, so it
# should NOT BE SET TOO LOW. It is intended mainly as a brake to
# keep a runaway server from taking the system with it as it spirals
# down...
#
# You may find that the server is regularly reaching the
# 'max_servers' number of threads, and that increasing
# 'max_servers' doesn't seem to make much difference.
#
# If this is the case, then the problem is MOST LIKELY that
# your back-end databases are taking too long to respond, and
# are preventing the server from responding in a timely manner.
#
# The solution is NOT do keep increasing the 'max_servers'
# value, but instead to fix the underlying cause of the
# problem: slow database, or 'hostname_lookups=yes'.
#
# For more information, see 'max_request_time', above.
#
max_servers = 32

# Server-pool size regulation. Rather than making you guess
# how many servers you need, FreeRADIUS dynamically adapts to
# the load it sees, that is, it tries to maintain enough
# servers to handle the current load, plus a few spare
# servers to handle transient load spikes.
#
# It does this by periodically checking how many servers are
# waiting for a request. If there are fewer than
# min_spare_servers, it creates a new spare. If there are
# more than max_spare_servers, some of the spares die off.
# The default values are probably OK for most sites.
#
min_spare_servers = 3
max_spare_servers = 10

# There may be memory leaks or resource allocation problems with
# the server. If so, set this value to 300 or so, so that the
# resources will be cleaned up periodically.
#
# This should only be necessary if there are serious bugs in the
# server which have not yet been fixed.
#
# '0' is a special value meaning 'infinity', or 'the servers never
# exit'
max_requests_per_server = 0
}

# MODULE CONFIGURATION
#
# The names and configuration of each module is located in this section.
#
# After the modules are defined here, they may be referred to by name,
# in other sections of this configuration file.
#
modules {
#
# Each module has a configuration as follows:
#
# name [ instance ] {
# config_item = value
# ...
# }
#
# The 'name' is used to load the 'rlm_name' library
# which implements the functionality of the module.
#
# The 'instance' is optional. To have two different instances
# of a module, it first must be referred to by 'name'.
# The different copies of the module are then created by
# inventing two 'instance' names, e.g. 'instance1' and 'instance2'
#
# The instance names can then be used in later configuration
# INSTEAD of the original 'name'. See the 'radutmp' configuration
# below for an example.
#

# PAP module to authenticate users based on their stored password
#
# As of 1.1.4, the "encryption_scheme" configuration should
# no longer be used. For backwards compatibility, it will still
# work as before, but we recommend that it is not used.
#
# The replacement is "auto_header = yes".
# For backwards compatibility, the default is "auto_header = no",
# but we recommend reviewing your use of the PAP module, based
# on the documentation in "man rlm_pap".
#
# The new capability in this module makes it MUCH easier to
# configure the server for multiple crypt/hash schemes, AND
# it supports more methods than before. Please read "man rlm_pap"
# for more detailed documentation.
#
pap {
encryption_scheme = clear
# auto_header = yes
}

# CHAP module
#
# To authenticate requests containing a CHAP-Password attribute.
#
chap {
authtype = CHAP
}

# Microsoft CHAP authentication
#
# This module supports MS-CHAP and MS-CHAPv2 authentication.
# It also enforces the SMB-Account-Ctrl attribute.
#
mschap {
authtype = MS-CHAP
#
# As of 0.9, the mschap module does NOT support
# reading from /etc/smbpasswd.
#
# If you are using /etc/smbpasswd, see the 'passwd'
# module for an example of how to use /etc/smbpasswd

# if use_mppe is not set to no mschap will
# add MS-CHAP-MPPE-Keys for MS-CHAPv1 and
# MS-MPPE-Recv-Key/MS-MPPE-Send-Key for MS-CHAPv2
#
#use_mppe = yes

}

# Preprocess the incoming RADIUS request, before handing it off
# to other modules.
#
# This module processes the 'huntgroups' and 'hints' files.
# In addition, it re-writes some weird attributes created
# by some NASes, and converts the attributes into a form which
# is a little more standard.
#
preprocess {
huntgroups = ${confdir}/huntgroups
hints = ${confdir}/hints

# Cisco (and Quintum in Cisco mode) sends it's VSA attributes
# with the attribute name *again* in the string, like:
#
# H323-Attribute = "h323-attribute=value".
#
# If this configuration item is set to 'yes', then
# the redundant data in the the attribute text is stripped
# out. The result is:
#
# H323-Attribute = "value"
#
# If you're not running a Cisco or Quintum NAS, you don't
# need this hack.
with_cisco_vsa_hack = no
}

# Livingston-style 'users' file
#
files {
usersfile = ${confdir}/users
acctusersfile = ${confdir}/acct_users
# preproxy_usersfile = ${confdir}/preproxy_users

# If you want to use the old Cistron 'users' file
# with FreeRADIUS, you should change the next line
# to 'compat = cistron'. You can the copy your 'users'
# file from Cistron.
compat = no
}

# Write a detailed log of all accounting records received.
#
detail {
# Note that we do NOT use NAS-IP-Address here, as
# that attribute MAY BE from the originating NAS, and
# NOT from the proxy which actually sent us the
# request. The Client-IP-Address attribute is ALWAYS
# the address of the client which sent us the
# request.
#
# The following line creates a new detail file for
# every radius client (by IP address or hostname).
# In addition, a new detail file is created every
# day, so that the detail file doesn't have to go
# through a 'log rotation'
#
# If your detail files are large, you may also want
# to add a ':%H' (see doc/variables.txt) to the end
# of it, to create a new detail file every hour, e.g.:
#
# ..../detail-%Y%m%d:%H
#
# This will create a new detail file for every hour.
#
detailfile = ${radacctdir}/%{Client-IP-Address}/detail-%Y%m%d

#
# The Unix-style permissions on the 'detail' file.
#
# The detail file often contains secret or private
# information about users. So by keeping the file
# permissions restrictive, we can prevent unwanted
# people from seeing that information.
detailperm = 0600

#
# Certain attributes such as User-Password may be
# "sensitive", so they should not be printed in the
# detail file. This section lists the attributes
# that should be suppressed.
#
# The attributes should be listed one to a line.
#
#suppress {
# User-Password
#}
}

#
# Many people want to log authentication requests.
# Rather than modifying the server core to print out more
# messages, we can use a different instance of the 'detail'
# module, to log the authentication requests to a file.
#
# You will also need to un-comment the 'auth_log' line
# in the 'authorize' section, below.
#
detail auth_log {
detailfile = ${radacctdir}/%{Client-IP-Address}/auth-detail-%Y%m%d

#
# This MUST be 0600, otherwise anyone can read
# the users passwords!
# detailperm = 0600
}

#
# This module logs authentication reply packets sent
# to a NAS. Both Access-Accept and Access-Reject packets
# are logged.
#
# You will also need to un-comment the 'reply_log' line
# in the 'post-auth' section, below.
#
detail reply_log {
detailfile = ${radacctdir}/%{Client-IP-Address}/reply-detail-%Y%m%d

#
# This MUST be 0600, otherwise anyone can read
# the users passwords!
detailperm = 0600
}

#
# Create a unique accounting session Id. Many NASes re-use
# or repeat values for Acct-Session-Id, causing no end of
# confusion.
#
# This module will add a (probably) unique session id
# to an accounting packet based on the attributes listed
# below found in the packet. See doc/rlm_acct_unique for
# more information.
#
acct_unique {
key = "User-Name, Acct-Session-Id, NAS-IP-Address, Client-IP-Address, NAS-Port"
}


# Include another file that has the SQL-related configuration.
# This is another file only because it tends to be big.
#
# The following configuration file is for use with MySQL.
#
# For Postgresql, use: ${confdir}/postgresql.conf
# For MS-SQL, use: ${confdir}/mssql.conf
# For Oracle, use: ${confdir}/oraclesql.conf
#
$INCLUDE ${confdir}/cakesql.conf

}


# Authorization. First preprocess (hints and huntgroups files),
# then realms, and finally look in the "users" file.
#
# The order of the realm modules will determine the order that
# we try to find a matching realm.
#
# Make *sure* that 'preprocess' comes before any realm if you
# need to setup hints for the remote radius server
authorize {
#
# The preprocess module takes care of sanitizing some bizarre
# attributes in the request, and turning them into attributes
# which are more standard.
#
# It takes care of processing the 'raddb/hints' and the
# 'raddb/huntgroups' files.
#
# It also adds the %{Client-IP-Address} attribute to the request.
preprocess

#
# The chap module will set 'Auth-Type := CHAP' if we are
# handling a CHAP request and Auth-Type has not already been set
chap

#
# If the users are logging in with an MS-CHAP-Challenge
# attribute for authentication, the mschap module will find
# the MS-CHAP-Challenge attribute, and add 'Auth-Type := MS-CHAP'
# to the request, which will cause the server to then use
# the mschap module for authentication.
mschap

#
# Read the 'users' file
files


cake_sql
}


# Authentication.
#
#
# This section lists which modules are available for authentication.
# Note that it does NOT mean 'try each module in order'. It means
# that a module from the 'authorize' section adds a configuration
# attribute 'Auth-Type := FOO'. That authentication type is then
# used to pick the apropriate module from the list below.
#

# In general, you SHOULD NOT set the Auth-Type attribute. The server
# will figure it out on its own, and will do the right thing. The
# most common side effect of erroneously setting the Auth-Type
# attribute is that one authentication method will work, but the
# others will not.
#
# The common reasons to set the Auth-Type attribute by hand
# is to either forcibly reject the user, or forcibly accept him.
#
authenticate {
#
# PAP authentication, when a back-end database listed
# in the 'authorize' section supplies a password. The
# password can be clear-text, or encrypted.
Auth-Type PAP {
pap
}

#
# Most people want CHAP authentication
# A back-end database listed in the 'authorize' section
# MUST supply a CLEAR TEXT password. Encrypted passwords
# won't work.
Auth-Type CHAP {
chap
}

#
# MSCHAP authentication.
Auth-Type MS-CHAP {
mschap
}

}


#
# Pre-accounting. Decide which accounting type to use.
#
preacct {
preprocess

}

#
# Accounting. Log the accounting data.
#
accounting {
acct_unique
#
# Create a 'detail'ed log of the packets.
# Note that accounting requests which are proxied
# are also logged in the detail file.
detail
# daily

cake_sql
}


# Session database, used for checking Simultaneous-Use. Either the radutmp
# or rlm_sql module can handle this.
# The rlm_sql module is *much* faster
#session {
# radutmp

#
# See "Simultaneous Use Checking Querie" in sql.conf
# sql
#}


# Post-Authentication
# Once we KNOW that the user has been authenticated, there are
# additional steps we can take.
post-auth {

#
# If you want to have a log of authentication replies,
# un-comment the following line, and the 'detail reply_log'
# section, above.
reply_log

}

#
# When the server decides to proxy a request to a home server,
# the proxied request is first passed through the pre-proxy
# stage. This stage can re-write the request, or decide to
# cancel the proxy.
#
# Only a few modules currently have this method.
#
#pre-proxy {
# attr_rewrite

# Uncomment the following line if you want to change attributes
# as defined in the preproxy_users file.
# files

# If you want to have a log of packets proxied to a home
# server, un-comment the following line, and the
# 'detail pre_proxy_log' section, above.
# pre_proxy_log
#}

#
# When the server receives a reply to a request it proxied
# to a home server, the request may be massaged here, in the
# post-proxy stage.
#
#post-proxy {

# If you want to have a log of replies from a home server,
# un-comment the following line, and the 'detail post_proxy_log'
# section, above.
# post_proxy_log

# attr_rewrite

# Uncomment the following line if you want to filter replies from
# remote proxies based on the rules defined in the 'attrs' file.

# attr_filter

#
# If you are proxying LEAP, you MUST configure the EAP
# module, and you MUST list it here, in the post-proxy
# stage.
#
# You MUST also use the 'nostrip' option in the 'realm'
# configuration. Otherwise, the User-Name attribute
# in the proxied request will not match the user name
# hidden inside of the EAP packet, and the end server will
# reject the EAP request.
#
# eap
#}


Далее переходим к clients.conf данный файл содержит конфигурацию о клиентах (NAS) работающих с RADIUS сервером.
clients.conf:

# секция описывает клиента c ip адресом 127.0.0.1.
# secret - секретное слово указывается еще на NAS желательно выбрать что-то отличное от test
# shortname - короткое имя используемое в качестве псевдонима.
# nastype - используется radcheck.pl т.е. внешним скриптом. В нашей системе оно используется.
# Поэтому выставленно other.
# Подобным же образом добавьте других клиентов.
client 127.0.0.1 {
secret = test
shortname = localhost
nastype = other
}

Скачиваем dictionary.ppp:

wget -c http://cakebilling.googlecode.com/files/dictionary.ppp

Редактируем dictionary:

#
# This is the master dictionary file, which references the
# pre-defined dictionary files included with the server.
#
# Any new/changed attributes MUST be placed in this file, as
# the pre-defined dictionaries SHOULD NOT be edited.
#
# $Id: dictionary.in,v 1.4 2004/04/14 15:26:20 aland Exp $
#

#
# The filename given here should be an absolute path.
#
$INCLUDE /usr/share/freeradius/dictionary
$INCLUDE /etc/freeradius/dictionary.ppp
#
# Place additional attributes or $INCLUDEs here. They will
# over-ride the definitions in the pre-defined dictionaries.
#
# See the 'man' page for 'dictionary' for information on
# the format of the dictionary files.

#
# If you want to add entries to the dictionary file,
# which are NOT going to be placed in a RADIUS packet,
# add them here. The numbers you pick should be between
# 3000 and 4000.
#

#ATTRIBUTE My-Local-String 3000 string
#ATTRIBUTE My-Local-IPAddr 3001 ipaddr
#ATTRIBUTE My-Local-Integer 3002 integer



ATTRIBUTE Acct-Interim-Interval 85 integer
ATTRIBUTE Session-Octets-Limit 227 integer
ATTRIBUTE Octets-Direction 228 integer

ATTRIBUTE PPPD-Upstream-Speed-Limit 230 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit 231 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-1 232 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-1 233 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-2 234 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-2 235 integer
ATTRIBUTE PPPD-Upstream-Speed-Limit-3 236 integer
ATTRIBUTE PPPD-Downstream-Speed-Limit-3 237 integer


Редактируем users:

DEFAULT Auth-Type:=Local


После этих изменений проверяем конфигурационные файлы:

root@cake# check-radiusd-config

вы должны получить аналогичный ответ:

root@cake# check-radiusd-config
Radius server configuration looks OK.

Создайте файл cakesql.conf содержащий:

sql cake_sql{
# Указываем драйвер для PostgreSQL
driver = "rlm_sql_postgresql"
# указываем PostgreSQL сервер.
server = "127.0.0.1"
# указываем логин к базе.
login = "cake"
# пароль который вы задавали при заведении пользователя cake.
password = "cake"
# Указываем базу.
radius_db = "cake"
# Создавать файл трассировки для SQL рапросов.
# Создается только при указании опции -x
sqltrace = yes
sqltracefile = /var/log/radius/sqltrace.sql
# Количество подключений к СУБД
num_sql_socks = 30
# Имя пользователя запрашиваемого в СУБД.
# Возможно применение регулярных выражений.
sql_user_name = "%{User-Name}"
# запрос на авторизацию. Если запрос возвращает ничего RADIUS считает, что такого пользователя нет
# и отдает Auth-Reject
authorize_check_query = "select * from cake.auth_check('%{SQL-User-Name}')"
# после успешной авторизации выполняется этот запрос который возвращает reply аттрибуты для пользователя.
# Они могут содержать лимиты для пользователя и сопутствующую информацию.
authorize_reply_query = "select * from cake.auth_reply('%{SQL-User-Name}')"
# запрос ведет запись alive пакетов сессии содержащих промежуточные значения использования ресурсов.
accounting_update_query = "select cake.acct_update('%{Acct-Unique-Session-Id}', %{Acct-Output-Octets},%{Acct-Input-Octets})"
# запрос ведет запись пакета начала сессии.
accounting_start_query = "select start_session('%{Acct-Unique-Session-Id}','%{SQL-User-Name}')"
# запрос ведет запись пакета конца сессии.
accounting_stop_query = "select stop_session(%{Acct-Input-Octets},%{Acct-Output-Octets},'%{Acct-Unique-Session-Id}')"
}

Снова запускаем check-radiusd-config. Если мы получили ответ:

Radius server configuration looks OK.

Проверяем работоспособность RADIUS сервера, вы должны увидеть нечто подобное:

radiusd -X
....
rlm_sql (cake_sql): Driver rlm_sql_postgresql (module rlm_sql_postgresql) loaded and linked
rlm_sql (cake_sql): Attempting to connect to postgres@127.0.0.1:/cake
rlm_sql (cake_sql): starting 0
rlm_sql (cake_sql): Attempting to connect rlm_sql_postgresql #0
rlm_sql (cake_sql): Connected new DB handle, #0
rlm_sql (cake_sql): starting 1
....
Если вы это не увидели проверьте доступность СУБД и т.п.
Далее уберите в radiusd.conf опцию auth_log в секции authorize, опцию detail в секции accounting и опцию reply_log в секции post-auth они не требуются в рабочем состоянии сервера. Поскольку будут только ухудшать призводительность сервера.
Запустите FreeRADIUS в рабочем режиме.

Тут не указаны некоторые операции проверки правильности функционирования. Для их проведения следует обратиться к документации CakeBilling.

2009-02-10

Проект по разработке ПО нового поколения для Fidonet

Объявлено о начале разработки проекта FNT - ПО нового поколения для сети Fidonet. Это программное обеспечение будет совместимо со старым на уровне inbound/outbound. Хранение будет осуществляться в SQL-базе, с узла почта будет раздаваться по специальному новому протоколу, приближая Фидо по времени отклика к Jabber.

Никто не станет спорить, что в настоящее время Фидо сильно отстаёт технологически. Однако концептуально это не так. На данный момент у Фидо нет достойного идеологического преемника. Вероятно, что его и не появится. Тем не менее, Фидо - реально существующая свободная альтернатива коммерциализированному и поглощённому корпорациями веб-пространству. Фидо по самому своему устройству не может служить иным целям, кроме интересов пользователей. Вопрос в том, как грамотно подойти к модернизации сети, не нарушив её целостности и не повредив её идеологической основы.

Данный проект является попыткой преодолеть отставание Фидо и вывести сеть на новый уровень. Автор проекта - Вячеслав Занько, известный тем, что воскресил Midnight Commander в виде отечественного форка. Более подробную информацию можно найти в wiki проекта и в тикетах.

Приглашаются желающие принять участие в разработке. Проекту особенно нужны люди, знающие FTN с точки зрения разработчика и хорошо ориентирующиеся в современных технологиях.

CakeBilling. Установка и настройка PostgreSQL.

Как и обещал, выкладываю последовательность действий при установке CakeBilling. Начинаем, как и в оригинальной инструкции, с установки и настройки PostgreSQL.

Установка PostgreSQL:

# apt-get install postgresql-8.3 // собственно сервер СУБД
# apt-get install libpg-java // JDBC-драйвер
# apt-get install libpg-perl // поддержка языка Perl

Переключаемся на пользователя postgres:
root@cake# su postgres

Добавляем нового пользователя cake в PostgreSQL:
postgres@cake$ createuser -P -D -A cake
Note: По умолчанию в веб-интерфейсе для доступа в базу используется login: cake, password: cake. Не забудьте изменить настройки web-интерфейса в случае выбора другого логина и пароля.

Создаём базу данных:
postgres@cake$ createdb -O cake cake (можно для верности добавить опцию -E UTF-8)

Добавляем язык хранимых процедур plpgsql:
postgres@cake$ createlang plpgsql cake

Загружаем и импортируем схему базы и начальные данные:
На странице http://groups.google.com/group/cakebilling/files надо взять файл cake-v1.0.1-UTF8.sql
postgres@cake$ psql -Ucake -W -d cake -f cake-v1.0.1-UTF8.sql

Проверяем права:
psql -Ucake cake -c "select * from cake.users;"

Закрываем сессию пользователя postgres:
postgres@cake$ exit

Релиз Debian GNU/Linux 5.0 "Lenny" выйдет 14 февраля

Вышел очередной выпуск Debian Project News от 9 февраля 2008 г. Среди главных новостей:

Adeodato Simó, on behalf of the release team, sent a release update [1]
about the upcoming release of Debian GNU/Linux 5.0 "Lenny", which might
be released during the weekend of 14 February 2009.


Т.о., релиз Debian GNU/Linux 5.0 "Lenny" ожидается в конце этой недели.

Finally he mentioned that a "Lenny-and-a-half" release is also planned, which will add drivers needed for newer hardware.

В связи с задержкой выхода последней версии Debian, также планируется релиз "Lenny-and-a-half" ("Lenny с половиной"), в который будут включены драйвера для поддержки новейшего оборудования.

2009-02-05

Обновление Java 6 update 12, представлена 64-разрядная сборка java плагина

Компания Sun Microsystems выпустила финальную версию двенадцатого обновления Java SE Runtime (JRE) 6 и Java SE Development Kit (JDK) 6, в котором зафиксировано 140 исправлений ошибок. В новой версии представлены новшества:

* Реализована 64-разрядная сборка java плагина, что позволяет использовать его в web-браузерах, собранных для 64-разрядных платформ;
* Добавлена поддержка платформы Windows 2008;
* Увеличена скорость запуска и работы JavaFX приложений;
* Увеличена производительность кода сглаживания графических элементов, заполнения областей, отрисовки прямоугольников и линий;
* Уменьшено время запуска Webstart приложений.

Отдельно подчеркивается, что в Java 6 update 12 отсутствуют связанные с безопасностью исправления.

2009-02-01

CakeBilling. Пролог.

Вроде разобрался сегодня с настройкой CakeBilling на системе с Ubuntu Server 8.04.1. В ближайшее время попытаюсь написать статейку (скорее цикл, ибо объем большой), в которой пройдусь по шагам установки и настройки CakeBilling в Ubuntu Server. Конечно, настройка не сильно отличается от приведенных в доке схем, но все же на поиск необходимых решений было потрачено время...

Основная ссылка: http://code.google.com/p/cakebilling/