Saturday, April 27, 2013

Modifying transfer contexts in FreePBX 2.10 higher or lower, and applying restrictions

(Image copyright PizzaHut Malaysia, QSR Brands)

Few days back, we dealt with a challenge to lock down phones in a callcenter of PizzaHut Malaysia. That was easy, we fired up a specialized context which I developed that uses Device User Mode based restriction. (If you wanna know more, about that, write me!). Now, we had a daunting task of getting the same kind of restrictions applied to user who perform transfers. By default, transfers are applied using the context “from-internal-xfer”. This is previously definable in FreePBX Advance settings, somehow it is now not available through the GUI. We had to make the same kind of restriction to those doing transfers too, so what we had to do, using Adminer (GUI database manager), look for a value in DB asterisk, table freepbx_settings called “from-internal-xfer”, for freepbx 2.10, look in asterisk DB, table, Globals, we changed that to “from-internal-xfer-phm”. Now, we forked the context out into our own little coding like here. Do note, after making changes in the DB, you need to make a change in the FreePBX gui, somewhere, and hit on the “Apply Config” button to materialize these changes.

To verify, run # asterisk –rx “dialplan show globals” and it should show you “TRANSFER_CONTEXT=from-internal-xfer-phm” or whatever you’ve called it.

Now that we are able to control transfers using our own context, we had to do it right and properly not to break other transfer functions with those whom are not bound by these restrictions.

In this example below, I have agents in Device Usermode, logged in as a 6XXX extension. What we are required to do is to not allow transfers using phone (button transfer) or even Asterisk code *2. Now, with the phone we had to modify the Asterisk SIP Setting and add a value like below, in the other SIP Setting;

allowtransfers=no

That fixed the phone transfers, no one can use transfers using SIP invites anymore directly. Cool.! Now, we force users to use *2 instead and when that code is pressed, the calls are being thrown to context [from-internal-xfer-phm]

In this context below, if any calls originating from 6XXX, retrieved from variable “PICKUPMARK” and is doing a transfer, looking at variable “TRANSFERNAME” which basically is populated when # transfers happen; we perform a soft hangup when those conditions are met, like below, otherwise, all others, we send back to the normal from-internal context, and basically allowing them to transfer it to wherever they like. , using this, you are free to write further more complex conditions as you please.

[from-internal-xfer-phm]
exten => _[4-6]XXX,1,ExecIf($["${PICKUPMARK:0:1}" = "6" & "${TRANSFERERNAME}" != "" ]?SoftHangup(Local/${EXTEN}))
exten => _X.,1,Goto(from-internal,${EXTEN},1)

 

Notes on the context above:

1) We catch calls in transfers made that start with digits 4 to 6, to digit “6” i.e. the call center agents. (We don’t want callcenter agents to call each other or in this case, transfer calls to each other)

2) It must be a transfer, i.e. must have the value TRANSFERNAME populated with something (With the two conditions above met, we do as below…, softhangup)

3) We softhangup the destination, i.e. EXTEN, causing the call to come back to the transferee

 

Have a good weekend folks!

Thursday, April 25, 2013

Asterisk –Debian based Asterisk 11, Freepbx 2.11 on VMware / Virtualbox (Asterisk VM/Asterisk Ready Virtual Machine)

Show some love,  do like our FB page www.fb.com/Astiostech |

[UPDATED: 03 FEB 2015]

Here’s a VMDK image to run a full featured Asterisk PaBX with FreePBX as the management UI using our default and secure install practices. No registrations, no username/password, no signing up for newsletter.

Get it from Sourceforge: https://sourceforge.net/projects/debianasterisk/[Select SWSterisk11 folder, then download the zip file therein]

 

After extracting, You either need VirtualBox or VMPlayer/VMWare or any Virtualization products that supports VMDK files or if you’re using Hypervisor, convert the image to VHD using MVMC from here.  This is to give you a feel of Asterisk with FreePBX without worrying about installation etc., its plug and play, literally. Just start up to your VirtualBox/VMplayer nd get it up and running in seconds. Go in to FreePBX and start creating extensions and enable other features. This image is free from any lockdowns or customizations that you cannot reverse or disable or enable as you wish. It is completely FREE from any personal restrictions. This image does not trace usage, or “dials home” or anything strange like that. Totally clean, totally lean and totally fast. It is functional and you can hook it up to a real production environment and you almost have a full fledge PBX, just add a Digium VoIP Gateway or another IP based PSTN.

IMPORTANT

  • While it is enterprise ready, it should rather be used for “playing” or “testing”….
  • DISCLAIMER: By using this VIRTUAL MACHINE IMAGE, i disclaim any sorts of liability whatsoever. What you do with this image is purely your choice/actions.
  • This is not "another disto", nothing proprietary, i don't claim any copyrights, just make it look and feel like its mine for fun, but of course any of those customizations can be reversed. All other trademarks are properties of their respective owners. All rights reserved.
