Friday, February 23, 2007

These are step by step very simple instructions to help most people to build

Tutorial on SIP and SIP SER server Installation of SER.

I would like to present three installation options:

· Follow the steps below using Red Hat Fedora Core 1 and rpm files. This is possibly getting a little old now (2006)

· FreeBSD comes with SER as an installable option, just tick the box.

· I have done some testing using Fedora Core 4 using the same steps as below
and compiled SER from www.openser.org and it seams to be the same as the
following.

These are step by step very simple instructions to help most people to build
a SER Server starting with a PC.

Linux Kernal using RedHat's Open Source "Fedora

Core 1"

The following instructions are based on building a Unix server using typical PC Intel i386 based hardware.

IMPORTANT NOTE: Fedora Core 1 does not support Intel PCs using Serial ATA Harddisks, and recent testing shows that SER does not run on Fedora Core 2.

  1. Follow the instructions at http://fedora.redhat.com/download/
    1. Download the three ISO images for Fedora Core 1 (not 2), also called
      "yarrow" from Red Hat.
      http://download.fedora.redhat.com/pub/fedora/linux/core/1/
    2. Create three CDROMs using the three ISO images.
  2. Insert Fedora Core 1 CD 1 and boot from CD
    1. Press Enter at boot screen to start setup
    2. When prompted to do the Media Test you can select Skip if you are confident your media is OK
    3. On the Fedora Core welcome screen, select Next
    4. Select English (English) as your language and press Next
    5. Select your keyboard type and press Next
    6. Select your mouse type and press Next
    7. If you have an existing Redhat Linux installation on the computer
      the Fedora installer will find this installation and ask you if you
      want to Upgrade the existing installation or perform a refresh installation
      of Fedora Core. If this is the case, select Install Fedora Core and
      press Next
  3. We want to do a Server installation of Fedora Core so select Server and press Next

  1. Select Manual partition with Disk Druid and press Next
    1. Delete any existing disk partitions so that your whole disk is Free Space
    2. For simplicity we will make 3 partitions, one swap partition, one boot partition and one big root partition
    3. Create a "Swap" partition to be 2 or 4 times the size of your available memory
      1. Click New
      2. Select swap as the File System Type
      3. In the Size (MB) text field enter the size of your swap partition.
        As a guide, set the swap partition to be 2 or 4 times the size of your available memory. As an example, my computer has 256Meg RAM, so I will set a 1Gig swap
      4. Under Additional Size Options select Fixed Size
      5. Ensure Force to be a primary partition is not selected and press OK
    4. Create a "/boot" partition with a File System Type of etx3 with 100Mbytes
      1. Click New
      2. In the Mount Point text field enter /boot to be an ext3 type of 100Meg.
      3. Select ext3 as the File System Type
      4. In the Size (MB) text field enter the size of your boot partition. This partition should be at least 50Meg, and a good size is usually
        100Meg.
      5. Under Additional Size Options select Fixed Size
      6. Select Force to be a primary partition and press OK
    5. Create a "/"
      root partition with the remained of the disk
      (Optional would be to create a /var partition for the logs to go)
      1. Click New
      2. In the Mount Point text field enter /
      3. Select ext3 as the File System Type
      4. Under Additional Size Options select Fill to maximum allowable size to use the remainder of the disk
      5. Ensure Force to be a primary partition is not selected and press OK
      6. Now you have setup your partitions press Next
  2. Select GRUB as the boot loader and press Next
  3. Next you will need to setup the network device of your machine. The information you enter here will vary depending on your environment
    1. Select eth0 device and press Edit
    2. Deselect Configure using DHCP - you want to configure a fixed ip address
    3. Select Activate on boot
    4. Enter your IP address
    5. Enter your Netmask
    6. Press OK
    7. Set the hostname manually
    8. Enter Gateway IP address.
    9. Enter Primary DNS IP address - For the Tutorial you may need to change it to simulate the SRV records, probably 169.222.239.2
    10. Enter Secondary DNS IP address if available
    11. Enter Tertiary DNS IP address if available
    12. Press Next
  4. Select No firewall and press Next
    1. Press Proceed on the warning screen about a firewall, you can setup a proper firewall later on
  5. Select the Default language for your system and press Next
  6. Select your timezone and press Next
  7. Enter your desired Root Password and Confirm and press Next
  8. This document assumes that this server will be dedicated to be your SIP server and so we will remove some packages that are not needed by your SIP server. For the purposes of the APAN SIP tutorial we will install Xwindows so you have a graphical interface with a browser to access the serweb tool. (Xwindows is not normally needed for your SIP server)
  9. Under Desktops select X Window System and click Details (far right side of X Window System
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      XFree86-twm
      Xfree86-xdm
      firstboot
      gdm
      rhgb
      xterm
  1. To install a decent Window Manager, under Desktops select your Window Manager of choise, either GNOME or KDE and install your required packages.
    For the purposes of the APAN SIP tutorial we will install we will install KDE.
  2. Under Desktops select KDE Desktop Environment and click Details
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      kdeadmin
      kdenetwork
      kdeutils
  3. Under Applications select Editors and click Details
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      vim-enhanced

      emacs
  4. Under Applications select Graphic Internet and click Details
    • Ensure only the following packages are installled (for a small installation although you can add more):
      mozilla

  1. Under Applications deselect Text-based Internet
  2. Under Servers click Details for Server Configuration Tools
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      Xfree86-xauth

  3. Under Web Servers click Details for
    Web S
    • Ensure only the following packages are installed (for a small installation although you can add more):
      httpd-manual
      php
      php-mysql
  4. Under Servers deselect Windows File Server
  5. Under Servers select SQL Database Server and click Details
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      mysql-server

  1. Under Development select Development Tools and click Details
    • Ensure only the following packages are installed (for a small installation although you can add more):
      rpm-build
  2. Under Development select Network Servers and click Details
    • Ensure only the following packages are installed (for a small installation
      although you can add more):
      freeradius
      tftp-server
  3. Under System deselect Administration Tools
  4. Under System select System Tools and click Details
    • Ensure only the following packages are installed (for a small installation although you can add more):
      ethereal
      nmap
      screen
  5. Under System deselect Printing Support
  6. We are now ready to continue with the installation.
    • Click Next
  7. The installation will now check for dependencies, but there shouldn't be any for our installation as above
    • Click Next again
  8. The required media will be listed in a popup dialog box, click Continue
  9. The installation will now proceed by formatting the required filesystems, transferring the install image to the hard drive, and then installing the
    selected packages.
  10. You will be prompted to insert the required media at different times throughout
    the installation. When prompted, insert the required media and press OK.
  11. When prompted to reboot, remove the installation media and press Reboot
  12. You have now installed a system that will run as a SER SIP Server for the APAN SIP Tutorial

#
# ENABLE ALL THE FOLLOWING SERVICES TO START AUTOMATICLY ON RELOAD OF SERVER
Use the programme "ntsysv"
# enable these:
# http
# mysql
# radiusd
# tftp

Step by Step Installation of SER on RedHad Fedora Core 1

The following has been tested on a RedHat Fedora Core 1 install as per instructions and is based on SER version 0.8.12

Key to the colours used:

Pink indicates a command or a filename
Red indicates something specific to your SER Server,
do not just put in the example

rpm -i ser-0.8.12-0.i386.rpm 

Start

/etc/rc.d/init.d/ser start

Do some environmental changes

export SIP_DOMAIN="aarnet.edu.au"

    • Edit /etc/profile and add the following line (same as above) onto the end of the file:

export SIP_DOMAIN="aarnet.edu.au"
Note I used an IP address here to make it work.

  • Get the SER mysql module, configure the install, install it, configure
    SER and restart SER

from SER or from this server

    • Install mysql
      rpm -i ser-mysql-0.8.12-0.i386.rpm
    • Start
      /etc/rc.d/init.d/mysqld start
    • If you wanted to you could make some changes, not recommended for first build, in the following file:
      • Edit /usr/sbin/ser_mysql.sh, the following may want to be changed, I just leave them as is
        DBHOST=localhost
        USERNAME=ser
        DEFAULT_PW=heslo
        ROUSER=serro
        RO_PW=47serro11
        SQL_USER="root"
        DEFAULT_PW=heslo
        # DEFAULT_PW is the password used by serctl to add users etc!
        Note:
        If you change the DEFAULT_PW password then you must add something to ser.cfg add

modparam("usrloc|other_modules_using_db", "db_url",
"mysql://ser:otherpassword@localhost/ser")


    • Run the SER script to create the SER database in mysql. IMPORTANT NOTE : You need to change your path statement in your shell environmentals to find the HA1 programme, personally I just ssh on as root and it runs fine.
      /usr/sbin/ser_mysql.sh create
      Notes: MySql password for root: BLANK
      Domain (Realm) is the domain name for the SIP users: aarnet.edu.au Second password: BLANK
    • Enter mysql and check that the tables have been created, follow these commands:
      mysql
      connect ser;
      show tables;
      select * from subscriber;
      exit
    • Copy the original SER configuration file and edit ser.cfg.
      • cp /etc/ser/ser.cfg /etc/ser/ser.cfg-original
      • Now edit the /etc/ser/ser.cfg /etc/ser/ser.cfg to make it do what you want it to. Here is a good guide: http://mit.edu/sip/sip.edu/ser.shtml.
    • Restart SER so that the changes take effect
      /etc/rc.d/init.d/ser restart
  • Create two users using serctl. IMPORTANT NOTE : YOU MUST BE LOGGED IN AS ROOT (NOT JUST sudo) or fix up the path statement in your shell. Format of the command is: serctl add <username> <password> <email> and you need to use the DEFAULT_PW=heslo as the password set in /usr/sbin/ser_mysql.sh
    /usr/sbin/serctl add srk password Stephen.Kingham@aarnet.edu.au
    /usr/sbin/serctl add
    caf password Clayton.Forbes@aarnet.edu.au

change password to the password that will be used by the user, do not use password as a password!

  • Test the connection using two SIP UAs.
    • See the examples of how to configure UAs.
    • Use the this command to see who is logged in:
      serctl ul show
  • Configure mysql so that it only listens to local requests and increase the maximum number of sessions:
    • edit /etc/my.cnf
      Change the start of the file so that it has these extra lines:
      [mysqld]
      datadir=/var/lib/mysql
      socket=/var/lib/mysql/mysql.sock
      set-variable = max_connections=500
      bind-address=127.0.0.1
    • Restart mysql
      /etc/rc.d/init.d/mysql restart
  • Create a special user for SER to run as, rather than running it as root.
    • Use the following command to create the new user in Unix:
      /usr/sbin/useradd -c "SER" -u 494 -s
      /sbin/nologin -r -d /usr/lib/ser ser
    • Now tell SER to run as the user ser by adding these lines into /etc/ser/ser.cfg:
      uid=ser
      gid=ser
    • Delete the old fifo file otherwise the new user "ser" may not be able to use it
      rm /tmp/ser_fifo

Step by Step Installation of WEBSER on RedHad Fedora Core 1

When the original distribution is installed the directory locations do not match up with the typical apache file locations. These notes document all the changes needed. SUGGESTION: For the Tutorial we should develop a new install TAR so delegates do not spend 30 minutes editing all the files.

  • Get the TAR, un-tar and place the files in the right directory
    • from SER or from this server
    • untar
      tar -xvzf serweb_2004-01-04.tar.gz
    • change directory to where the files were untared to
      cd serweb_2004-01-04
    • Create the directory and move the files there
      mkdir /var/www/phplib
      chown root /var/www/phplib
      chgrp root /var/www/phplib
      chmod 755 /var/www/phplib
      cp ./phplib/* /var/www/phplib/ -R

# Move the html files to the DocumentRoot directory
mkdir /var/www/html/serweb/
chown apache /var/www/html/serweb/
chgrp root /var/www/html/serweb/
chmod 755 /var/www/html/serweb/
cp ./html/* /var/www/html/serweb -R

  • edit these lines in /etc/php.ini
    and change short_open_tag = Off" to "On"

and change register_globals = Off" to "On"

· Create these files as part of the serweb module.

vi /var/www/html/serweb/prolog.html
AARNet SER SIP Server
vi /var/www/html/serweb/separator.html
vi /var/www/html/serweb/epilog.html
End of page text

  • ALL the files that follw are with respect to /var/www/html/serweb
    cd /var/www/html/serweb
  • edit these lines in ./config.php
    In general replace all 192.168.2.16 with 192.94.63.28
    #If you have changed the mysql username, dbname or password you need to change these:
    db_name="ser"; //database name
    db_user="ser"; //database conection user
    db_pass="heslo"; //database conection password
    # NOTE: The above relate to the mysql database, see /usr/sbin/ser_mysql.sh.
    $this->root_path="/serweb/";
    #The above must match where the serweb html directory is put
    this user_pages_path = this root_path."user_interface/";


    $this->prolog="/serweb/prolog.html";
    $this->separator="/serweb/separator.html";
    $this->epilog="/serweb/epilog.html";
    # /* email address for questions concerning registration */
    $this->root_uri.

$this->root_path."user_interface/my_account.php?#session#\n\n".
$this->root_uri.

$this->root_path."user_interface/reg/confirmation.php?nr=#confirm#\n\n".
# There is heaps more to customise in this file which we will leave to the user. These include more email references
# and text used in emails to users who register. Here are some example which do not need to be changed for this tutorial:
$this->mail_header_from="Stephen.Kingham@aarnet.edu.au";
$this->web_contact="sip:Stephen.Kingham@aarnet.edu.au";
$this->title="The AARNet IP Telephony Site";
$this->infomail = "Stephen.Kingham@aarnet.edu.au";
$this->regmail = "Stephen.Kingham@aarnet.edu.au";

  • Edit /var/www/phplib/db_mysql.inc
    # You need to add the following to /* public: connection parameters */
    var $Host = "192.94.63.28";
    var $Database = "ser";
    var $User = "ser";
    var $Password = "heslo";

The follwoing changes can be applied two ways:

1. Get and extract this tar file

get the file fixupserwebphp.tar from this server put it in the directory /usr/local/src/ser issue these commands

cd /var/www/html/serweb

tar -xvf fixupserwebphp.tar

OR


2. Manualy make all these changes

Generaly you have to add "../" to all these files so that they point correctly to where the phplib is.


Edit ./admin/prepend.php
# change $_PHPLIB["libdir"] = "../../../phplib/";

  • Edit ./user_interface/prepend.php
    # change $_PHPLIB["libdir"] = "../../../phplib/";
  • Edit ./user_interface/reg/prepend.php
    # change $_PHPLIB["libdir"] = "../../../../phplib/";
  • Edit ./admin/acl.php
    # change require "../../../phplib/oohforms.inc";
  • Edit ./admin/index.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./admin/users.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./user_interface/accounting.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./user_interface/find_user.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./user_interface/index.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/missed_calls.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/my_account.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/phonebook.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/send_im.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/notification_subscription.php
    # require "../../../phplib/oohforms.inc";
  • Edit ./user_interface/reg/finish.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./user_interface/reg/get_pass.php
    # require "../../../../phplib/oohforms.inc";
  • Edit ./user_interface/reg/index.php
    # require "../../../../phplib/oohforms.inc";

LAST STEP: START APACHE
/etc/rc.d/init.d/httpd start

Initial configuration of SER

Some key SER configuration commands

  • Create users:You must be root.
    sudo su -
    Format of the command is: serctl add username password email
    and you need to use the DEFAULT_PW=heslo as the password set in /usr/sbin/ser_mysql.sh
    /usr/sbin/serctl add srk password Stephen.Kingham@aarnet.edu.au
    /usr/sbin/serctl add
    caf password Clayton.Forbes@aarnet.edu.au
    change password to the password that will be used by the user, do not use password as a password!
  • Give the User several aliases, such as a telephone number:
    /usr/sbin/serctl
  • Set up some permanent forking, so calls to the user also go through to telephone numbers:
    /usr/sbin/serctl
  • Test the connection using two SIP UAs.
    • See the examples of how to configure UAs.
    • Use the this command to see who is logged in:
      serctl ul show
  • What places users can call are set by a flag for the user in mysql, the "acl" table. Use the serctl command to enable various flags for each user. You can create the flags by configuring the serctl programme it's self, ie vi /usr/sbin/serctl.
    /usr/sbin/serctl acl grant srk
    free-pstn

    /usr/sbin/serctl acl grant srk
    ld
    /usr/sbin/serctl acl grant srk
    ld

    What the various flags do is done within the routing in ser.cfg.

Thursday, February 22, 2007

CDRTool installation (MYSQL)

Obtain the software from http://cdrtool.ag-projects.com. The software is
available as a tar archive or as a debian package.

Installing from the tar archive:

Change directory to your web root (/var/www on Debian systems)

tar zxvf cdrtool*.tgz

Installing from the debian package:

dpkg -i cdrtool*.deb

The files will be installed under /var/www/CDRTool directory.


Create CDRTool database
-----------------------

You need MySQL root access with GRANT priviledges from the machine where
CDRTool runs, otherwise copy the files required by setup/setup_mysql.sh to
the MySQL machine and run the script locally.

Change the MySQL password of the cdrtool user from file
setup/create_users.mysql

Then run the database setup script:

/var/www/CDRtool/setup/mysql/setup_mysql.sh

The script performs the following:

1. It adds to the MySQL server a user for cdrtool software
2. It creates a new MySQL database "cdrtool"
3. It creates a default web user admin/admin, you may use
this initial account to login in the web interface
4. It populates the cdrtool database with initial values


PHP setup and Apache setup
--------------------------

Install PHP and dependencies. If you have chosen to install the debian package, the dependencies will be resolved during installation.

Example for Debian systems and php4:

Enable php-mysql module in /etc/php/*/php.ini:

extension=mysql.so

Enable php in apache web server. Configuration example for apache on Debian systems:

/etc/apache/httpd.conf

DirectoryIndex index.phtml index.php index.html index.htm index.shtml index.cgi
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtml

Make sure php module is insbale in apache configuration. For apache this is done in /etc/apache/modules.conf:

LoadModule php4_module /usr/lib/apache/1.3/libphp4.so

Change AllowOverride None to AllowOverride All

For apache2 us a2enmode php command.

Create a virtual host for cdrtool. Example for apache2:

cp setup/apache2/sites-available/cdrtool.example.com /etc/apache2/sites-enabled
cp setup/apache2/conf.d/cdrtool /etc/apache2/conf.d/



ServerName cdrtool.example.com
DocumentRoot /var/www/
CustomLog /var/log/apache2/cdrtool-access.log combined
ErrorLog /var/log/apache2/cdrtool-errors.log
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown

# To enable SSL:
# a2enmode ssl
# add Listen 443 to ports.conf file
# generate site certificates

# SSLEngine On
# SSLCertificateFile /etc/apache2/ssl/snakeoil-rsa.crt
# SSLCertificateKeyFile /etc/apache2/ssl/snakeoil-rsa.key



Enable the virtual site using:

a2ensite cdrtool.example.com

You may enable ssl using "a2enmod ssl" command. If you use ssl you must also generate a site certificate using the instructions provided by apache2 software.


Create a configuration file
---------------------------

cd /var/www/CDRTool
cp setup/global.inc.new.installation global.inc

Edit global.inc and setup your variables to match your system.

For each different datasource you must instantiate a new class extending one of the existing classes (ser, asterisk or cisco).

global.inc.in contains a more elaborate example for setting up datasources


Enable rating engine
--------------------

The rating engine is used for prepaid applications and as price calculator for postpaid traffic. It provides access to the rating tables and stays in memory (running as a daemon) to avoid reading the rating tables at every rating request. The rating tables can be reloaded without restarting the rating engine.

See the information in the head of the scripts/ratingEngine.php daemon for how to enable prepaid or other rating functionality. For prepaid, an external B2BUA is required, CDRTool provides only the rating and update balance functions.

Set the IP and port where the rating engine listens to and the OpenSER datasource in global.inc:

$RatingEngine=array("socketIP" => IP.address.of.the.private.interface.of.cdrtool.example.com",
"socketPort" => "9024",
"CDRS_class" => "ser_radius");

The MSQL schema for prepaid accounts: setup/mysql/create_prepaid.mysql The network engine has no security features, it must run over a protected network.

Edit /etc/default/cdrtool and set RUN_ratingEngine=yes

Then restart the rating engine:

/etc/init.d/cdrtool restart


High availability
-----------------

Setup heartbeat and MySQL replication.


CRON setup
----------

Some operations must be scheduled to run periodically by cron. Such operations are the scripts that block fraudulous accounts in OpenSER, normalize the call detail records, purge the old SIP traces.

The sample cron file is in /var/www/CDRTool/setup/crontabs/

This is done automatically if you install the debian package.


RADIUS setup
------------

CDRTool works with FreeRadius server from http://www.freeradius.org

apt-get install freeradius freeradius-mysql Create the database for radius tables on MySQL server

mysqladmin -u root create radius

Create RADIUS tables

The paths might differ depending on freeradius installation

cp /usr/share/doc/freeradius/examples/db_mysql.sql.gz .
gunzip db_mysql.sql.gz
mysql -u root radius < /usr/share/doc/freeradius/examples/db_mysql.sql

Patch radacct table for storage of CISCO VSA and rating. Apply a patch to the default radacct table. This will add fields necessary to store Vendor Specific Atributes from Cisco or OpenSER.

It is not possible to mix call details records from CISCO and OpenSER in the same radius table. You need to create multiple radius server profiles and save the CDRs into dedicated tables for each datasource.

Modify the default radacct table for OpenSER by running:

/var/www/CDRTool/setup/radius/OpenSER/radacct-patch.sh

and for CISCO by running:

/var/www/CDRTool/setup/radius/CISCO/radacct-patch.sh

Configure Freeradius to write data into the radacct table:

cp /var/www/CDRTool/setup/radius/OpenSER/sql.conf /etc/freeradius/sql.conf

For large volume of CDRs it is usefull automatically rotate the tables in which the data is written.

/var/www/CDRTool/setup/radius/OpenSER/radius_accounting.*, contain mysql procedures that automatically create monthly tables in the format radacctYYYYMM. To use mysql procedures, your must use MySQL server version 5 or greater and Freeradius server mysql module must be compiled to support CLIENT_MULTI_RESULTS mysql connection flag. This must be done in
src/modules/rlm_sql/drivers/rlm_sql_mysql/sql_mysql.c:

if (!(mysql_sock->sock = mysql_real_connect(&(mysql_sock->conn),
config->sql_server,
config->sql_login,
config->sql_password,
config->sql_db,
atoi(config->sql_port),
NULL,
CLIENT_FOUND_ROWS|CLIENT_MULTI_RESULTS ))) {

Also, if you use MediaProxy for accounting in combination with OpenSER you must use the MediaProxy version that supports the same mysql procedures.

Edit the database connection details in sql.conf and restart Freeradius server.

Add RADIUS clients in clients.conf. Each device sending RADIUS accounting requests must be added to /etc/radddb/clients.conf. Examples:

client 10.0.0.0/8 {
secret=DssUET01
nastype=other
shortname=localnet
}

Enable MySQL accounting in FreeRadius server. Edit radius.conf "sql" must be uncommented or added if missing.

# accounting {
detail
sql
}

Copy /var/www/CDRTool/setup/radius/OpenSER/dictionary.ser to /etc/freeradius


OpenSER setup
-------------

CDRTool version >4.3 have been tested only against OpenSER 1.0 and above.

Enable MySQL storage for subscribers and accounting and Radius accounting. For SIP Tracing you need OpenSER siptrace module. To enable quota you must add an extra column in the subscriber table:

alter table openser.subscriber add column quota int not null;

Entries required in openser.cfg:

loadmodule "acc.so"

modparam("acc", "failed_transaction_flag", 1)
modparam("acc", "report_cancels", 0)
modparam("acc", "report_ack", 0)
modparam("acc", "early_media", 0)

modparam("acc", "log_level", 1)
modparam("acc", "log_flag", 1)
modparam("acc", "log_missed_flag", 1)

modparam("acc", "radius_config", "/etc/openser/radius/client.conf")
modparam("acc", "radius_flag", 1)
modparam("acc", "radius_missed_flag", 1)
modparam("acc", "radius_extra", "Sip-RPid=$avp(s:rpid); \
Source-IP=$si; \
Source-Port=$sp; \
Canonical-URI=$avp(can_uri); \
Billing-Party=$avp(billing_party); \
Divert-Reason=$avp(s:divert_reason); \
X-RTP-Stat=$avp(s:rtp_statistics); \
From-Header=$hdr(from); \
User-Agent=$hdr(user-agent); \
Contact=$hdr(contact); \
Event=$hdr(event); \
SIP-Proxy-IP=$avp(s:sip_proxy_ip)")

Further, you must enable accounting in various parts of the routing script by setting the accounting flag and saving the AVP containing the proxy IP address. It is important to save $avp(can_uri) after the Proxy has performed all possible lookups except DNS. The Canonical-URI will be used for rating the session. Example:

route {
...
setflag(ACCOUNTING_FLAG);
avp_write("SER_IP","$avp(s:sip-proxy)");
avp_write("$ru", "$avp(can_uri)");
}

Copy /var/www/CDRTool/setup/radius/OpenSER/dictionary.ser to /etc/openser/radius/ and uncomment the line:

$INCLUDE /etc/radiusclient-ng/dictionary


SOAP engine
-----------

Warning!

Support for the SOAP engine has been discontinued from version >=5.0.

Note: It depends on the SOAP library from http://pear.php.net/package/SOAP. On Debian systems, this dependency is automatically installed but if CDRTool is installed from the tar archive you must download and install manually this SOAP library.

The SOAP engine can be used by an external provisioning system to access information available in CDRTool (like prepaid accounts).

The rating and other CDRTool functions (like provisioning of prepaid accounts or checking the balance) are available by using SOAP calls. The SOAP calls are translated into requests for the rating engine (which must be up and running, see previous section).

The SOAP functionality including a WSDL file for creating a SOAP client is available in SOAP/WSDL/ directory.

The SOAP server supports authorization, the SOAP clients must connect using an account that has soap_client right assigned into the CDRTool accounts page. The SOAP server uses the Apache web server for transport, it can work with both HTTP and HTTPS. The servers logs all network requests to syslog.

Define in global.inc the SOAP server URL where the client should connect to:

$SOAPServer=array("cdr_source"=>"ser_radius",
"location" =>"https://example.com/CDRTool/SOAP/server.php",
"wsdl" =>"https://example.com/CDRTool/SOAP/WSDL/"
);

A test SOAP client is available in SOAP/client.php. It connects to the server and displays the CDRTool server version.

To prevent a bug in PEAR SOAP server add the following last line in function SOAP_ServerErrorHandler from SOAP/Server.php

function SOAP_ServerErrorHandler($errno, $errmsg, $filename,$linenum, $vars) {
....

unset($soap_server_fault->backtrace);
}

Interaction between rating engine and SOAP:

Function Provisioning B2BUA RatingEngine SOAP/XML
----------------------------------------------------------------------------------------
MaxSessionTime <----------------->

DeductBalance <----------------->

AddBalance ----------------------------------------------------------->
<------------------

CheckBalance ----------------------------------------------------------->
<------------------

ShowAccounts ----------------------------------------------------------->
<------------------

LastMissedCalls ----------------------------------------------------------->
LastPlacedCalls ----------------------------------------------------------->
LastReceivedCalls ----------------------------------------------------------->
OpenSERLocations ----------------------------------------------------------->



MediaProxy setup
----------------

MediaProy can log into CDRTool the IP bandwidth utilization, the codecs and the User Agents. MediaProxy logs this information into the database used by the Radiusserver, the radacct table.

MediaProxy can also correct the session duration of CDRs for which no BYE messages have been received.

The following information is logged:

- InputOctets and OutputOctets
- CodecType (like GSM or G711)
- ApplicationType (text/audio/video)
- User Agent(s)
- Media IP source and IP destination

See MediaProxy documentation for how to enable Radius or database accounting.


Asterisk setup
--------------

Download from cvs the asterisk-addons and patch asterisk to store CDRs in MySQL.

See /var/www/CDRTool/setup/asterisk for more information.


Cisco setup
-----------

Use the CISCO CLI, enter enable mode and configuration from terminal:

>enable
config terminal
aaa new-model
aaa group server radius aaa.router
server RADIUS_SERVER_IP auth-port 1812 acct-port 1813
aaa accounting connection h323 start-stop group radius
gw-accounting h323
gw-accounting h323 vsa
gw-accounting voip


Manual CDR uploads
------------------

If MySQL is down you will miss CDRs written by RADIUS. These CDRs can be reload manually from radius accounting files using the supplied upload scripts in scripts directory (IPNX, OpenSER and CISCO import scripts available).


Q931 Release codes for Cisco
----------------------------

In CDRTool CISCO hexadecimal release codes are automatically mapped to Q931 release codes.


Rating engine
-------------

See RATING file.


Monitoring
----------

Monit can check if the rating engine stopped working and restart it. A sample configuration file for monit is available in setup/monit/monitrc. Edit the IP address and hostname where the rating engine runs and copy /var/www/CDRTool/setup/monit/monitrc /etc/monit/monit.d/cdrtool

Usage statistics
----------------

CDRTool can build usage statistics of the number of online SIP devices from OpenSER, simultaneous number of media streams and relayed IP traffic by MediaProxy.

Define DB_siponline as a new database class in global.inc. Example:

class DB_siponline extends DB_Sql {
var $Host = "db";
var $Database = "openser";
var $User = "openser";
var $Password = "password";
var $Halt_On_Error ="no";
}

Define all media proxy servers in:

/var/www/CDRTool/status/config/media_servers.php

The script that gathers the usage information and builds the graphical statistics is /var/www/CDRTool/scripts/buildStatistics.php

This script runs as a cron job every 5 minutes.

The usage information is cumulated in /tmp/CDRTool-sip-statistics.txt file, which is a plain text file with one line per domain and values separated by tabs. This file can be easily parsed by external scripts to build statistics using other tools like SNMP.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

MYSQL SP

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
/*
LAST UPDATED: 2007-01-04 03:14 CET

CHANGELOG:
- Added database name as parameter to stored procedures
- Fixed the multiple query result in "update_raddact_record_mediaproxy"
- Modus operandi update
- Fixed determination of previous year in "update_raddact_record_mediaproxy"
- Consolidate SET statements to minimize binary log entries
- Fixed bug in update_raddact_record_mediaproxy, the record values were reset
after execution of update on the first table causing failure to update
the previous table

Starting with version CDRTool version 4.9 it is possible to store call
details records in automatically rotated radacct tables by using MySQL
stored procedures.

This implementation has been contributed by
Andrei Magureanu

How to setup auto-rotation
--------------------------

1. Load radius_accounting.proc into the mysql server. MySQL >=5.0
version and SUPER priviledges are required.

2. Patch the Freeradius server mysql client to allow stored procedures.
Instructions can be found in ../freeradius directory. Re-compile and
re-install Freeradius server.

3. Copy radius_accounting.conf to sql.conf to the Freeradius server. Edit
the new sql.conf with the database connection information.

4. Update MediaProxy configuration to use radius accounting, instead of
database accounting (MediaProxy >= 1.8.0 is required)

5. In CDRTool, change global.inc table name to:
"table" => "radacct".date("Ym"),


The modus operandi of the stored procedure
------------------------------------------

Currently, call detail records generated by the OpenSER SIP Proxy are stored into a central radius.radacct table. The radacct table grows and must be manually purged, the purge operation locks the table for writing, which is blocking the application that performs the queries, and this situation is unacceptable.

The radacct tables are populated with data as follows: When a SIP session starts, an INSERT query generated by the Freeradius server inserts data into MySQL a radacctYYYYMM table (e.g. radacct200611). Later, when the SIP session ends, an UPDATE query sets various fields of the previously inserted record. The server that performs the INSERT matches the inserted data based on indexes present in the table. We want to store the data in monthly tables that have a name based on the following syntax:

radacct%Y%m

Examples:

radacct200611 (November table)
radacct200612 (December table)

The stored procedure achieves the following: On INSERT the monthly table is created automatically when necessary. If an INSERT query fails with the mysql code table not available, the right table is created and the INSERT query is performed in the new table. The table name is derived from the current month, which is determined from the AcctStartTime radius attribute. On UPDATE the procedure detects if the UPDATE query has failed because the record does not exist in the current table and updates the record in the previous table by substracting one calendar month, redefining the table name
and retry the query. The table name is derived from the AcctStopTime radius attribute. A example of queries on how the procedures can be used is available at the end of this script.

*/

-- OPTIONAL (COMMENT OUT): DATABASE TO USE
-- USE radius;

-- MUST FOR UNIX BASED SYSTEMS -- (SEE: http://dev.mysql.com/doc/refman/5.0/en/stored-procedure-logging.html)
-- SET GLOBAL log_bin_trust_function_creators = 1;


DELIMITER ;

-- CREATE "BEGINNING OF DEFAULT TABLE NAME" FUNCTION

DROP FUNCTION IF EXISTS `set_radacct_table_name`;

DELIMITER $$

CREATE FUNCTION `set_radacct_table_name`() RETURNS varchar(50)
DETERMINISTIC
BEGIN
DECLARE tblname VARCHAR(50);
SET tblname = 'radacct';
RETURN tblname;
END $$

DELIMITER ;

-- CREATE SUPPORT "CREATE TABLE" PROCEDURE

DROP PROCEDURE IF EXISTS `create_radacct_table`;

DELIMITER $$

CREATE PROCEDURE `create_radacct_table`(IN var_tbl VARCHAR(50))

BEGIN

SET @stbl = CONCAT("CREATE TABLE IF NOT EXISTS ", var_tbl, " (
`RadAcctId` bigint(21) NOT NULL auto_increment,
`AcctSessionId` varchar(255) NOT NULL default '',
`AcctUniqueId` varchar(255) NOT NULL default '',
`UserName` varchar(64) NOT NULL default '',
`Realm` varchar(64) default '',
`NASIPAddress` varchar(15) NOT NULL default '',
`NASPortId` varchar(50) NOT NULL default '',
`NASPortType` varchar(255) NOT NULL default '',
`AcctStartTime` datetime NOT NULL default '0000-00-00 00:00:00',
`AcctStopTime` datetime NOT NULL default '0000-00-00 00:00:00',
`AcctSessionTime` int(12) default NULL,
`AcctAuthentic` varchar(32) default NULL,
`ConnectInfo_start` varchar(32) default NULL,
`ConnectInfo_stop` varchar(32) default NULL,
`AcctInputOctets` bigint(12) default NULL,
`AcctOutputOctets` bigint(12) default NULL,
`CalledStationId` varchar(50) NOT NULL default '',
`CallingStationId` varchar(50) NOT NULL default '',
`AcctTerminateCause` varchar(32) NOT NULL default '',
`ServiceType` varchar(32) default NULL,
`FramedProtocol` varchar(32) default NULL,
`FramedIPAddress` varchar(15) NOT NULL default '',
`AcctStartDelay` int(12) default NULL,
`AcctStopDelay` int(12) default NULL,
`SipMethod` varchar(50) NOT NULL default '',
`SipResponseCode` smallint(5) unsigned NOT NULL default '0',
`SipToTag` varchar(128) NOT NULL default '',
`SipFromTag` varchar(128) NOT NULL default '',
`SipTranslatedRequestURI` varchar(255) NOT NULL default '',
`SipUserAgents` varchar(255) NOT NULL default '',
`SipApplicationType` varchar(255) NOT NULL default '',
`SipCodecs` varchar(255) NOT NULL default '',
`SipRPID` varchar(255) NOT NULL default '',
`SipRPIDHeader` varchar(255) NOT NULL default '',
`SourceIP` varchar(255) NOT NULL default '',
`SourcePort` varchar(255) NOT NULL default '',
`CanonicalURI` varchar(255) NOT NULL default '',
`DelayTime` varchar(5) NOT NULL default '',
`Timestamp` bigint(20) NOT NULL default '0',
`DestinationId` varchar(15) NOT NULL default '',
`Rate` text NOT NULL,
`Price` double(20,4) default NULL,
`Normalized` enum('0','1') default '0',
`BillingId` varchar(255) NOT NULL default '',
`MediaInfo` varchar(32) default NULL,
`RTPStatistics` text NOT NULL,
`FromHeader` varchar(128) NOT NULL default '',
`UserAgent` varchar(128) NOT NULL default '',
`Contact` varchar(128) NOT NULL default '',
PRIMARY KEY (`RadAcctId`),
UNIQUE KEY `sess_id` (`AcctSessionId`(128),`SipFromTag`,`SipToTag`),
KEY `UserName` (`UserName`),
KEY `AcctSessionId` (`AcctSessionId`),
KEY `AcctUniqueId` (`AcctUniqueId`),
KEY `AcctStartTime` (`AcctStartTime`),
KEY `AcctStopTime` (`AcctStopTime`),
KEY `NASIPAddress` (`NASIPAddress`),
KEY `caller_idx` (`CallingStationId`),
KEY `called_idx` (`CalledStationId`),
KEY `canon_idx` (`CanonicalURI`),
KEY `source_ip_idx` (`SourceIP`),
KEY `billing_id_idx` (`BillingId`),
KEY `dest_id_idx` (`DestinationId`),
KEY `sip_req_uri_idx` (`SipTranslatedRequestURI`),
KEY `normalize_idx` (`Normalized`),
KEY `MediaInfo_idx` (`MediaInfo`),
KEY `Realm_idx` (`Realm`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");
PREPARE ctbl_stmt FROM @stbl;
EXECUTE ctbl_stmt;
DEALLOCATE PREPARE ctbl_stmt;

END $$

DELIMITER ;

-- CREATE "INSERT RECORD" PROCEDURE
DROP PROCEDURE IF EXISTS `insert_radacct_record`;

DELIMITER $$

CREATE PROCEDURE `insert_radacct_record`(
IN var_db_name VARCHAR(20),
IN var_AcctSessionId VARCHAR(255),
IN var_AcctUniqueId VARCHAR(255),
IN var_UserName VARCHAR(64),
IN var_Realm VARCHAR(64),
IN var_NASIPAddress VARCHAR(15),
IN var_NASPortId VARCHAR(50),
IN var_AcctStartTime VARCHAR(20),
IN var_AcctStopTime VARCHAR(20),
IN var_AcctSessionTime INT(12),
IN var_AcctInputOctets BIGINT(12),
IN var_AcctOutputOctets BIGINT(12),
IN var_CalledStationId VARCHAR(50),
IN var_CallingStationId VARCHAR(50),
IN var_AcctTerminateCause VARCHAR(32),
IN var_ServiceType VARCHAR(32),
IN var_FramedProtocol VARCHAR(32),
IN var_FramedIPAddress VARCHAR(15),
IN var_AcctStartDelay INT(12),
IN var_AcctStopDelay INT(12),
IN var_SipResponseCode SMALLINT(5),
IN var_SipMethod VARCHAR(50),
IN var_SipTranslatedRequestURI VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128),
IN var_SipRPID VARCHAR(255),
IN var_SourceIP VARCHAR(255),
IN var_SourcePort VARCHAR(255),
IN var_CanonicalURI VARCHAR(255),
IN var_Rate TEXT,
IN var_RTPStatistics TEXT
)
BEGIN

-- SET VARIABLES
SET @v_AcctSessionId = var_AcctSessionId,
@v_AcctUniqueId = var_AcctUniqueId,
@v_UserName = var_UserName,
@v_Realm = var_Realm,
@v_NASIPAddress = var_NASIPAddress,
@v_NASPortId = var_NASPortId;

IF var_AcctStartTime = '0' OR var_AcctStartTime = '' THEN
SET @v_AcctStartTime = NOW();
ELSE
SET @v_AcctStartTime = CAST(var_AcctStartTime AS DATETIME);
END IF;

IF var_AcctStopTime = '0' OR var_AcctStopTime = '' THEN
SET @v_AcctStopTime = CAST('0000-00-00 00:00:00' AS DATETIME);
ELSE
SET @v_AcctStopTime = CAST(var_AcctStopTime AS DATETIME);
END IF;

SET @v_db_name = var_db_name,
@v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_CalledStationId = var_CalledStationId,
@v_CallingStationId = var_CallingStationId,
@v_AcctTerminateCause = var_AcctTerminateCause,
@v_ServiceType = var_ServiceType,
@v_FramedProtocol = var_FramedProtocol,
@v_FramedIPAddress = var_FramedIPAddress,
@v_AcctStartDelay = var_AcctStartDelay,
@v_AcctStopDelay = var_AcctStopDelay,
@v_SipResponseCode = var_SipResponseCode,
@v_SipMethod = var_SipMethod,
@v_SipTranslatedRequestURI = var_SipTranslatedRequestURI,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@v_SipRPID = var_SipRPID,
@v_SourceIP = var_SourceIP,
@v_SourcePort = var_SourcePort,
@v_CanonicalURI = var_CanonicalURI,
@v_Rate = var_Rate,
@v_RTPStatistics = var_RTPStatistics,
@var_y = (SELECT YEAR(@v_AcctStartTime)),
@var_m = (SELECT DATE_FORMAT(@v_AcctStartTime, '%m')),
@var_tbl_begin = (SELECT set_radacct_table_name()),
@var_tbl = CONCAT(@var_tbl_begin, @var_y, @var_m),
@var_tbl_cnt = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl);

-- TABLE DOES NOT EXIST
IF @var_tbl_cnt = 0 THEN

-- CREATE RAD TABLE
SET @ctblproc = CONCAT("CALL create_radacct_table(", "'", @var_tbl, "'", ")");
PREPARE ctbl_proc_stmt FROM @ctblproc;
EXECUTE ctbl_proc_stmt;
DEALLOCATE PREPARE ctbl_proc_stmt;

END IF;

-- INSERT RECORD IN NEW TABLE
SET @instmt = CONCAT("INSERT INTO ", @var_tbl, " (
RadAcctId, AcctSessionId, AcctUniqueId,
UserName, Realm, NASIPAddress, NASPortId,
AcctStartTime, AcctStopTime, AcctSessionTime,
AcctInputOctets, AcctOutputOctets, CalledStationId,
CallingStationId, AcctTerminateCause, ServiceType,
FramedProtocol, FramedIPAddress, AcctStartDelay,
AcctStopDelay, SipResponseCode,
SipMethod, SipTranslatedRequestURI, SipToTag,
SipFromTag, SipRPID, SourceIP, SourcePort, CanonicalURI,
Rate, RTPStatistics)
VALUES (NULL, ?, ?, ?, SUBSTRING_INDEX(?, '@',-1),
?, ?, ?, ?, ?, ?, ?, trim(leading 'sip:' from trim(leading 'sips:' from ?)), trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ?, ?, ?, ?, ?, ?, ?,trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ?, ?, ?, ?, trim(leading 'sip:' from trim(leading 'sips:' from ?)), ?, ? )");

PREPARE add_rad FROM @instmt;
EXECUTE add_rad USING @v_AcctSessionId, @v_AcctUniqueId,
@v_UserName, @v_Realm, @v_NASIPAddress, @v_NASPortId,
@v_AcctStartTime, @v_AcctStopTime, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets, @v_CalledStationId,
@v_CallingStationId, @v_AcctTerminateCause, @v_ServiceType,
@v_FramedProtocol, @v_FramedIPAddress, @v_AcctStartDelay,
@v_AcctStopDelay, @v_SipResponseCode, @v_SipMethod,
@v_SipTranslatedRequestURI, @v_SipToTag, @v_SipFromTag,
@v_SipRPID, @v_SourceIP, @v_SourcePort, @v_CanonicalURI,
@v_Rate, @v_RTPStatistics;
DEALLOCATE PREPARE add_rad;

-- CLEAN UP
SET @v_AcctSessionId = null,
@v_AcctUniqueId = null,
@v_UserName = null,
@v_Realm = null,
@v_NASIPAddress = null,
@v_NASPortId = null,
@v_AcctStartTime = null,
@v_AcctStopTime = null,
@v_AcctSessionTime = null,
@v_AcctInputOctets = null,
@v_AcctOutputOctets = null,
@v_CalledStationId = null,
@v_CallingStationId = null,
@v_AcctTerminateCause = null,
@v_ServiceType = null,
@v_FramedProtocol = null,
@v_FramedIPAddress = null,
@v_AcctStartDelay = null,
@v_AcctStopDelay = null,
@v_SipResponseCode = null,
@v_SipMethod = null,
@v_SipTranslatedRequestURI = null,
@v_SipToTag = null,
@v_SipFromTag = null,
@v_SipRPID = null,
@v_SourceIP = null,
@v_SourcePort = null,
@v_CanonicalURI = null,
@v_Rate = null,
@v_RTPStatistics = null,
@var_y = null,
@var_m = null,
@v_db_name = null,
@var_tbl_begin = null,
@var_tbl = null;

END $$

DELIMITER ;

-- CREATE "UPDATE RECORD" PROCEDURE

DROP PROCEDURE IF EXISTS `update_radacct_record`;

DELIMITER $$

CREATE PROCEDURE `update_radacct_record`(
IN var_db_name VARCHAR(20),
IN var_AcctStopTime VARCHAR(20),
IN var_AcctStopDelay INT(12),
IN var_ConnectInfo_stop VARCHAR(32),
IN var_RTPStatistics VARCHAR(255),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128)
)

BEGIN

-- SET VARIABLES
SET @v_db_name = var_db_name,
@var_tbl_begin = (SELECT set_radacct_table_name()),
@v_stoptime = var_AcctStopTime,
@var_month_formatted = (SELECT DATE_FORMAT(@v_stoptime, '%m')),
@var_yst = (SELECT DATE_FORMAT(@v_stoptime, '%Y')),
@var_tbl_month = CONCAT(@var_tbl_begin, @var_yst, @var_month_formatted),
@v_AcctStopTime = CAST(var_AcctStopTime AS DATETIME),
@v_AcctStopDelay = var_AcctStopDelay,
@v_ConnectInfo_stop = var_ConnectInfo_stop,
@v_RTPStatistics = var_RTPStatistics,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@var_tbl_cnt1 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl_month);

