20.12.2018

sox asterisk wav mp3

Хорошая статья по теме конвертации в mp3 для centos7. 

у меня лично возникла проблема со входящими файлами wav почему-то – sox не видел данных в них, пришлось явно указывать.

скрипт для конвертации всех файлов в каталоге в mp3

#!/usr/bin/perl
use strict;
use Proc::PID::File;

if (Proc::PID::File->running()) {
        print "Already running, exiting now\n";
        exit(0);
}


my @monitor_dirs=("/var/spool/asterisk/monitor");

foreach my $monitor_dir (@monitor_dirs) {
    opendir(my $dh,$monitor_dir) or die ("Cannot open dir $monitor_dir");
    print "Processing dir $monitor_dir\n";
    while (my $file=readdir($dh))  {

        next if $file !~m/\.wav$/;
        print "Processing file $file\n";
        my $newfile=$file;
        $newfile=~s/\.wav$/\.mp3/;

        system ("/usr/local/bin/sox -t raw -r 8000 -b 16 -e signed-integer  $monitor_dir/$file -t mp3 -C32 $monitor_dir/$newfile");
        sleep(0.01);
        if (-e "$monitor_dir/$newfile") {
            print "Coneverted sucessfully $file\n";
            unlink "$monitor_dir/$file";
        }

    }
    closedir($dh);
}

10.12.2018

migrate freepbx inaflash to issabel 2.11

update: После действий необходимо проверить IVR и какие outbound_trunk  включены или выключены. 

автоматический перенос не возможен, но вполне возможно перенести основные данные через таблицы, для этого нужно:

  1. развернуть дам базы данных freepbx в новую базу данных на машине, где расположен issabel, например в test_aster
  2. дополнить удалить колонки в старой базе данных:  

alter table test_aster.fax_users add column faxattachformat varchar(10);
alter table test_aster.incoming drop column faxexten;
alter table test_aster.incoming drop column faxemail;
alter table test_aster.incoming drop column answer;
alter table test_aster.incoming drop column wait;
alter table test_aster.queues_config add column destcontinue varchar(50);
alter table test_aster.queues_config add column callback_id varchar(8);
alter table test_aster.ivr_details add column timeout_ivr_ret tinyint(1);
alter table test_aster.ivr_details add column invalid_ivr_ret tinyint(1);
alter table test_aster.ivr_details drop column timeout_enabled;
alter table test_aster.timeconditions add column timeconditions varchar(50);

Теперь можно копировать данные из этих таблиц простым запросом:

insert into asterisk.ivr_entries select * from test_aster.ivr_entries;

Список таблиц которые надо скопировать, все таблицы копировать я полагаю нельзя, т.к. в них содержится конфигурация всей системы – это может привести к неисправимым поломкам в GUI. 

insert into asterisk.announcement select * from test_aster.announcement;
insert into asterisk.cidlookup select * from test_aster.cidlookup;
insert into asterisk.cidlookup_incoming select * from test_aster.cidlookup_incoming;
insert into asterisk.daynight select * from test_aster.daynight;
insert into asterisk.devices select * from test_aster.devices;
//directory tables not found in issabelPBX maybe we have to install directory module;
insert into asterisk.fax_users select * from test_aster.fax_users;
//featurecodes table is present and seems we don’t need to update it
//freepbx_users not in issabel maybe we have to install it
//hotelwakeup_calls not in issabelPBX
insert into asterisk.incoming select * from test_aster.incoming;
insert into asterisk.ivr_details select * from test_aster.ivr_details;
//outbound_route_patterns linked with route_id so it maybe differend between systems
insert into asterisk.outbound_route_patterns select * from test_aster.outbound_route_patterns;
insert into asterisk.outbound_routes select * from test_aster.outbound_routes;
insert into asterisk.paging_groups select * from test_aster.paging_groups;
insert into asterisk.queues_config select * from test_aster.queues_config;
insert into asterisk.queues_details select * from test_aster.queues_details;
insert into asterisk.recordings select * from test_aster.recordings;
insert into asterisk.ringgroups select * from test_aster.ringgroups;
insert into asterisk.sip select * from test_aster.sip;
//superfectaconfig tables not present maybe we have to install module superfecta
insert into asterisk.timeconditions select * from test_aster.timeconditions;
insert into asterisk.timegroups_details select * from test_aster.timegroups_details;
insert into asterisk.timegroups_groups select * from test_aster.timegroups_groups;
insert into asterisk.trunks select * from test_aster.trunks;
insert into asterisk.users select * from test_aster.users;

6.12.2018

firewalld asterisk fail2ban

На centos 7 по умолчанию используется firewalld и возникла проблема с тем что fail2ban не банит после неуспешных попыток авторизации и звонков

проблемы тут 2:

Первая это сами правила которыми пользуется  fail2ban чтобы банить, я их заменил на 