Here’s some information about the VM image you just downloaded
  • It’s in ZIP compression, just get WinRAR or 7-ZIP to extract. After extracting, there should be one vmdk just mount the vmdk into VMWare/VMPlayer or Virtualbox and start the image
  • Username/password
  • OS
    - Username: root (the other non root user is swsterisk with same password as below)
    - Password: asteriskrocks (change this!)
  • FreePBX(admin), MySQL(root), AMI(admin): usernames and passwords;
    username: admin
    password: @steriskRocks1 (change this, here’s a good guide to start you off with http://www.freepbx.org/support/documentation/installation/first-steps-after-installation)
  • REMEMBER REMEMBER REMEMBER: CHANGE PASSWORDS!
  • The network adapter is set to auto on eth0.
  • Image needs at least 384M memory (or more if you have more)
  • All source files except kernel-headers are removed to save disk space for downloading, you need to download them manually
  • Be sure your image can access internet when starting otherwise NTP and EXIM will start slow, don’t blame me!

OS features/settings

  • Debian 6.0.7 64bit (Source AMD64 netinstall) – UPDATED, Bash Vulnerability Fixed with latest patch no33, SSLV3 disabled and Ghost Vulnerability fixed. All binaries are retrieved from Debian’s 6 LTS repos. So they are up to date.
  • The interface, extX, is set to use DHCP, so be sure to hook up DHCP or manually. In case you can’t bring the interface up, run #ifconfig –a . Then edit the file in /etc/network/interfaces and set all values to correspond to the interface shown when you run ifconfig –a (not loopback of course)
  • IPV6 disabled
  • MySQL backend (performance tuned)
  • Webmin installed but not started (# /etc/init.d/webmin start , then access using https://<ipaddress>:10000)  - UPDATED!
  • Apache as webserver with enforced HTTPS
  • MySQL administration with Adminer in https://<ipaddress>/dbmanager  - UPDATED!
  • DHCP and TFTP server downloaded, not installed
  • Firewalled with IPTables (be sure to see /bin/wallfire.sh) – UPDATED and fixed wallfire.sh script …can be stopped and started #wallfire stop #wallfire start
  • Time i.e NTP autosyncs with ntp.org daily, when starting and when stopping
  • Exim4 (mailserver) configured to relay, configure your email appropriately #dpkg-reconfigure exim4-config
  • fail2ban for Asterisk and SSH with enhancement to the log checking facility which includes asterisk security channel inside messages log (modify notification email here /etc/fail2ban/jail.conf) – UPDATED to 0.9.1!
  • Munin for monitoring in https://<ipaddress>/munin
  • Phpsysinfo for server information in https://<ipaddress>/phpsysinfo
  • Many CLI tools for troubleshooting like tcpdump, ntop, htop…
  • Astribank support [if ever u need it]
  • Removed VirtualBox OSE support to make it more cross platform compatible.
Asterisk features
FreePBX features
  • https://<ipaddress> to access FreePBX
  • FreePBX 2.11.0.38 (with only basic modules pre-installed) - UPDATED
  • Enhanced FreePBX security built in
  • SIP defaults to NAT yes (avoid all one way audio issue)
  • Security basic hardening in extensions
  • CEL support in FreePBX CDR
  • Enabled g729, speex and silk (enabled for IAX and SIP)
  • Most services are started with /etc/init.d/btelsvc

Additional reading

 

As usual do give me your feedback. ==> sanjay(the at symbol)astiostech.com

Thanks!
Sanjay Willie

Monday, March 4, 2013

Asterisk or FreePBX call alert script (e.g. for sudden spike in international calls) that runs independently or via Nagios (Nagios compatible)

Lets face it, some of us may have had our share of FreePBX/Asterisk compromises and abusers almost always use the facility to make international calls to exotic numbers. The bill at the end of the month is already too late and there’s significant monetary damage. While its good to know in realtime of what’s going on, its of course best to prevent anything to compromise your server. see this guide here to get you started.

Here’s a small script we wrote that works for me to check as often as cronjob/Nagios allows it to, based on the parameters you set and report back via email if the script is triggered.

This script here does the following;

  • It checks the CDR for n minutes of past records also set by flags
  • Uses filters based on the dst column on your CDR to match that you specify during execution (the parameters), this can be prefixes or whole numbers, and run multiple instances. 
  • You can set the flag to check the prefix and the number of digits which is same or greater so that you won’t catch local calls, normally international calls have higher number of called digits, i.e. > 10
  • To automatically check or do it almost realtime, you can use cron on your server locally (It can also work with Nagios too, however, this guide does not cover configuring on Nagios, set NAGIOSMODE=YES). If you set Nagiosmode, it will not independently send out email and instead your Nagios server will decide what to do according to what you’ve set it to.
  • Be sure to change SYSADMINEMAIL, FROMUSER,SERVER,PORT,DATABASE,TABLE,USER,PASS in the script relevant to your setup

Getting started:

  1. Copy paste this script below in /usr/bin/checkintl.sh (or any location of your choice)
  2. Modify the parameters as described below
  3. Make it executable (chmod +x /usr/bin/checkintl.sh)
  4. Put this script in a cronjob if you wish to automate checking (crontab –e), e.g. like this     */15 * * * * /usr/bin/checkintl.sh -w 5 -c 10 -i 30 -p 00:6,900:6"
    • Above cronjob does the checks for every 15 minutes 30 records in CDR and warns on 5 critical alerts on 10 for pattern 00, with length greater than or equals 6 numbers and for pattern 900 with length greater than or equals 6 numbers
  5. Test manually. You surely can run this manually and try to invoke the trigger by making n number of calls and you should get an email alert based on the email address you specified
  6. This script requires a MySQL CDR for Asterisk (therefore making it perfect for use with FreePBX, out of the box)
  7. IMPORTANT: THIS SCRIPT CHECKS AFTER ASTERISK WRITES TO CDR AND ALSO WHILE IN CALL COMBINED, SO CHECK BOTH PLACES

Set these below before running the script

  • The emailtoSYSADMINEMAIL, emailFROMUSER,SERVERip,serverPORT,cdrDATABASE,cdrTABLE,dbUSER,dbPASS
  • If using Nagios, just set the flag NAGIOSMODE=YES
  • Everything copied from below must be in a single line, no line breaks

Here’s the script, copy paste this as per item 1. getting started guide.

###PASTE START###

#!/bin/bash
RELEASE="Version 2"
AUTHOR="sanjay@astiostech.com"
PROGNAME="checkintl.sh"
#
# PRE-REQ
# – BASH 4.1.X or higher
# – FREEPBX and MYSQL of course
# - ASTERISK WITH CDR SUPPORT
# - ACCESS TO ASTERISKCDR DB
# – CLI tools like mail, awk, tr, curl,grep,mysql bin

# - ABLE TO SEND EMAIL OUT USING #mail with exim etc..
#
# ChangeLog
# - FIRST RELEASE
# - 1.1 Minor changes encapsulating output for compatibility
# - 2.0 Updated checking algorithm
#
# Place a cronjob, e.g. check every 5 minutes
# */15 * * * * /<locationofscript>/checkintl.sh
#
# NOTHING TO CHANGE HERE
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
USERDATEFORMAT=`date +%d-%m-%Y_%H:%M:%S`
#
########MODIFY HERE
########
NAGIOSMODE=NO
SYSADMINEMAIL=youradmin@yourdomain.com #add more separated by commas
FROMUSER=youruser@yourdomain.com
EMAILSUBJECT="CALL ALERTER – By Astiostech"
server="localhost"
port="3306"
database="asteriskcdrdb"
table="cdr"
user="<mysqluser>"
pass="<mysqlpass>"
########END MODIFY########
#
#
##FUNCTIONS
function sendoutmail()
{
( echo [$USERDATEFORMAT] - $2 ) | mail -aFrom:$FROMUSER -s "$EMAILSUBJECT" $SYSADMINEMAIL
return
}
#
print_release() {
    echo "$RELEASE $AUTHOR"
}
#
print_usage() {
    clear
    echo ""
    echo "$PROGNAME $RELEASE - Checks international calls"
    echo ""
    echo "Usage: checkintl.sh [flags]"
    echo ""
    echo "e.g  : ./checkintl.sh -w 5 -c 10 -i 30 -p 00:6,900:6"
    echo "Where it warns at 5 intl calls, and makes a critcal alert 10 calls at every 30 minutes "
    echo "of past CDR record for prefixes 00 and 900 combined total of equals to or higher than 6 digits"
    echo ""
    echo "Flags:"
    echo "  -w <number> : Warning value for number of international calls."
    echo "  -c <number> : Critical value for number of international calls"
    echo "  -i <number> : How many minutes of CDR data to poll to evaluate"
    echo "  -p <prefix:length,prefix:length,prefix:length> : Comma separated prefixes with IDD, e.g. 900:5,800:5,00:5. Length value is equals or higher. Default is 5 or higher chars"
    echo "  -h  Show this page"
    echo ""
    echo "Usage: $PROGNAME --help"
    echo ""
}
print_help() {
    print_usage
        echo ""
        echo "This plugin will check international calls made on Asterisk CDR"
        echo ""
    exit 0
}

# Parse parameters
while [ $# -gt 0 ]; do
    case "$1" in
        -h | --help)
            print_help
            exit $STATE_OK
            ;;
        -v | --version)
                print_release
                exit $STATE_OK
                ;;
        -w | --warning)
                shift
                WARNING_THRESHOLD=$1
                ;;
        -c | --critical)
               shift
                CRITICAL_THRESHOLD=$1
                ;;
        -i | --interval)
               shift
               INTERVAL=$1
                ;;
        -p | --prefix)
               shift
               PREFIXES=$1
                ;;
        *)  echo "Unknown argument: $1"
            print_usage
            exit $STATE_UNKNOWN
            ;;
        esac