IF @var_tbl_cnt1 = 1 THEN
-- WE HAVE A TABLE BASED ON StopTime
-- SO LET'S TRY TO UPDATE
SET @updstmt1 = CONCAT("UPDATE ", @var_tbl_month, " SET
AcctStopTime = ?,
AcctSessionTime = UNIX_TIMESTAMP(?) - UNIX_TIMESTAMP(AcctStartTime),
AcctStopDelay = ?,
ConnectInfo_stop = ?,
RTPStatistics = ?,
Normalized = '0'
WHERE
AcctSessionId = ?
AND ((SipToTag = ? AND SipFromTag = ?) OR (SipToTag = ? AND SipFromTag = ?))
AND ConnectInfo_stop IS NULL;");
PREPARE update_rad1 FROM @updstmt1;
EXECUTE update_rad1 USING @v_AcctStopTime, @v_AcctStopTime,
@v_AcctStopDelay, @v_ConnectInfo_stop, @v_RTPStatistics,
@v_AcctSessionId, @v_SipToTag, @v_SipFromTag,
@v_SipFromTag, @v_SipToTag;

SET @updatedrows = (SELECT ROW_COUNT()),
@updstmt1 = null;

DEALLOCATE PREPARE update_rad1;

ELSE
SET @updatedrows = 0;
END IF;


IF @updatedrows = 0 THEN
-- UPDATE LAST MONTH'S TABLE BASED ON var_AcctStopTime

SET @var_prev_month = (SELECT DATE_FORMAT(DATE_ADD(@v_stoptime, INTERVAL -1 MONTH), '%Y%m')),
@var_tbl_pmonth = CONCAT(@var_tbl_begin, @var_prev_month),
@var_tbl_cnt2 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_db_name
AND TABLE_NAME = @var_tbl_pmonth);