actionban = firewall-cmd –direct –add-rule ipv4 raw PREROUTING 0 -s -j DROP && firewall-cmd –change-source= –zone=block && firewall-cmd –change-source= –zone=block –permanent

actionunban = firewall-cmd –direct –remove-rule ipv4 raw PREROUTING 0 -s -j DROP && firewall-cmd –change-source= –zone=block && firewall-cmd –change-source= –zone=block –permanent && firewall-cmd –remove-source= –zone=block && firewall-cmd –remove-source= –zone=block –permanent 

Вторая это то, что firewalld разрешает все соединения которые были установлены и остались в таблицах, посмотреть их можно командой iptstate

решается первым правилом 
firewall-cmd –direct –add-rule ipv4 raw PREROUTING 0 -s -j DROP 

Которое добавляет блокировку пакетов до проверки ESTABLESHED,RELATED

А третья проблема была в фильтре fail2ban который смотрит для регистраций accountID, и по мнению fail2ban он может быть только числовым или <unknown> 

решается изменением регулярного выражения accountID = “(.+)” в фильтрах fail2ban. 

18.09.2018

asterisk freepbx wss webrtc issue

Команда для проверки установления TLS соединения, показывает информацию о сертификате и ошибки. 

openssl s_client -connect xxx.xxx.xxx.xxx:8089 -bugs

ошибка на астериске выдавала:

TLS non-recoverable I/O error occurred: error:00000005:lib(0):func(0):DH lib, System call EOF

Также в

Оказалось, просто истёк сертификат:

verify error:num=10:certificate has expired

но в через ssldump Этого не увидеть, там будет просто “S>C Alert” хотя абсолютно точно можно было посмотреть информацию о сертификате и понять это:

openssl x509 -in certificate.crt -text -noout

11.09.2018

Как Астериск распределяет входящие звонки:

link to original

link to original answer

Incoming SIP Connections When Asterisk receives an incoming SIP call, the SIP Channel Module

  • first tries to find a [user] section matching the caller name (From: username),
  • then tries to find a [peer] section matching the caller’s IP address.

If no matching user or peer is found, the call is sent to the context defined in the [general] section of sip.conf.sip.conf.

5.07.2018

Kamailio. topos. topology hiding. bug.

В kamailio обнаружился баг с модулем topos. Проявляется так: Если во время звонка случается re-invite от клиента, то сообщения BYE обрабатываются некорректно. Этот BYE отправляется не дальше клиенту, а остается на kamailio, сам kamilio при этом выдает “Not here” и точка. Клиент не получает BYE в следствие чего звонок на конечной точке зависает.

Связано это с модулем topos который позволяет скрывать топологию сети после прохождения через sip-proxy. сам по себе модуль очень хорош – его достаточно загрузить и никаких настроек не надо.
но вот багесть. Разработчик уже поправил в исходном коде, но в пакеты пока не попал…

24.06.2018

скорость перерегистрации телефонов на asterisk issabel

через веб интерфес добавляешь в sip_general_custom.conf:

defaultexpiry=30
minexpiry=20
maxexpiry=40

таким образом если телефон настроен на 3600, то время будет уменьшено до 40 секунд.

31.05.2018

tftp ports provisioning

Специфика протокола TFTP такова, что получая запрос на 69 порт, сервер будет отправлять ответы со случайных портов. Клиент находящийся за любым роутером может и не воспринять такой трафик.
Штатный tftpd не может приниматься запросы на 69 и отправлять с него.
Удивительно но не особо кто с такой проблемой сталкивается, вероятно потому, что роутеры должны уметь работать с TFTP протоколом, но нет.
Итак решение установить opentftpd сервер.

Для centos 7 мне пришлось его скомпилировать, что заняло 1 сек.
Затем, скопировав файл с настройками в /etc сервер запускается и работает только через порт 69.

30.05.2018

Cisco 7911 Asterisk Issabel

Надо было организовать provisioning для cisco 7911.
Сама по себе процедура описана много где хорошо. Принцип работы: Телефон при загрузке запрашивает файлы с конфигурацией у tftp сервера.
Изменить TFTP сервер на 7911 так:
Enter Menu,
Press ( **# ) to make setting editable,
Settings → Network → IP4 → Alternate TFTP (YES),
Settings → Network → IP4 → TFTP Server (111.111.111.111),
Press ( **#** ) to restart phone.

Настройки файла можно найти в статье. В приложенном архиве рабочая конфигурация.
PS: Мне удалось настроить работу только по протоколу TCP. По UDP есть подозрение, что циско слишком умная, описание проблемы с UDP здесь

25.04.2018

AWK ASTERISK CSV

Получить все звонки длительностью болье 3900 секунд.

awk ‘{FS=”,”; if ($16 > 3900) print $0}’ Master.csv > long