shift
done
#
if  [[ "$WARNING_THRESHOLD" == "" ]]; then
    echo "Warning value not set, quitting.."
    exit $STATE_OK
fi
if  [[ "$CRITICAL_THRESHOLD" == "" ]]; then
    echo "Critical value not set, quitting.."
    exit $STATE_OK
fi
if  [[ "$INTERVAL" == "" ]]; then
    echo "Interval value not set, quitting.."
    exit $STATE_OK
fi
if  [[ "$PREFIXES" == "" ]]; then
    echo "You must define at least one prefix, quitting.."
    exit $STATE_OK
fi
#
# SET VARIABLES
warning_value="$WARNING_THRESHOLD"
critical_value="$CRITICAL_THRESHOLD"
interval="$INTERVAL"
PREFIX="$PREFIXES"
MYSQLBIN=`which mysql`
MYAST=`which asterisk`
#
# CONSTANTS
todate=`/bin/date`
unixtime=`/bin/date --date="$todate" +%s`
filename=mycdrlogforintl.$unixtime.txt
#
# DB CONNECTION CHECKER
checkdb=`$MYSQLBIN -b -n -N -s -h $server -P $port -u $user -p$pass -D $database -e "show databases;" | grep -c $database`
# START CHECKING CALLS
IFS=$OLDIFS
IFS=,
if  [[ $checkdb -lt 1 ]]; then
    echo "Error connecting to MySQL CDR DB"
    if [[ "$NAGIOSMODE" == "NO" ]]; then
        sendoutmail -f "Error connecting to MySQL CDR DB"
    fi
    exit $STATE_UNKNOWN
else
    for i in $PREFIX; do
        i=`echo $i | awk -F':' '{print $1}'`
        length=`echo $i | awk -F':' '{print $2}'`
        if [[ $length == 0 ]]; then
            length=5
        fi
        rawdata=`$MYSQLBIN -b -n -N -s -h $server -P $port -u $user -p$pass -D $database -e "SELECT dst FROM $table WHERE cdr.calldate > now() - INTERVAL $interval MINUTE and CHAR_LENGTH(dst) >= '$length';" | grep -o '[0-9]*' | grep -e '\<'$i'.*\>' | tr -d ' '`
        subtotal=`echo $rawdata | awk 'NF > 0' | wc -l`
        echo $rawdata >> /tmp/$filename
        ((totalcalls+=$subtotal))
    done
    for n in $PREFIX; do
        n=`echo $n | awk -F':' '{print $1}'`
        length=`echo $n | awk -F':' '{print $2}'`
        if [[ $length == 0 ]]; then
            length=5
        fi
        rawdata2=`$MYAST -rx "core show channels concise" |grep Outgoing | grep -e '\<'$n'.*\>' `
        if [[ "$rawdata2" != "" ]]; then
            subtotal=`echo $rawdata2 | awk 'NF > 0' | wc -l`
            echo $rawdata2 >> /tmp/$filename       
            ((totalcalls+=$subtotal))
        fi   
    done
IFS=$OLDIFS
fi
csved=`cat /tmp/$filename | tr -d ' ' | awk 'NF > 0' | tr "\n" ","`
#
# Now we start reporting to Nagios/sendmail if required
#
if [[ "$totalcalls" == "0" ]]; then
    echo "OK:$totalcalls |intl_calls=$totalcalls;$warning_value;$critical_value"
    exit $STATE_OK
elif [[ "$totalcalls" -ge "$critical_value" ]]; then
    echo "CRITICAL:$totalcalls LISTING:[START] $csved[END]|intl_calls=$totalcalls;$warning_value;$critical_value"
    if [[ "$NAGIOSMODE" == "NO" ]]; then
        sendoutmail -f "CRITICAL:$totalcalls LISTING:[START]$csved[END] | Critical threshold set: $critical_value"
    fi
    exit $STATE_CRITICAL
elif [[ "$totalcalls" -ge "$warning_value" ]]; then
    echo "WARNING:$totalcalls LISTING:[START] $csved[END]|intl_calls=$totalcalls;$warning_value;$critical_value"
    if [[ "$NAGIOSMODE" == "NO" ]]; then
        sendoutmail -f "WARNING:$totalcalls LISTING:[START] $csved[END] | Warning threshold set: $warning_value"
    fi
    exit $STATE_WARNING
else
    echo "TOTAL:$totalcalls LISTING:[START] $csved[END]|intl_calls=$totalcalls;$warning_value;$critical_value"
    exit $STATE_OK
fi

###PASTE END###

Tuesday, February 12, 2013

Asterisk/FreePBX Setting up and enabling Speex codec.

Why Speex?

  1. It works like SILK but, see item 2.
  2. Its an old codec thus supported by lots of phones as opposed to SILK