IF @var_tbl_cnt2 = 1 THEN
-- UPDATE PREVIOUS MONTH TABLE

SET @updstmt2 = CONCAT("UPDATE ", @var_tbl_pmonth, " SET
AcctStopTime = ?,
AcctSessionTime = UNIX_TIMESTAMP(?) - UNIX_TIMESTAMP(AcctStartTime),
AcctStopDelay = ?,
ConnectInfo_stop = ?,
RTPStatistics = ?,
Normalized = '0'
WHERE
AcctSessionId = ?
AND ((SipToTag = ? AND SipFromTag = ?) OR
(SipToTag = ? AND SipFromTag = ?));");
PREPARE update_rad2 FROM @updstmt2;
EXECUTE update_rad2 USING @v_AcctStopTime, @v_AcctStopTime,
@v_AcctStopDelay, @v_ConnectInfo_stop, @v_RTPStatistics,
@v_AcctSessionId, @v_SipToTag, @v_SipFromTag,
@v_SipFromTag, @v_SipToTag;

SET @updatedrows = (SELECT ROW_COUNT()),
@updstmt = null;

DEALLOCATE PREPARE update_rad2;
ELSE
SET @updatedrows = 0;
END IF;

END IF;

-- CLEAN UP
SET @v_AcctStopTime = null,
@v_AcctStopDelay = null,
@v_ConnectInfo_stop = null,
@v_RTPStatistics = null,
@v_AcctSessionId = null,
@v_SipToTag = null,
@v_SipFromTag = null,
@v_db_name = null;

END $$

DELIMITER ;

-- CREATE "MEDIAPROXY RECORD UPDATE" PROCEDURE

DROP PROCEDURE IF EXISTS `update_raddact_record_mediaproxy`;

DELIMITER $$

CREATE PROCEDURE `update_raddact_record_mediaproxy`(
IN var_db_name VARCHAR(20),
IN var_AcctSessionTime int(12),
IN var_AcctInputOctets bigint(12),
IN var_AcctOutputOctets bigint(12),
IN var_SipUserAgents VARCHAR(255),
IN var_SipCodecs VARCHAR(255),
IN var_SipApplicationType VARCHAR(255),
IN var_MediaInfo VARCHAR(32),
IN var_Normalized ENUM('0','1'),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128)
)