Environments (of course, improvise and modify for your respective OSes, it can run too far away from these)

  • Debian 6 32bit (somehow I messed up my 64bit or it doesn’t work well with 64 bit)
  • Asterisk 11
  • FreePBX

So the steps are simple as outlined here;

  1. # apt-get install speex speex libspeexdsp-dev libspeex-dev
  2. Go to your Asterisk source directory
  3. Do a #make clean && ./configure && make && make install
  4. NOTE: It should automatically notice Speex libraries are already installed and it will auto select, so don’t have to menu select whatnot.
  5. Once done make, restart Asterisk (#amportal kill && amportal start)
  6. Then you should be autoloading the codec, so # asterisk –rx “core show translation”     should show you speex

    speex 15000 15000 15000 15000 15000  9000 15000     -   23000 15000    15000 17250  17000   15000   23000  17000  17000  17000  17000  17000  17000   17000
    speex16 23500 23500 23500 23500 23500 17500 23500 23500       - 23500    23500 15000   9000   23500   23000  17500  17000  17000  17000  17000  17000   17000

  7. Otherwise, manually load #asterisk –rx “module load codec_speex.so”
  8. If you hit errors, lookout for the full log…
  9. Now, if speex is loaded properly, go to the IAX/SIP Setting pages in FreePBX and enable speex codec respectively
  10. That should now allow you to use speex in the extensions/devices you’ve configured

And you guessed, it, here’s the cliché, Enjoy Speex-ing…

More Asterisk related codec.conf configuration on Speex can be found here:

PS> What Codec we really want to consider in future and see it released to support Asterisk?.
OPUS. I believe this one codec will rule them all. Till then, we use bits like SILK and SPEEX and sometimes g729 to get our very cranky networks to play nice with VoIP audio.

Saturday, February 2, 2013

Setting up SILK Codec with Asterisk 10/11

Wikipedia on SILK: http://en.wikipedia.org/wiki/SILK
This guide takes you through the setup of SILK codec with Asterisk 11. It also can be used to setup Asterisk 10.
While it should work for other environments, this particular guide was written for
1) Debian
2) Working Asterisk 11 (try this article if you want a how-to)
Why use Skype’s SILK?
Here’s the quick how-to (Parts of this guide was taken from Asterisk Wiki here )
  1. Download the  benchmark tool based on your processor architecture. In my case I am using 64 bit so I downloaded the x86_64. Browse to http://downloads.digium.com/pub/telephony/codec_silk/benchsilk/ for options. Copy the URL and do the wget like below
    # cd /usr/src
    # wget
    http://downloads.digium.com/pub/telephony/codec_silk/benchsilk/x86-64/benchsilk-1.0.0-x86_64
    # chmod +x bench*
    # ./benchsilk-1.0.0-x86_64
  2. After this you will see the recommendation made from the benchmarking tool. Since I was running a VM for writing this, my winner was “generic”, so I headed to this http://downloads.digium.com/pub/telephony/codec_silk/ link, selected my Asterisk version, and selected the processor architecture, which was x86_64, then copied the generic codec url to do wget with
    # wget http://downloads.digium.com/pub/telephony/codec_silk/asterisk-11.0/x86-64/codec_silk-11.0_1.0.0-generic_64.tar.gz
    # tar –zxvf codec_silk*
    # cd codec_silk-11.0_1.0.0-generic_64     (or whatever version of yours directory name)
    # cp codec* /usr/lib/asterisk/modules/
  3. Now put up some configs for codecs.conf
    # nano /etc/asterisk/codecs.conf         (create the file if don’t exist). Paste below all variations this codec
    [silk8]
    type=silk
    samprate=8000
    fec=true
    packetloss_percentage=10
    maxbitrate=20000
    dtx=false

    [silk12]
    type=silk
    samprate=12000
    fec=true
    packetloss_percentage=10
    maxbitrate=25000
    dtx=false

    [silk16]
    type=silk
    samprate=16000
    fec=true
    packetloss_percentage=10
    maxbitrate=30000
    dtx=false

    [silk24]
    type=silk
    samprate=24000
    fec=true
    packetloss_percentage=10
    maxbitrate=40000
    dtx=false
  4. Save and exit
  5. Load the codec
    # asterisk -rx "module load codec_silk.so"
    You should see it return as “Loaded….”
  6. Now, check the translations and codecs
    # asterisk –rx “core show translation”
    # asterisk –rx “core show codecs”
  7. Sometimes, you might need to start and stop asterisk for it to show up in the codec translation table (and for it to work)
  8. On both command executions, you should see in those outputs the words SILK8, SILK12, SILK16, SILK24
  9. Be sure to “allow” this codec for each of your extensions, or sip general settings
    And for each extension, be sure to setup like this
    disallow=all
    allow=silk8 ;;;
    or whatever silk band you fancy, I use the narrowband as its important to use smallest bandwidth
  10. Connect using phones that support SILK, set those phones to only use SILK in its list of codecs based on the frequency you’ve “allowed”, in the case above, 8Khz. Typically, 8Khz band will only use 5-20kbps :)
  11. Checkout this document on the payload. The codecs.conf gives you the ability to tweak for poor network conditions too like on Wifi roamers….
Phones that support SILK in my tests:
  1. CSIPSimple for Android Mobile
  2. Basically anything using the PJSIP stack (which has become my favorite softphone….), e.g. http://microsip.org.ua/
Lots other phone vendors also do support SILK but it will probably come slower: Anyway, the PJSIP MicroSIP, I was making calls clean and flawlessly over Wifi
image

Thursday, January 17, 2013

Play listen 11 times on Asterisk to irritate caller..


This dialplan is to show how you can use the applicationmap feature in Asterisk to have an inband interruption during a call and force the caller (the other party) to hear something irritating like the word “listen” for 11 times while you listen to soothing music. This come from this forum youtube posting now Malaysian public enemy no .1 . The # in the instructions below means it’s a command you run on your linux box.
  • This is article is designed for FreePBX or adjust it for almost any Asterisk based distros…..
  • This article is to present how simple it is to do so much stuff on Asterisk…
  • This dialplan goes out to everyone in support of freedom of speech… :)
  1. Create an inband DTMF based code, e.g. here would be #9 by
    # nano /etc/asterisk/features_applicationmap_custom.conf
    Add this line below
    listenrant=>#9,peer/callee,Macro,listentome,s,1
  2. Now, create a dialplan in Asterisk
    # nano /etc/asterisk/extension_custom.confPaste like below
    [macro-listentome]
    exten => s,1,NoOp(Start to irritate you la)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,Playback(custom/listen)
    exten => s,n,NoOp(There ya go..)
  3. Now, enable the feature in globals
    # nano /etc/asterisk/globals_custom.confEdit or paste to include, if you have more than one applicationmap, separate it with a #
    DYNAMIC_FEATURES = listenrant
  4. Now reload stuff
    # asterisk -rx "dialplan reload"
    # asterisk -rx "features reload"
  5. Now, place this sound file in /var/lib/asterisk/sounds/customs, change directory where relevant and the user which asterisk process runs. These below are defaults
    # mkdir /var/lib/asterisk/sounds/custom
    # cd /var/lib/asterisk/sounds/custom
    # wget
    https://dl.dropbox.com/u/18507018/listen.sln
    # chown asterisk:asteirsk listen.sln
  6. Done. When someone calls you, to irritate them, just hit #9…..lol!

Saturday, January 12, 2013

Asterisk 10 or 11 Messaging (SMS/SIP Messaging) with offline message sending

Article revision: 3
If you read and tried my post here, you would have probably got the AstSMS working. It is important to get that part working first then read the rest of this article. This article enhances that dialplan to add offline sending of SIP message (or SMS) even if a host/SIP peer is offline and they will get the message once they come back online.
HOW IT WORKS
  • It uses Asterisk .call files to requeue
  • It checks device state using the function DEVICE_STATE to determine if a call is successful or not so that it can start/stop the queuing of the .call file
  • Runs a script within dialplan using the SYSTEM application to call a bash file with certain variables that will then auto generate the .call files
IMPORTANT
  • Since the messaging feature will automatically return OK if a device status is seen as online on Asterisk, irregarless of its actual state (probably qualify has not run yet to let asterisk know its offline). So to mitigate, reduce the qualifyfreq value on extensions sip.conf or general section.
  • I’ve not tested this in large setups or production environment. So please take caution and test.
  • DEVICE_STATE must exist/work in order for you to make this work too. E,g SIP/1000 should show me state of NOT_INUSE or UNAVAILABLE etc…Read more on DEVICE_STATES .
  • When sending messages, if there’s a break character, e.g. apostrophe, it will break the script since it runs on CLI and uses BASH, so you need to clean it up through Asterisk dialplan before sending to CLI/SYSTEM app
  • If multiple offline messages are bombarded at once, it may not be received in that order.
  • I don’t regard this as a final final solution, this would just give you an idea how to get to your final solution
  • I don’t enable CDR logs, but if you have CEL they may appear, you can re-enable it by modding NoCDR accordingly and change the priority accordingly too
  • Modify the bash script to suite your operating system, mine was designed for Debian
ENVIRONMENT (that worked for me)
  • Debian 6.0.x
  • Asterisk 10/11
  • FreePBX 2.10/2.11(Beta2) – If you don’t use FBX, modify and code accordingly
  • I had working DEVICE_STATES for SIP extensions
  • PortGo softphone as sender
  • CSIPSimple softphone on Android as recipient

HOWTO

  1. Create a temp spool folder wherever your Asterisk spool folder is at, this here is default, this will be used to spool the .call file temporarily
    # mkdir /var/spool/asterisk/temp
    # chown -R asterisk:asterisk /var/spool/asterisk/temp
  2. Create or modify your astsms context, to use this new one.  Everything should start with exten on single lines.

    [astsms]
    exten => _X.,1,NoOp(SMS receiving dialplan invoked)
    exten => _X.,n,NoOp(To ${MESSAGE(to)})
    exten => _X.,n,NoOp(From ${MESSAGE(from)})
    exten => _X.,n,NoOp(Body ${MESSAGE(body)})
    exten => _X.,n,Set(ACTUALTO=${CUT(MESSAGE(to),@,1)})
    exten => _X.,n,ExecIf($["${ACTUALTO}" != "sip:${EXTEN}"]?Set(ACTUALTO=sip:${EXTEN}))
    exten => _X.,n,MessageSend(${ACTUALTO},${MESSAGE(from)})
    exten => _X.,n,NoOp(Send status is ${MESSAGE_SEND_STATUS})
    exten => _X.,n,GotoIf($["${MESSAGE_SEND_STATUS}" != "SUCCESS"]?sendfailedmsg)
    exten => _X.,n,Hangup()
    ;
    ; Handle failed messaging
    exten => _X.,n(sendfailedmsg),NoOp(Sending error to user)
    exten => _X.,n,Set(SRC=${MESSAGE(from)})
    exten => _X.,n,Set(DST=${MESSAGE(to)})
    exten => _X.,n,Set(MSG=${MESSAGE(body)})
    exten => _X.,n,Set(MESSAGE(body)="[${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)}] Your message to ${EXTEN} has failed. Sending when available")
    exten => _X.,n,Set(ME_1=${CUT(MESSAGE(from),<,2)})
    exten => _X.,n,Set(ACTUALFROM=${CUT(ME_1,@,1)})
    exten => _X.,n,MessageSend(${ACTUALFROM},ServiceCenter)
    exten => _X.,n,GotoIf($["${INQUEUE}" != "1"]?startq)
    exten => _X.,n,Hangup()
    ;
    exten => _X.,n(startq),NoOp(Queueing messaging for offline)
    exten => _X.,n,Set(MSGTIME=${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)})
    exten => _X.,n,SYSTEM(/var/lib/asterisk/agi-bin/astqueue.sh –SRC ‘${SRC}’ –DST ‘${DST}’ –MSG ‘${MSG}’)
    exten => _X.,n,Hangup()
    [app-fakeanswer]
    exten => _X.,1,NoCDR
    exten => _X.,n,Set(DESTDEV=${EXTEN})
    exten => _X.,n,Set(THISDEVSTATE=${DEVICE_STATE(SIP/${DESTDEV})})
    exten => _X.,n,GotoIf($["${THISDEVSTATE}" = "UNAVAILABLE"]?hang)
    exten => _X.,n,GotoIf($["${THISDEVSTATE}" = "UNKNOWN"]?hang)
    exten => _X.,n,Answer
    exten => _X.,n,Hangup()

    exten => _X.,n(hang),Hangup()
  3. Now, here’s the magic script called astqueue.sh, create it like this
    # nano /var/lib/asterisk/agi-bin/astqueue.sh
    Paste this below, adjust the maxretry and retryint so that your Asterisk wont blow up in smokes and act like on steroids retrying like crazy

    #!/bin/bash
    # v0.2
    # copyleft Sanjay Willie sanjayws@gmail.com
    # SCRIPT PURPOSE: GENERATE SMS OFFLINE QUEUE
    # GEN INFO: Change variables sections
    ###########################################
    #
    #VARIABLES
    maxretry=100
    retryint=30
    #
    #CONSTANTS
    ERRORCODE=0
    d_unique=`date +%s`
    d_friendly=`date +%T_%D`
    astbin=`which asterisk`
    myrandom=$[ ( $RANDOM % 1000 )  + 1 ]
    #
    function bail(){
          echo "SMS:[$ERRORCODE] $MSGOUT. Runtime:$d_friendly. UniqueCode:$d_unique"
        exit $ERRORCODE
    }
    while test -n "$1"; do
        case "$1" in
            -SRC)
                source="$2"
                shift
               ;;
            -DST)
                dest="$2"
                shift
               ;;
            -MSG)
                message="$2"
                shift
               ;;
            -TIME)
                originaltime="$2"
                shift
               ;;             
    esac
    shift
    done
    #
    #
    if [[ "$source" == "" ]]; then
        echo "ERROR: No source. Quitting."
        ERRORCODE=1
        bail
    fi
    if [[ "$dest" == "" ]]; then
        echo "ERROR: No usable destination. Quitting."
        ERRORCODE=1
        bail
    fi
    if [[ "$message" == "" ]]; then
        echo "ERROR: No message specified.Quitting."
        ERRORCODE=1
        bail
    fi
    #
    # generate call file
    mydate=`date +%d%m%y`
    logdate=`date`
    #
    # Check to see if extension exist
    destexten=`echo $dest | cut -d @ -f1 | cut -d : -f2`
    ifexist=`$astbin -rx "sip show peers" | grep -c $destexten`
    if [[ "$ifexist" == "0" ]]; then
        echo "Destination extension don't exist, exiting.."
        ERRORCODE=1
        bail
    fi

    # If that conditions pass, then we will queue,
    # you can write other conditions too to keep the sanity of the looping

    filename="$destexten-$d_unique.$myrandom.call"
    echo -e "Channel: Local/$destexten@app-fakeanswer
    CallerID: $source
    Maxretries: $maxretry
    RetryTime: $retryint
    Context: astsms
    Extension: $destexten
    Priority: 1 
    Set: MESSAGE(body)=$message
    Set: MESSAGE(to)=$dest
    Set: MESSAGE(from)=$source
    Set: INQUEUE=1 "> /var/spool/asterisk/temp/$filename
    # move files
    chown asterisk:asterisk /var/spool/asterisk/temp/$filename
    chmod 777 /var/spool/asterisk/temp/$filename
    sleep 3
    mv /var/spool/asterisk/temp/$filename /var/spool/asterisk/outgoing/
    #
    ERRORCODE=0
    bail

  4. Change permission and ownership accordingly
    # chown asterisk:asterisk /var/lib/asterisk/agi-bin/astqueue.sh
    #chmod +X /var/lib/asterisk/agi-bin/astqueue.sh
  5. Try sending a message when the device is online, then try again offline. Then go back online and you should get the message.
  6. Do modify and enhance and do share if you found something interesting or bugs..er