BEGIN

-- SET VARIABLES
SET @var_tbl_begin = (SELECT set_radacct_table_name()),
@var_prev_month = (SELECT DATE_FORMAT(DATE_ADD(CURRENT_DATE, INTERVAL -1 MONTH), '%Y%m')),
@var_current_month = (SELECT DATE_FORMAT(CURRENT_DATE, '%Y%m')),
@var_tbl = CONCAT(@var_tbl_begin, @var_current_month),
@var_tbl_prev_month = CONCAT(@var_tbl_begin, @var_prev_month),
@v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_SipUserAgents = var_SipUserAgents,
@v_SipCodecs = var_SipCodecs,
@v_SipApplicationType = var_SipApplicationType,
@v_MediaInfo = var_MediaInfo,
@v_Normalized = var_Normalized,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag,
@v_na = 'n/a',
@v_dbname = var_db_name,
@updatedrows = 0,
@var_tbl_cnt1 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_dbname
AND TABLE_NAME = @var_tbl),
@var_tbl_cnt2 = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @v_dbname
AND TABLE_NAME = @var_tbl_prev_month),
@proc_query = CONCAT("CALL proc_update_raddact_record_mediaproxy (?,?,?,?,?,?,?,?,?,?,?,?,?)");

PREPARE proc_rad_stmt FROM @proc_query;