Its already 4am here in Malaysia, …sleep now. Good luck and enjoy your weekend.

Tuesday, January 8, 2013

A basic IPTables (firewall) for just about anyone using Asterisk and FreePBX

Hi guys, developed this simple bash script that will enable and disable IPTABLES based firewall targeted to mainly Asterisk with FreePBX users.
NOTE:
  • This is a basic firewall, feel free to fine tune as much as you want.
  • IT may erase existing FW/IPTABLES rules you have but it does back it up to /root
  • It does not interfere with fail2ban if you are using fail2ban
  • You add this into a startup if you like but it is not formatted to the init format, you need to set that up yourself or include this script into any existing init.d script you may have
  • It only allows SSH from anywhere, rest are allowed internally
  • You can edit the file to set to allow anywhere access to other common protocols if you want
  • Make sure you define your internal network range, by default it will allow RFC1918 …
What are the default rules
  • SSH allow from any
  • HTTP/HTTPS, SIP(and RTP), IAX2, NTP, SSH, TFTP and DHCP (tftp and dhcp accepts both server mode and client mode)
  • For HTTP(insecure http) you need to uncomment inside the script to allow port 80
  • Outbound is unrestrictive
  • Uses default ports as defined by standards
  1. # nano astfw.sh
  2. Copy the script as below and paste into the file you just opened/created, save and exit
  3. # chmod +x astfw.sh
  4. # mv astfw.sh /bin/
  5. Try starting and stopping (MAKE SURE YOU CAN ACCESS CONSOLE IF SOMETHING BREAKS!!!!!!)
    /bin/astfw.sh start
    /bin/astfw.sh stop
  6. Add to an init.d script or edit the rc.local to start this automatically when booting


Copy these below…
#!/bin/bash
# sanjayws@gmail.com
# V.1.1 - Modded for our Asterisk installs, reldate 08-01-2013
# V.1.2 - Added enable disable functinality just incase
# iptables Asterisk related to stop start
# usage ./astfw.sh start[stop]
#
# IMPORTANT READ THIS NOW
# =======================
# ---BE SURE TO DEFINE WHAT IS YOUR INTERNAL NETWORK, BY DEFAULT ALL RFC1918 IPs ARE ALLOWED
# ---DO NOT USE OTHER 3RD PARTY IPTABLES MANAGEMENT SYSTEM WHEN USING THIS, E.G. WEBMIN
# ---There is a section below to define custom ports/rules for incoming, use that
# ---YOU CAN DISABLE ENABLE SCRIPT COMPLETELY NOW
#
# ---DEFAULT SERVICES INBOUND ALLOWED FROM ANYWHERE
# ++++SSH
#
# ---DEFAULT SERVICES INBOUND ALLOWED INTERNAL ONLY
# ++++HTTPS,IAX2,NTP,SSH,SIP(WITH RTP),TFTP (SERVER AND CLIENT MODE), DHCP(SERVER AND CLIENT MODE)
#
# ---DEFAULT SERVICES ALLOWED OUTBOUND
# ++++ANY
#
# ---DEFAULT SERVICES ALLOWED LOCALHOST
# ++++ANY
#
# --- EXISTING RULES WILL ALWAYS BE BACKED UP IN /root/fwrulesbackup.<datetime>
#
# USER DEFINITION
# ENABLE OR DISABLE,IF DISABLED, ONLY FAIL2BAN WILL RUN, YES[NO]
ENABLE=YES
#
# INTERNAL BY DEFAULT ACCEPTS RFC1918 IP RANGES. ADD NEW OR MODIFY NEW ONES BY ADDING COMMAS. DEFINE BY MASK BITS LIKE 192.168.100.0/24
INTERNALNETWORK="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"
#
# BY DEFAULT ONLY SSH IS ALLOWED FROM ANYWHERE, REST RESTRICTED INTERNAL ONLY, ACCEPTS 0 OR 1
allowextsip=0
allowextntp=0
allowextssh=1
allowextdhcp=0
allowexttftp=0
allowextiax=0
allowextweb=0
allowextntp=0

#
# Starting script here
if [[ "$ENABLE" == "YES" ]]; then
    mydate=`date +%d%m%y-%H%M%S`
    fw=`which iptables`
    fwsave=`which iptables-save`
    opt=$1
    if [[ "$opt" == "" ]]; then
        echo Command not specified, quitting
        exit
    fi
    if [[ "$opt" == "start" ]]; then

            echo "Starting firewall rules"
            echo "Backing up current rules to /root/filename"
            $fwsave > /root/fwrulesbackup.$mydate
            echo "Setting up defaults, clearing other rules"
            $fw -F INPUT
            $fw -F OUTPUT
            $fw -F FORWARD
            $fw -P INPUT ACCEPT
            $fw -P FORWARD ACCEPT
            $fw -P OUTPUT ACCEPT
            echo "Done sweeping"
            echo "Setting specific rules"
           
            #####INBOUND RULES#####
            # DEFAULT ALLOWED
            $fw -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
            $fw -A INPUT -p icmp --icmp-type 8 -s 0/0 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
            #
            if [[ $allowextsip == "1" ]]; then
                $fw -A INPUT -p udp -m udp --dport 5060:5062 -j ACCEPT
                $fw -A INPUT -p udp -m udp --dport 10000:20000 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 5060:5062 -j ACCEPT
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 10000:20000 -j ACCEPT
            fi
            if [[ $allowextiax == "1" ]]; then
                $fw -A INPUT -p udp -m udp --dport 4569 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 4569 -j ACCEPT       
            fi
            if [[ $allowextweb == "1" ]]; then
                $fw -A INPUT -p tcp -m tcp  --dport 443 -j ACCEPT
                #$fw -A INPUT -p tcp -m tcp  --dport 80 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p tcp -m tcp --dport 443 -j ACCEPT
                #$fw -A INPUT -s $INTERNALNETWORK -p tcp -m tcp --dport 80 -j ACCEPT
            fi
            if [[ $allowextssh == "1" ]]; then
                $fw -A INPUT -p tcp -m tcp  --dport 22 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p tcp -m tcp --dport 22 -j ACCEPT
            fi
            if [[ $allowextntp == "1" ]]; then
                $fw -A INPUT -p udp -m udp --dport 123 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 123 -j ACCEPT       
            fi
            if [[ $allowextdhcp == "1" ]]; then
                $fw -A INPUT -p udp -m udp --dport 67:68 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 67:68 -j ACCEPT       
            fi
            if [[ $allowexttftp == "1" ]]; then
                $fw -A INPUT -p udp -m udp --dport 69 -j ACCEPT
            else
                $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 69 -j ACCEPT       
            fi
          if [[ $allowextntp== "1" ]]; then
              $fw -A INPUT -p udp -m udp --dport 123 -j ACCEPT
          else
              $fw -A INPUT -s $INTERNALNETWORK -p udp -m udp --dport 123 -j ACCEPT       
          fi


            #
            #
            ###ADD YOUR CUSTOM INBOUND PORTS HERE
            # E.G. MYSQL, INTERNAL ONLY
            # $fw -A INPUT -s $INTERNALNETWORK -p tcp -m tcp --dport 3306 -j ACCEPT
            # E.G. MYSQL EXTERNAL AND INTERNAL
            # $fw -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
           
            #####OUTRULES#####
            #out stuff, currently none only defaults
            $fw -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
            $fw -A OUTPUT -j ACCEPT

            #loopallow, dont mess with this
            $fw -A INPUT -i lo -j ACCEPT
            $fw -A OUTPUT -s 127.0.0.1 -j ACCEPT       
                   
            #policy
            $fw -P INPUT DROP
            $fw -P OUTPUT DROP
            $fw -P FORWARD DROP   
            clear
            tput bel
            echo "Done - FIREWALL RUNNING - SECURED"
            exit 0

    elif [[ "$opt" == "stop" ]]; then       
            echo "Stopping firewall rules"
            echo "Backing up current rules to /root/filename"
            $fwsave > /root/fwrulesbackup.$mydate
            $fw -F INPUT
            $fw -F OUTPUT
            $fw -F FORWARD
            $fw -P INPUT ACCEPT
            $fw -P FORWARD ACCEPT
            $fw -P OUTPUT ACCEPT
            tput bel
            clear
            echo "Done - FIREWALL NOT RUNNING - INSECURE"
            exit 0
    else
            echo "Option not found, quitting"
            exit 1
    fi
    exit 0
   
else
    echo "Bypassing since flag set to ENABLE=$ENABLE"
    exit 0
fi

Friday, January 4, 2013

Asternic (2.0 earlier/later) and latest FreePBX 2.10 (or even 2.11) recording/playback via the GUI doesn’t show anymore after upgrading FBX or a new updated installation of FBX

Hi guys, had encountered an issue with Asternic and FreePBX’s latest Queue module which I noticed was version 2.10.07. Since I updated, the guide and .diff file provided by Asternic doesn’t work. So I had to do some hacks to get it sorted. I guess until Asternic team fixes the .diff file, here’s what you can quickly do to fix it.

IMPORTANT:

  • This only applies for queue module version 2.10.0.7 or newer, you can still use the .diff file provided by Asternic for older versions. If you follow the INSTALL file in the asternic tar.gz package, and when you patch, you don’t get errors, you are then still using the old version. If you do get errors, then you’ve installed the new version of the queue module.
  • If you upgraded/updated your FreePBX then suddenly recordings don’t work, well, then this updated new queues module is the issue.
  • If you ever upgrade the core/queues module after doing these steps below, you must redo step 1, every time you upgrade/update core/queues module in FBX
  • If you are installing Asternic for the first time on a FreePBX queue version 2.10.0.7 or higher, follow the steps detailed in Asternic’s “INSTALL” file up until the patch fpbxmixmon.diff, skip that part and do the parts below instead, to get straight to the fix, once done, continue the “INSTALL” file instructions per usual
  • The recordings after doing this hack below, will still show up in both Asternic and also in ARI