IF @var_tbl_cnt1 = 1 THEN
-- FOR THE CURRENT MONTH
EXECUTE proc_rad_stmt USING @var_tbl, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_SipToTag, @v_SipFromTag, @v_dbname;
END IF;

IF @updatedrows = 0 AND @var_tbl_cnt2 = 1 THEN
-- FOR THE PREVIOUS MONTH
EXECUTE proc_rad_stmt USING @var_tbl_prev_month, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_SipToTag, @v_SipFromTag, @v_dbname;

IF @var_tbl_cnt1 = 1 AND @updatedrows = 0 THEN
-- FOR THE CURRENT MONTH WITH SipToTag = 'n/a'
EXECUTE proc_rad_stmt USING @var_tbl, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_na, @v_SipFromTag, @v_dbname;

IF @var_tbl_cnt2 = 1 AND @updatedrows = 0 THEN
-- FOR THE PREVIOUS MONTH WITH SipToTag = 'n/a'
EXECUTE proc_rad_stmt USING @var_tbl_prev_month, @v_AcctSessionTime,
@v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs,
@v_SipApplicationType, @v_MediaInfo, @v_Normalized, @v_AcctSessionId,
@v_na, @v_SipFromTag, @v_dbname;
END IF;
END IF;
END IF;

DEALLOCATE PREPARE proc_rad_stmt;

-- CLEAN UP

SET @var_current_month = null,
@var_db_name = null,
@var_tbl_begin = null,
@var_tbl = null,
@var_tbl_cnt = null,
@var_prev_month = null,
@var_tbl_prev_month = null,
@v_AcctSessionTime = null,
@v_AcctInputOctets = null,
@v_AcctOutputOctets = null,
@v_SipUserAgents = null,
@v_SipCodecs = null,
@v_SipApplicationType = null,
@v_MediaInfo = null,
@v_Normalized = null,
@v_AcctSessionId = null,
@v_SipFromTag = null,
@v_SipToTag = null,
@v_na = null,
@v_dbname = null;

END $$

DELIMITER ;

-- CREATE SUPPORT PROCEDURE FOR "update_raddact_record_mediaproxy"

DROP PROCEDURE IF EXISTS `proc_update_raddact_record_mediaproxy`;

DELIMITER $$

CREATE PROCEDURE `proc_update_raddact_record_mediaproxy`(
IN var_tblname VARCHAR(50),
IN var_AcctSessionTime int(12),
IN var_AcctInputOctets bigint(12),
IN var_AcctOutputOctets bigint(12),
IN var_SipUserAgents VARCHAR(255),
IN var_SipCodecs VARCHAR(255),
IN var_SipApplicationType VARCHAR(255),
IN var_MediaInfo VARCHAR(32),
IN var_Normalized ENUM('0','1'),
IN var_AcctSessionId VARCHAR(255),
IN var_SipToTag VARCHAR(128),
IN var_SipFromTag VARCHAR(128),
IN var_dbname VARCHAR(20)
)
BEGIN