NOTICE

  • I believe in the new recordings formatting, the FreePBX team has probably done some cleanup in their codes to streamline recordings.
  • USE THIS AT YOUR OWN RISK! While I take precautions to use FBX standards and not to invoke changes to any other dialplans, things can go wrong, so test test test
  • NOTE: Improvise if needed, e.g. directory location etc.

 

Step 1 – Modify the FreePBX coding

# nano /var/www/html/admin/modules/queues/functions.inc/dialplan.php

Locate anywhere that says sub-record-check and replace it with sub-record-check-asternic

This is because, we will need to override this context to fit to Asternic’s fancy.

 

Step 2 – Create a MODIFIED sub-record-check macro to support Asternic recording format and post recording script.

# nano /etc/asterisk/extensions_override_freepbx.conf

Paste this below into that file. Please be aware of the location of MONITOR_EXEC script to match the location of yours. All single lines below, so ensure that when copying/pasting.

[sub-record-check-asternic]
exten => s,1,GotoIf($["${BLINDTRANSFER}" = ""]?check)
exten => s,n,ResetCDR()
exten => s,n,GotoIf($["${REC_STATUS}" != "RECORDING"]?check)
exten => s,n,Set(AUDIOHOOK_INHERIT(MixMonitor)=yes)
exten => s,n,MixMonitor(${MIXMON_DIR}${YEAR}/${MONTH}/${DAY}/${CALLFILENAME}.${MIXMON_FORMAT},a,${MIXMON_POST})
exten => s,n(check),Set(__MON_FMT=${IF($["${MIXMON_FORMAT}"="wav49"]?WAV:${MIXMON_FORMAT})})
exten => s,n,GotoIf($["${REC_STATUS}"!="RECORDING"]?next)
exten => s,n,Set(CDR(recordingfile)=${CALLFILENAME}.${MON_FMT})
exten => s,n,Return()
exten => s,n(next),ExecIf($[!${LEN(${ARG1})}]?Return())
exten => s,n,GotoIf($["${REC_STATUS}"!=""]?${ARG1},1)
exten => s,n,Set(__REC_STATUS=INITIALIZED)
exten => s,n,ExecIf($["${REC_POLICY_MODE}"="" & "${ARG3}"!=""]?Set(__REC_POLICY_MODE=${ARG3}))
exten => s,n,Set(NOW=${EPOCH})
exten => s,n,Set(__DAY=${STRFTIME(${NOW},,%d)})
exten => s,n,Set(__MONTH=${STRFTIME(${NOW},,%m)})
exten => s,n,Set(__YEAR=${STRFTIME(${NOW},,%Y)})
exten => s,n,Set(__TIMESTR=${YEAR}${MONTH}${DAY}-${STRFTIME(${NOW},,%H%M%S)})
exten => s,n,Set(__FROMEXTEN=${IF($[${LEN(${AMPUSER})}]?${AMPUSER}:${IF($[${LEN(${REALCALLERIDNUM})}]?${REALCALLERIDNUM}:unknown)})})
;exten => s,n,Set(__CALLFILENAME=${ARG1}-${ARG2}-${FROMEXTEN}-${TIMESTR}-${UNIQUEID})  ;;;MODIFIED LINE 1 -- THIS WAS THE ORIGINAL VERSION, ITS COMMENTED SO IT WONT EXECUTE
exten => s,n,Set(__CALLFILENAME=q${ARG2}-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${UNIQUEID}) ;;; MODIFIED LINE 2 -- THIS IS MY VERSION, COMPATIBLE WITH ASTERNIC
exten => s,n,Set(__MONITOR_EXEC=/usr/local/parselog/update_mix_mixmonitor.pl ^{UNIQUEID} ${MIXMON_DIR}${YEAR}/${MONTH}/${DAY}/${CALLFILENAME}.${MIXMON_FORMAT}) ;;; MODIFIED LINE 3 --THIS I ADDED

exten => s,n,Goto(${ARG1},1)

exten => recq,1,Set(AUDIOHOOK_INHERIT(MixMonitor)=yes)
exten => recq,n,Set(MONITOR_FILENAME=${MIXMON_DIR}${YEAR}/${MONTH}/${DAY}/${CALLFILENAME})
exten => recq,n,Set(__REC_STATUS=RECORDING)
exten => recq,n,Set(CDR(recordingfile)=${CALLFILENAME}.${MON_FMT})
exten => recq,n,Return()

exten => q,1,GosubIf($["${REC_POLICY_MODE}"="always"]?recq,1(${EXTEN},${ARG2},${FROMEXTEN}))
exten => q,n,Return()

Step 3 – Make any change in FreePBX and it should all work again Smile

- Click submit to anything and click Apply Conf

- Try to make calls and see ..

 

Additional stuff

Below is the parselog file I used that worked, be sure to find out AND CHANGE where your LAME app is in. In this case (Debian) lame was in /usr/local/bin/lame

A working parselog file. Click here. IT SHOULD BE THE SAME AS THE Original but yea…Please follow the configuration guide from Asternic for the parselog file.

Outbound call recording should work without any issues if you follow Asternic’s guide as it doesn’t interfere with FreePBX core coding through php, it uses the [macro-dialout-trunk-predial-hook] that doesn’t get directly modified in FreePBX gui.

 

Here’s my screenie of the before and after, notice before I hadn’t had recording, now with the above steps 1-3, it works again, yay

image

 

Bonus

If you got files that were not converted due to this issue above, here’s a dirty way how to get it working again on Asternic

1) Go to each directory containing the .wav file and run this code (For Debian 6 only, use on other OSes at your own risk)

# cd /var/spool/asterisk/monitor/2013/01/01/

# for i in `ls -l | awk {'print $9'}`; do uniqwav=`echo $i | cut -d - -f6 `;  uniqueid=`echo ${uniqwav//.wav/}`; /usr/local/parselog/update_mix_mixmonitor.pl $uniqueid `pwd`/$i; done

Tuesday, December 25, 2012

PortGo SIP softphone with Asterisk 11

Something weird with Asterisk 11 and portGo that drove me nuts and finally figured the damn thing out.

So here’s my issue, when I use Asterisk 11 and port go, calls signaling can work but as soon as audio is to be transmitted, it hang up the call. After debugging on Asterisk, found that it was a remote disconnection request. Then it was obvious it is something to do with RTP, so I went into PortGo’s setup and click on Misc there was the RTP setting. I had to manually set the RTP setting there to something like 12000 to 12020, or whatever range of your fancy. And now it works, damn..

image