-- TABLENAME VARIABLE
SET @var_tbl = var_tblname,
@var_db_name = var_dbname,
@var_tbl_cnt = (SELECT COUNT(TABLE_NAME) AS TBLCNT
FROM information_schema.tables
WHERE TABLE_SCHEMA = @var_db_name
AND TABLE_NAME = @var_tbl);

IF @var_tbl_cnt = 0 THEN
-- TABLE DOESN'T EVEN EXISTS, SO RETURN 0
SET @rcnt = (SELECT 0);
ELSE

SET @radupdstmt = CONCAT("UPDATE ", @var_tbl, " SET
AcctSessionTime = AcctSessionTime + IF(ConnectInfo_stop IS NULL, ?, 0),
AcctStopTime = DATE_ADD(AcctStartTime, INTERVAL AcctSessionTime SECOND),
AcctInputOctets = AcctInputOctets + ?,
AcctOutputOctets = AcctOutputOctets + ?,
SipUserAgents = ?,
SipCodecs = ?,
SipApplicationType = ?,
MediaInfo = ?,
Normalized = ?
WHERE
AcctSessionId = ?
AND SipToTag = ? AND SipFromTag = ?;");
PREPARE update_rad FROM @radupdstmt;

SET @v_AcctSessionTime = var_AcctSessionTime,
@v_AcctInputOctets = var_AcctInputOctets,
@v_AcctOutputOctets = var_AcctOutputOctets,
@v_SipUserAgents = var_SipUserAgents,
@v_SipCodecs = var_SipCodecs,
@v_SipApplicationType = var_SipApplicationType,
@v_MediaInfo = var_MediaInfo,
@v_Normalized = var_Normalized,
@v_AcctSessionId = var_AcctSessionId,
@v_SipToTag = var_SipToTag,
@v_SipFromTag = var_SipFromTag;

EXECUTE update_rad USING @v_AcctSessionTime, @v_AcctInputOctets, @v_AcctOutputOctets,
@v_SipUserAgents, @v_SipCodecs, @v_SipApplicationType,
@v_MediaInfo, @v_Normalized, @v_AcctSessionId, @v_SipToTag, @v_SipFromTag;
SET @rcnt = (SELECT ROW_COUNT());
DEALLOCATE PREPARE update_rad;

END IF;

END $$

DELIMITER ;


/*

-- TEST PROCEDURE THAT INSERTS A RECORD
CALL insert_radacct_record (
'radius','3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', '5af53194787eccf1',
'adi@umts.ro', 'adi@umts.ro', '83.149.75.105', '5060', '2006-12-10 12:09:19',
'0', '0', '0', '0', 'sip:3333@umts.ro=3Buser=3Dphone',
'sip:adi@umts.ro', '200', 'Sip-Session', '', '', '0', '0', '200', 'Invite',
'sip:3333@vm01.dns-hosting.info=3Buser=3Dphone', 'as5664a60b', '27qems1o2j',
'208005169', '81.23.228.147', '5060',
'sip:3333@vm01.dns-hosting.info=3Buser=3Dphone', '', ''
);

-- TEST PROCEDURE THAT UPATES A RECORD WITH MEDIAPROXY INFORMATION
CALL update_raddact_record_mediaproxy (
'radius','3','5896','7140','snom320/5.2 + Asterisk', 'GSM', 'Audio', '', '0',
'3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', 'as5664a60b','27qems1o2j'
);

-- TEST PROCEDURE THAT UPATES A RECORD
CALL update_radacct_record (
'radius','2006-12-10 12:09:21', '0', '', 'n/a',
'3c3b5ff12bf2-m5udeydrjsuw@snom320-000413241247', 'as5664a60b', '27qems1o2j'
);

*/