0% found this document useful (0 votes)
78 views44 pages

Kannel Install

Uploaded by

Robert Marbun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views44 pages

Kannel Install

Uploaded by

Robert Marbun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

general description

kannel is an open source wap and sms gateway designed to transmit SMS messages to
a cellular operator using the SMPP protocol . The application is very flexible. It is also
possible to configure the modem to transmit SMS. But the most important advantage
of this software is that it is free and works normally ( set it and forget it ).

The kannel is configured via the command line, which is not a particular problem for
me personally ( there is no GUI ). You will have to carefully read the
documentation and forget about any support. The application has not been updated by
its creators since October 20, 2010.

Monitoring of the server's operation is carried out through the Web interface - a
simple application in PHP, included in the kannel package.

The server consists of several daemons (hereinafter referred to as binaries):

1. bearerbox - the main part of the application that routes messages from any server
daemons to the operator;
2. smsbox - a daemon that allows you to send SMS via the http protocol;
3. wapbox - wap gateway (works over the UDP protocol, is used to display WML pages and
is not discussed in this article);

Additional demons:

1. sqlbox - a daemon that allows you to send SMS via writing to a MySQL database;
2. opensmppbox - SMPP gateway for connecting child servers using the SMPP protocol;

Important! This manual does not contain information on setting up USB modems for
SMS transmission.

Installing additional software


$ sudo su

# apt-get update && apt-get install mysql-server php5-cli nginx php5-fpm gcc make

Assembly (compilation and installation) kannel


To install kannel, you can use deb packages sudo apt-get install kannel , but by default
only wapbox and smsbox will be installed, and in order for smsbox to work, you need
to uncomment the directive in the /etc/default/kannel . I recommend installing kannel
from the deb package to see how it works and runs.

If you install opensmppbox, sqlbox, you must not use compiled packages and ready-
made binaries. All packages need to be collected on the usage server. This is due to
the fact that when building additional packages, the newly built kannel libraries are
used. If the main server has a different version than the additional daemons, then
errors like opensmppbox multi-message die are possible ; this is due to the already
built kannel libraries.

To install kannel with database support, you need the mysql client library.

Install them:

# apt-get install libmysqlclient-dev libxml2-dev

Compiling kannel from sources


Download kannel sources from the official website .

# cd /tmp

# wget http://www.kannel.org/download/kannel-snapshot.tar.gz

# tar -zxvf kannel-snapshot.tar.gz

# cd /tmp/kannel-snapshot

# ./configure --with-mysql --with-mysql-dir=/usr/include/mysql/ --enable-start-stop-


daemon=yes --enable-docs=yes

# make

# make install

Let's assemble sqlbox (continuation of the previous listing)

Let's go to the folder with the source code

# cd /tmp/kannel-snapshot/addons/sqlbox/
Next, copy the mysql header files to the source code folder.

Important! If the folder gw and headers already exist, then there is no need to copy
and you can skip the next listing.

# mkdir gw

# cp -R /usr/include/mysql/ gw/

Then we collect sqlbox

# ./configure --with-kannel-dir=/usr/local/include/kannel/

# make

# make install

Let's immediately assemble opensmppbox so that smpp client gateways can connect to
us (continuation of the previous listing):

# cd /tmp/kannel-snapshot/addons/opensmppbox/

# ./configure --with-kannel-dir=/usr/local/include/kannel/

# make

# make install

Let's create the databases:

# mysql -u root -p

mysql> create database smsbearerbox character set utf8 collate utf8_general_ci;

Query OK, 1 row affected (0.00 sec)

mysql> create user bearerbox@localhost identified by 'HW4Qh';

Query OK, 0 rows affected (0.07 sec)

mysql> grant all privileges on smsbearerbox.* to bearerbox@localhost;

Query OK, 0 rows affected (0.01 sec)

mysql> create database smssqlbox character set utf8 collate utf8_general_ci;

Query OK, 1 row affected (0.00 sec)

mysql> create user sqlbox@localhost identified by '98D9D';

Query OK, 0 rows affected (0.00 sec)


mysql> grant all privileges on smssqlbox.* to sqlbox@localhost;

Query OK, 0 rows affected (0.01 sec)

Let's create a mysql dump file:

# nano /tmp/kannel_dump.sql

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;

/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;

/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;

/*!40101 SET NAMES utf8 */;

/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;

/*!40103 SET TIME_ZONE='+00:00' */;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sms_db` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `sms_db`;

DROP TABLE IF EXISTS `dlr_sms`;

/*!40101 SET @saved_cs_client = @@character_set_client */;

/*!40101 SET character_set_client = utf8 */;

CREATE TABLE `dlr_sms` (

`source` varchar(255) NOT NULL,

`destination` varchar(255) NOT NULL,

`time` datetime NOT NULL,

`smsc_id` varchar(255) NOT NULL,

`sms_id` varchar(255) NOT NULL,


`mask` varchar(255) NOT NULL,

`status` varchar(255) NOT NULL,

`msgdata` varchar(255) NOT NULL,

`msgtime` datetime NOT NULL,

`charset` varchar(255) NOT NULL,

`coding` varchar(255) NOT NULL,

`smssys_id` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*!40101 SET character_set_client = @saved_cs_client */;

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `smsbearerbox` /*!40100 DEFAULT CHARACTER SET utf8
*/;

USE `smsbearerbox`;

DROP TABLE IF EXISTS `dlr_sms_kannel`;

/*!40101 SET @saved_cs_client = @@character_set_client */;

/*!40101 SET character_set_client = utf8 */;

CREATE TABLE `dlr_sms_kannel` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`smsc` varchar(20) DEFAULT NULL,

`ts` bigint(10) DEFAULT NULL,

`destination` varchar(20) DEFAULT NULL,

`source` varchar(20) DEFAULT NULL,

`service` varchar(20) DEFAULT NULL,

`url` text,

`mask` varchar(20) DEFAULT NULL,

`status` varchar(20) DEFAULT NULL,

`boxc` varchar(20) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=90107 DEFAULT CHARSET=utf8;


/*!40101 SET character_set_client = @saved_cs_client */;

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `smssqlbox` /*!40100 DEFAULT CHARACTER SET utf8
*/;

USE `smssqlbox`;

DROP TABLE IF EXISTS `send_sms`;

/*!40101 SET @saved_cs_client = @@character_set_client */;

/*!40101 SET character_set_client = utf8 */;

CREATE TABLE `send_sms` (

`sql_id` bigint(20) NOT NULL AUTO_INCREMENT,

`momt` enum('MO','MT') DEFAULT NULL,

`sender` varchar(20) DEFAULT NULL,

`receiver` varchar(20) DEFAULT NULL,

`udhdata` blob,

`msgdata` text,

`time` bigint(20) DEFAULT NULL,

`smsc_id` varchar(255) DEFAULT NULL,

`service` varchar(255) DEFAULT NULL,

`account` varchar(255) DEFAULT NULL,

`id` bigint(20) DEFAULT NULL,

`sms_type` bigint(20) DEFAULT NULL,

`mclass` bigint(20) DEFAULT NULL,

`mwi` bigint(20) DEFAULT NULL,

`coding` bigint(20) DEFAULT NULL,

`compress` bigint(20) DEFAULT NULL,

`validity` bigint(20) DEFAULT NULL,

`deferred` bigint(20) DEFAULT NULL,

`dlr_mask` bigint(20) DEFAULT NULL,

`dlr_url` varchar(255) DEFAULT NULL,


`pid` bigint(20) DEFAULT NULL,

`alt_dcs` bigint(20) DEFAULT NULL,

`rpi` bigint(20) DEFAULT NULL,

`charset` varchar(255) DEFAULT NULL,

`boxc_id` varchar(255) DEFAULT NULL,

`binfo` varchar(255) DEFAULT NULL,

`meta_data` varchar(255) DEFAULT NULL,

`foreign_id` bigint(20) DEFAULT NULL,

PRIMARY KEY (`sql_id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `sent_sms`;

/*!40101 SET @saved_cs_client = @@character_set_client */;

/*!40101 SET character_set_client = utf8 */;

CREATE TABLE `sent_sms` (

`sql_id` bigint(20) NOT NULL AUTO_INCREMENT,

`momt` enum('MO','MT','DLR') DEFAULT NULL,

`sender` varchar(20) DEFAULT NULL,

`receiver` varchar(20) DEFAULT NULL,

`udhdata` blob,

`msgdata` text,

`time` bigint(20) DEFAULT NULL,

`smsc_id` varchar(255) DEFAULT NULL,

`service` varchar(255) DEFAULT NULL,

`account` varchar(255) DEFAULT NULL,

`id` bigint(20) DEFAULT NULL,

`sms_type` bigint(20) DEFAULT NULL,

`mclass` bigint(20) DEFAULT NULL,

`mwi` bigint(20) DEFAULT NULL,

`coding` bigint(20) DEFAULT NULL,


`compress` bigint(20) DEFAULT NULL,

`validity` bigint(20) DEFAULT NULL,

`deferred` bigint(20) DEFAULT NULL,

`dlr_mask` bigint(20) DEFAULT NULL,

`dlr_url` varchar(255) DEFAULT NULL,

`pid` bigint(20) DEFAULT NULL,

`alt_dcs` bigint(20) DEFAULT NULL,

`rpi` bigint(20) DEFAULT NULL,

`charset` varchar(255) DEFAULT NULL,

`boxc_id` varchar(255) DEFAULT NULL,

`binfo` varchar(255) DEFAULT NULL,

`meta_data` varchar(255) DEFAULT NULL,

`foreign_id` bigint(20) DEFAULT NULL,

PRIMARY KEY (`sql_id`)

) ENGINE=MyISAM AUTO_INCREMENT=238489 DEFAULT CHARSET=utf8;

/*!40101 SET character_set_client = @saved_cs_client */;

/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;

/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

Let's restore the database dump:

# mysql -uroot -p < /tmp/kannel_dump.sql

The pre-installation process is complete. All binaries are located in the


directory /usr/local/sbin
Box settings
The tasks are different and servers need to be configured in completely different ways,
somewhere there is sqlbox, somewhere opensmppbox, somewhere just smsbox.
Therefore, in the process of work, an understanding emerged of how configuration
files should be located for versatility and convenience.

The entire configuration is located in the directory /etc/kannel/ :

# cd /etc/kannel

# tree

├── dlr-bearerbox.conf

├── kannel.conf # основной файл конфигурации kannel

├── opensmppbox.conf # основной файл конфигурации opensmppbox

├── smsbox # учетные записи для подключения к smsbox по http

│ └── users.conf

├── opensmppbox # клиенты opensmppbox

│ └── users.conf

├── smsc # настройки SMPP (операторы к кому подключаемся)

│ └── smsc.conf

├── routing # роутер соответствие номера и smsbox-id для входящих смс

│ └── routing.conf

├── services # sms сервисы

│ └── services.conf

├── smsbox.conf # основной файл конфигурации smsbox

└── sqlbox.conf # основной файл конфигурации sqlbox

Important! Pay attention to the log files, as well as the ports that are opened. All
boxes communicate with each other via TCP connections. Also look at which configs
are included in which.

Let's agree that all configuration listings contain <что-то в треугольных скобках> user
settings - logins, passwords, etc.
Configuration example:

# nano /etc/kannel/kannel.conf

# ------ CORE GROUP ------

group = core

wdp-interface-name = "*"

admin-port = 13000

smsbox-port = 13001

admin-password = <admin_password_for_http>

admin-deny-ip = "*.*.*.*"

admin-allow-ip = "127.0.0.1;192.168.*.*"

log-file = "/var/log/kannel/bearerbox.log"

log-level = 0

access-log = "/var/log/kannel/access.log"

box-allow-ip = "127.0.0.1;*.*.*.*"

# для хранения очереди смс в базе данных mysql

dlr-storage = mysql

# для хранения очереди смс в файле

#store-type = spool

#store-location = "/var/spool/kannel"

#store-file = "/var/log/kannel/store_sms"

include = "/etc/kannel/dlr-bearerbox.conf"

include = "/etc/kannel/smsс/smsc.conf"

include = "/etc/kannel/smsbox.conf"

# ------ SEND-SMS USERS ------

include = "/etc/kannel/smsbox/users.conf"

# ------ SMS-SEVICE ------


include = "/etc/kannel/services/services.conf"

# ------ INBOUND-SMS-ROUTING -----

include = "/etc/kannel/routing/routing.conf"

Settings for connecting to an operator usually contain host, login, password, port, as
well as settings for converting international (national) numbers , operating mode
(transceiver - reception and transmission over one connection), interface version, etc.:

# nano /etc/kannel/smsс/smsc.conf

#------ SMSC GROUP ------

#group = smsc #тестовый sms центр для проверки работоспособности

#smsc-id = fakesmsc

#smsc = fake

#port = 10000

group = smsc

smsc = smpp

smsc-id = <smsc-id> # уникальное имя для подключения

system-type = VMA

host = <operator_host>

port = 9932

transceiver-mode = false

receive-port = 9932

interface-version = 34

smsc-username = <username>

smsc-password = <secret>

enquire-link-interval = 270

source-addr-ton = 2

source-addr-npi = 1

dest-addr-ton = 2

dest-addr-npi = 1
msg-id-type = 0x03

log-file = "/var/log/kannel/<operator>.log"

log-level = 0

Megaphone settings:

group = smsc

smsc = smpp

smsc-id = megafon

system-type = VMA

host = <megafon_host>

port = 9932

transceiver-mode = false

interface-version = 34

smsc-username = <username>

smsc-password = <secret>

enquire-link-interval = 270

reconnect-delay = 60

connection-timeout = 120

source-addr-ton = 2

source-addr-npi = 1

dest-addr-ton = 2

dest-addr-npi = 1

msg-id-type = 0x03

log-file = "/var/log/kannel/megafon.log"

log-level = 0

MTS settings:

group = smsc

smsc = smpp

smsc-id = mts

system-type = VMA
host = <mts_host>

port = 5000

transceiver-mode = true

interface-version = 34

smsc-username = <username>

smsc-password = <secret>

enquire-link-interval = 60

source-addr-ton = 1

source-addr-npi = 1

dest-addr-ton = 1

dest-addr-npi = 1

msg-id-type = 0x03

log-file = "/var/log/kannel/mts.log"

log-level = 0

Settings sms-telecom.by

group = smsc

smsc = smpp

smsc-id = smstelecom

system-type = VMA

host = <smstelecom_host>

port = 2775

transceiver-mode = false

interface-version = 34

smsc-username = <username>

smsc-password = <secret>

enquire-link-interval = 270

source-addr-ton = 2

source-addr-npi = 1

dest-addr-ton = 2

dest-addr-npi = 1
msg-id-type = 0x03

log-file = "/var/log/kannel/smstelecom.log"

log-level = 0

ZTE MF636 modem settings as smsc

# SMSC SETUP: ZTE INCORPORATED GSM Modem

group = smsc

smsc = at

smsc-id = ACMZTE

modemtype = ztemodem

device = /dev/ttyUSB1

allowed-prefix = "+998;998"

sms-center = +998930190000

#sim-buffering = true

my-number = +999988888888

speed = "default"

log-file = "/var/log/kannel/zte.log"

log-level = 0

# Modem SETUP

group = modems

id = ztemodem

name = "ZTE"

init-string = "ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0;+CNMI=3,1,0,0,0;+CMGF=1"

detect-string = "ZTE MF110/MF636"

#need-sleep = true

#message-storage = "SM"

no-smsc = true

keepalive-cmd = "AT+CBC;+CSQ"

broken = true
Huawei E173 modem settings as smsc (Sadulla, thank you very much for these
settings.)

#SMSC SETUP: HUAWEI E173 GSM Mod

group = smsc

smsc = at

connect-allow-ip = 127.0.0.1

port = 13013

host = "localhost"

smsc-id = Ucell

modemtype = auto

device = /dev/ttyUSB0

speed = 9600

sms-center = "+998000000000"

my-number = "+99888888888"

group = modems

id = huawei_e173

name = "Huawei E173"

detect-string = "huawei"

init-string = "AT+CFUN=1"

init-string= “ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0″

init-string = “AT+CNMI=3,2,0,0,0″

init-string = “AT+CMEE=2;+CNMI=3,1,0,0,0″

reset-string = “ATZ”

need-sleep = true

keepalive-cmd = “AT+CBC;+CSQ”

enable-mms = true

message-storage=”SM”

smsbox settings:

# nano /etc/kannel/smsbox.conf
# ------ SMSBOX GROUP ------

group = smsbox

smsbox-id = smsbox-web

bearerbox-host = 127.0.0.1

bearerbox-port = 13005

sendsms-port = 13013

log-file = "/var/log/kannel/smsbox.log"

log-level = 0

access-log = "/var/log/kannel/sms-access.log"

sendsms-chars = "0123456789+"

#переопределяет номер отправителя для смс бокса

global-sender = "<sender-nuber>"

Settings for smsbox users, users who send sms via http:

# nano /etc/kannel/smsbox/users.conf

# ------ SENDSMS USERS GROUP ------

group = sendsms-user

username = satssmsgateway

password = Q8EM8Q1BJ5

max-messages = 10

concatenation = true

default-smsc = megafon

SMS service settings:

# nano /etc/kannel/services/services.conf

# ------ SMS SERVICE EXAMPLE ------

group = sms-service
keyword = nop

text = "You asked nothing and I did it!"

# there should be default always

group = sms-service

keyword = default

text = "No service specified"

Incoming SMS routing settings:

# nano /etc/kannel/routing/routing.conf

# ------ SMS ROUTING ------

group = smsbox-route

smsbox-id = <opensmppbox-user-1>

shortcode = "<shortcode-1>"

group = smsbox-route

smsbox-id = <opensmppbox-user-2>

shortcode = "<shortcode-2>"

group = smsbox-route

smsbox-id = <opensmppbox-user-3>

shortcode = "<shortcode-3>"

sqlbox settings

# nano /etc/kannel/sqlbox.conf

# ------ SQLBOX GROUP ------

group = sqlbox

id = "sqlbox-db"
sql-engine = mysql

smsbox-id = "sqlbox-mysql"

bearerbox-port = 13001

smsbox-port = 13005

smsbox-port-ssl = false

sql-log-table = sent_sms

sql-insert-table = send_sms

log-file = "/var/log/kannel/sqlbox.log"

log-level = 0

# ------ MYSQL CONNECTION ------

group = mysql-connection

id = "sqlbox-db"

host = localhost

username = sqlbox

password = 98D9D

database = smssqlbox

max-connections = 25

Settings for connecting to the database, as well as storing SMS delivered by smsbox

# nano dlr-bearerbox.conf

# ------ MYSQL CONNECTION ------

group = mysql-connection

id = bearerbox-dlr

host = localhost

username = bearerbox

password = HW4Qh

database = smsbearerbox

max-connections = 10
# ------ DLR STORAGE CONFIGURATION ------

group = dlr-db

id = bearerbox-dlr

table = dlr_sms_kannel

field-smsc = smsc

field-timestamp = ts

field-destination = destination

field-source = source

field-service = service

field-url = url

field-mask = mask

field-status = status

field-boxc-id = boxc

opensmppbox settings
opensmppbox has a separate configuration file, which contains separate routing

# opensmppbox.conf

group = core

dlr-storage = internal

store-file = "/var/log/kannel/smpp_store_sms"

#the following is just standard dlr configuration

# this group defines your opensmppbox

group = opensmppbox

opensmppbox-id = smppbox

opensmppbox-port = 19933

# we connect to the following host as a box

bearerbox-host = 127.0.0.1
bearerbox-port = 13001

log-level = 0

log-file = "/var/log/kannel/opensmppbox.log"

our-system-id = satssmpp

route-to-smsc = <smsc-id>

# see sample smpplogins.txt

smpp-logins = "/etc/kannel/opensmppbox/users.conf"

# If you set usesmppbox-id, you must set use-systemid-as-smsboxid, too

# See documentation for details of this flag.

use-systemid-as-smsboxid = yes

#Rules to route MOs. Routing is based either on smsc id,

# shortcode or both.

#group = client-route

#client-id = <client-id-1>, <client-id-2>

#smsc-id = <operator>

Launch scripts
These scripts are based on the original scripts that come with kannel when installed
from the deb package. They differ from the FreeBSD startup scripts in that they use
utilities /lib/lsb/init-functions that are only available in Debian. The main task of
these scripts is to launch a process with a specific configuration file, create a PID file
if necessary and kill the process. There is no magic.

Let's create launch files for the SMPP gateway binaries:

1. To run bearerbox, sqlbox, smsbox


2. To run opensmppbox
All binaries must be launched with a "parachute". If the process fails, the parachute
picks it up again. In order not to crash the entire server, opensmppbox is launched
separately.

The file in which the default boxes for launch are registered

# nano /etc/default/kannel

#START_WAPBOX=1

START_SMSBOX=1

START_SQLBOX=1

START_OPENSMPPBOX=1

Let's create launch scripts:

# nano /etc/init.d/kannel

#!/bin/sh

# Start/stop the Kannel boxes: One bearer box and one WAP box.

# This is the default init.d script for Kannel. Its configuration is

# appropriate for a small site running Kannel on one machine.

# Make sure that the Kannel binaries can be found in $BOXPATH or somewhere

# else along $PATH. run_kannel_box has to be in $BOXPATH.

### BEGIN INIT INFO

# Provides: kannel

# Required-Start: $local_fs $remote_fs

# Required-Stop: $local_fs $remote_fs

# Should-Start: $network $named

# Should-Stop: $network $named

# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6

# Short-Description: SMS and WAP gateway

# Description: Kannel is a gateway for connecting WAP phones to the

# Internet. It also works as an SMS gateway.

### END INIT INFO

. /lib/lsb/init-functions

BOXPATH=/usr/local/sbin

PIDFILES=/var/run/kannel

CONF=/etc/kannel/kannel.conf

SMSBOX_CONF=/etc/kannel/smsbox.conf

SQL_CONF=/etc/kannel/sqlbox.conf

PATH=$BOXPATH:$PATH

# On Debian, the most likely reason for the bearerbox not being available

# is that the package is in the "removed" or "unconfigured" state, and the

# init.d script is still around because it's a conffile. This is normal,

# so don't generate any output.

test -x $BOXPATH/bearerbox || exit 0

test -r /etc/default/kannel && . /etc/default/kannel

if [ ! -d $PIDFILES ]

then

mkdir $PIDFILES

chown kannel:root $PIDFILES

fi

case "$1" in
start)

log_progress_msg "start bearerbox"

log_daemon_msg "start bearerbox"

start-stop-daemon --start --quiet \

--pidfile $PIDFILES/kannel_bearerbox.pid \

--chuid kannel \

--exec $BOXPATH/run_kannel_box \

-- \

--pidfile $PIDFILES/kannel_bearerbox.pid \

--no-extra-args \

$BOXPATH/bearerbox -v 4 -- $CONF

sleep 1

test ! -z $START_SQLBOX && (

log_progress_msg "start sqlbox"

log_daemon_msg "start sqlbox"

start-stop-daemon --start --quiet \

--pidfile $PIDFILES/kannel_sqlbox.pid \

--chuid kannel \

--exec $BOXPATH/run_kannel_box \

-- \

--pidfile $PIDFILES/kannel_sqlbox.pid \

--no-extra-args \

$BOXPATH/sqlbox -v 4 -- $SQL_CONF

sleep 1

test ! -z $START_SMSBOX && (

log_progress_msg "start smsbox"

log_daemon_msg "start smsbox"

start-stop-daemon --start --quiet \

--pidfile $PIDFILES/kannel_smsbox.pid \

--chuid kannel \
--exec $BOXPATH/run_kannel_box \

-- \

--pidfile $PIDFILES/kannel_smsbox.pid \

--no-extra-args \

$BOXPATH/smsbox -v 4 -- $CONF

log_end_msg 0

;;

stop)

test ! -z $START_SMSBOX && (

log_progress_msg "stop smsbox"

log_daemon_msg "stop smsbox"

start-stop-daemon --stop --quiet \

--pidfile $PIDFILES/kannel_smsbox.pid \

--exec $BOXPATH/run_kannel_box

test ! -z $START_SQLBOX && (

log_progress_msg "stop sqlbox"

log_daemon_msg "stop sqlbox"

start-stop-daemon --stop --quiet \

--pidfile $PIDFILES/kannel_sqlbox.pid \

--exec $BOXPATH/run_kannel_box

log_progress_msg "stop bearerbox"

log_daemon_msg "stop bearerbox"

start-stop-daemon --stop --quiet \

--pidfile $PIDFILES/kannel_bearerbox.pid \

--exec $BOXPATH/run_kannel_box

log_end_msg 0

;;
reload)

# We don't have support for this yet.

exit 1

;;

restart|force-reload)

$0 stop

sleep 1

$0 start

;;

*)

echo "Usage: $0 {start|stop|restart|force-reload}"

exit 1

esac

exit 0

# nano /etc/init.d/opensmppbox

#!/bin/sh

# Start/stop the Kannel boxes: One bearer box and one WAP box.

# This is the default init.d script for Kannel. Its configuration is

# appropriate for a small site running Kannel on one machine.

# Make sure that the Kannel binaries can be found in $BOXPATH or somewhere

# else along $PATH. run_kannel_box has to be in $BOXPATH.

### BEGIN INIT INFO


# Provides: kannel

# Required-Start: $local_fs $remote_fs

# Required-Stop: $local_fs $remote_fs

# Should-Start: $network $named

# Should-Stop: $network $named

# Default-Start: 2 3 4 5

# Default-Stop: 0 1 6

# Short-Description: SMS and WAP gateway

# Description: Kannel is a gateway for connecting WAP phones to the

# Internet. It also works as an SMS gateway.

### END INIT INFO

. /lib/lsb/init-functions

BOXPATH=/usr/local/sbin

PIDFILES=/var/run/kannel

SMPPBOX_CONF=/etc/kannel/opensmppbox.conf

PATH=$BOXPATH:$PATH

# On Debian, the most likely reason for the bearerbox not being available

# is that the package is in the "removed" or "unconfigured" state, and the

# init.d script is still around because it's a conffile. This is normal,

# so don't generate any output.

test -x $BOXPATH/opensmppbox || exit 0

test -r /etc/default/kannel && . /etc/default/kannel

if [ ! -d $PIDFILES ]

then

mkdir $PIDFILES

chown kannel:root $PIDFILES


fi

case "$1" in

start)

log_daemon_msg "Starting opensmppbox"

start-stop-daemon --start --quiet \

--pidfile $PIDFILES/kannel_opensmppbox.pid \

--chuid kannel \

--exec $BOXPATH/run_kannel_box \

-- \

--pidfile $PIDFILES/kannel_opensmppbox.pid \

--no-extra-args \

$BOXPATH/opensmppbox -v 4 $SMPPBOX_CONF

;;

stop)

log_daemon_msg "Stopping opensmppbox"

start-stop-daemon --stop --quiet \

--pidfile $PIDFILES/kannel_opensmppbox.pid \

--exec $BOXPATH/run_kannel_box

log_end_msg 0

;;

reload)

# We don't have support for this yet.

exit 1

;;

restart|force-reload)

$0 stop

sleep 1
$0 start

;;

*)

echo "Usage: $0 {start|stop|restart|force-reload}"

exit 1

esac

exit 0

Set launch rights

# chmod +x /etc/init.d/kannel

# chmod +x /etc/init.d/opensmppbox

Startup script option for FreeBSD:

#!/bin/sh

# Configuration file

CONF=/usr/local/etc/kannel/kannel.conf

SQLCONF=/usr/local/etc/kannel/sqlbox.conf

# Kannel boxes

BEARERBOX=/usr/local/sbin/bearerbox

SMSBOX=/usr/local/sbin/smsbox

SQLBOX=/usr/local/sbin/sqlbox

# Debug level: 0..4

DEBUGLEVEL=0

# Kannel user account


USER=kannel

# Check that boxes and config are ok

[ -x $BEARERBOX ] || exit 0

[ -x $SMSBOX ] || exit 0

[ -f $CONF ] || exit 0

case "$1" in

start)

echo -n "Starting bearerbox... "

$BEARERBOX -v $DEBUGLEVEL --daemonize --user $USER $CONF &

echo "done"

echo -n

sleep 1

echo -n "Starting sqlbox... "

$SQLBOX -v $DEBUGLEVEL --daemonize --user $USER $SQLCONF &

echo "done"

echo -n

sleep 1

echo -n "Starting smsbox... "

$SMSBOX -v $DEBUGLEVEL --daemonize --user $USER $CONF &

echo "done"

;;

stop)

echo -n "Shutting down smsbox... "

/etc/rc.d/killall smsbox

echo "done"

sleep 1
echo -n "Shutting down sqlbox... "

/etc/rc.d/killall sqlbox

echo "done"

sleep 1

echo -n "Shutting down bearerbox... "

/etc/rc.d/killall bearerbox

echo "done"

;;

restart)

$0 stop

sleep 1

$0 start

;;

*)

echo "Usage: kannelctl {start|stop|restart}"

exit 1

esac

exit 0

Setting up monitoring and test sending SMS via


smsbox
The smsbox comes with kannel-monitor ( /tmp/kannel-snapshot/contrib ). This is a PHP
application with which you can view the state of a kannel through a browser. To
deploy the application, you need to install a web server. For us it is nginx with php-
fpm. Server setup is described in another article nginx php-fpm . In that same
directory there are also scripts in Python, Perl and shell. A very useful directory.
[flickr:id=35805484390]

Form for sending SMS via smsbox. This is a small PHP application that processes the
form, determines the presence of Russian and sends it to smsbox for conversion, while
writing the sms identifier to the dlr_sms database, and when sending it sends a
callback, thanks to which, when the status is received, it is written to the database.

[flickr:id=35805261370]

Scheme of how sending works: monitoring/sendsms (port 13013, callback=dlr.php?...)


<=> smsbox <=> bearerbox <===> smsc

Setting up locations in nginx (php-fpm on port 9000)

location /kannel-monitor/ {

root /usr/local/www;

index index.php;

location /kannel-sendsms/ {

root /usr/local/www;

index index.php;

location ~ \.php$ {

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /usr/local/www$fastcgi_script_name;

include fastcgi_params;

fastcgi_param DOCUMENT_ROOT /usr/local/www;

Copy the kannel-monitor files:

# cp -R /tmp/kannel-snapshot/contrib/kannel-monitor /usr/local/www/
Let's edit the lines with the settings in accordance with the settings kannel.conf :

nano /usr/local/www/kannel-monitor/index.php

$configs = array(

array("base_url" => "http://127.0.0.1:13000",

"status_passwd" => "",

"admin_passwd" => "fnccvjkmysq",

"name" => "Kannel 1"

)/*,

array( "base_url" => "http://127.0.0.1:23000",

"status_passwd" => "",

"admin_passwd" => "fnccvjkmysq",

"name" => "Kannel 2"

),

array( "base_url" => "http://127.0.0.1:33000",

"status_passwd" => "",

"admin_passwd" => "fnccvjkmysq",

"name" => "Kannel 3"

)/**/

);

We create directories for the application to work and the necessary files

# mkdir /usr/local/www/kannel-sendsms

# cd /usr/local/www/kannel-sendsms

Settings file:

# nano config.inc

<?php

// Include file for SMS interface.

// These variables MUST match your kannel.conf configuration


$bearerboxhost = "localhost";

define("BEARERBOX_HOST", "localhost");

define("SENDSMS_PORT", "13013");

define("ADMIN_PORT", "13000");

define("ADMIN_PASSWORD", "fnccvjkmysq");

define("USERNAME", "satssmsgateway");

define("PASSWORD", "Q8EM8Q1BJ5");

define("GLOBAL_SENDER", "<from-number>");

?>

# nano functions.inc

<?php

function http_send($URL, $port)

$connection = fsockopen(BEARERBOX_HOST, $port, &$error_number, &$error_description,


60);

if (!$connection) {

echo "<p>$error_description ($error_number)<br>\n";

echo "The SMS message was NOT sent!</p>\n";

} else {

socket_set_blocking($connection, false);

echo "$URL";

fputs($connection, "GET $URL HTTP/1.0\r\n\r\n");

while (!feof($connection)) {

$myline = fgets($connection, 128);

switch ($myline) {

case (strstr($myline, 'Content-')):

break;

case (strstr($myline, 'HTTP/1')):


break;

case "":

break;

case "\r\n":

break;

default:

echo "<p>" . $myline . "</p>";

fclose($connection);

function octstr_append_cstr($mystring)

$mystring2 = "";

for ($pos = 0; $pos < strlen($mystring); $pos++) {

$mystring2 .= sprintf("%%%02x", $mystring[$pos]);

return ($mystring2);

?>

File index.php :

<html>

<head>

<meta http-equiv='content-type' content='text/html; charset=utf-8'>

<title>Отправить СМС</title>

</head>

<body bgcolor="#FFFFFF" text="#000000">


<?php

include("config.inc");

include("functions.inc");

$this_page = $_SERVER['PHP_SELF'];

if ($_GET['submit']) {

$to = $_POST['to'];

$text = $_POST['text'];

if ((strlen($to)) && (strlen($text))) {

print $text;

$sms_id = uniqid();

$ptrn = '~([а-яА-ЯёЁ]+)~ui';

if (preg_match($ptrn, $text)) {

//Найден русский текст";

//$text = urlencode(@iconv("utf-8","ucs-2be", $text));

$coding = "&coding=2";

} else {

$coding = "&coding=0";

$text = urlencode($text);

$dlr_url = "http://127.0.0.1/dlr.php?sms_id=" . $sms_id . "&from=%p&to=%P&smsc=


%i&dlr-type=%d&text=%b&time=%t&charset=%C&coding=%c&smssys_id=%I";

echo "Отправляется сообщение: <b>\"$text\"</b> получателю <b>$to</b>...<br>\n";

$URL = "/cgi-bin/sendsms?username=" . USERNAME . "&password=" . PASSWORD . "&from="


. GLOBAL_SENDER . "&to=$to&text=" . $text . $coding . "&charset=UTF-8&dlr-mask=31&dlr-url="
. urlencode($dlr_url); /*mask = 1+2+4+8+16 = 31*/

http_send($URL, SENDSMS_PORT);

} else {
echo "Не заполнен текст или номер получателя.";

echo "<address><a href=\"$this_page\">Отправить еще СМС</a></address>\n";

} else {

?>

<h1>Отправка СМС сообщений</h1>

<form name="sendsms" method="post" action="<?php echo "$this_page" ?>?submit=true">

<p>

Номер телефона (в формате: 7XXXxxxxxxx):

<br>

<input type="text" size="30" name="to">

</p>

<p>

Сообщение:

<br>

<textarea cols="20" rows="5" name="text"></textarea>

</p>

<input type="submit" value="Отправить" name="submit">

<input type="reset" value="Сброс">

<br>

</form>

<?php

?>

<p>

</p>
<hr>

<table border="0" width="100%">

<tr>

<td width="100%">

<address><a href="/">На портал</a></address>

</td>

</tr>

</table>

</body>

</html>

Script for changing SMS status, with a mark in the database

# nano dlr.php

<?php

$server = 'localhost';

$username = '<db_login>';

$password = '<db_password>';

$dbname = 'sms_db';

$db = mysql_connect($server, $username, $password);

if (!$db) {

die('Невозможно соединиться с базой данных: ' . mysql_error());

$db_selected = mysql_select_db($dbname, $db);

if (!$db_selected) {

die ('Невозможно выбрать базу данных: ' . mysql_error());

}
$msgdata = $_GET['text'];

$original_time = $_GET['time'];

$smsc = $_GET['smsc'];

$sender = $_GET['from'];

$receiver = $_GET['to'];

$dlr = $_GET['dlr-type'];

$sms_id = $_GET['sms_id'];

$smssys_id = $_GET['smssys_id'];

$charset = $_GET['charset'];

$coding = $_GET['coding'];

$report = array(

1 => "Delivery success",

2 => "Delivery failure",

4 => "Message buffirized",

8 => "SMSC submit",

16 => "SMSC reject"

);

switch ($dlr) {

case '8':

$dt = date("Y-m-d");

$ti = date("H:i:s");

$time = $dt . " " . $ti;

$result_8 = mysql_query("INSERT INTO dlr_sms (source, destination, time, smsc_id,


sms_id, mask, status, msgdata, msgtime, charset, coding,smssys_id) VALUES ('" . $sender .
"', '" . $receiver . "', '" . $time . "', '" . $smsc . "', '" . $sms_id . "', '" . $dlr .
"', '" . $report[8] . "', '" . $msgdata . "', '" . $original_time . "', '" . $charset . "',
'" . $coding . "', '" . $smssys_id . "');");

break;

case '1':
$dt = date("Y-m-d");

$ti = date("H:i:s");

$time = $dt . " " . $ti;

$result_1 = mysql_query("UPDATE dlr_sms SET time = '" . $time . "', mask = '" .
$dlr . "', status = '" . $report[1] . "' WHERE destination = '" . $receiver . "' AND
smssys_id = '" . $smssys_id . "';");

break;

case '2':

$dt = date("Y-m-d");

$ti = date("H:i:s");

$time = $dt . " " . $ti;

$result_2 = mysql_query("UPDATE dlr_sms SET time = '" . $time . "', mask = '" .
$dlr . "', status = '" . $report[2] . "' WHERE destination = '" . $receiver . "' AND
smssys_id = '" . $smssys_id . "';");

break;

case '4':

$dt = date("Y-m-d");

$ti = date("H:i:s");

$time = $dt . " " . $ti;

$result_4 = mysql_query("UPDATE dlr_sms SET time = '" . $time . "', mask = '" .
$dlr . "', status = '" . $report[4] . "' WHERE destination = '" . $receiver . "' AND
smssys_id = '" . $smssys_id . "';");

break;

case '16':

$dt = date("Y-m-d");

$ti = date("H:i:s");
$time = $dt . " " . $ti;

$result_16 = mysql_query("INSERT INTO dlr_sms (source, destination, time, smsc_id,


sms_id, mask, status, msgdata, msgtime, charset, coding,smssys_id) VALUES ('" . $sender .
"', '" . $receiver . "', '" . $time . "', '" . $smsc . "', '" . $sms_id . "', '" . $dlr .
"', '" . $report[16] . "', '" . $msgdata . "','" . $original_time . "', '" . $charset . "',
'" . $coding . "', '" . $smssys_id . "');");

break;

?>

Launch
Testing the launch

# service kannel start

# service kannel stop

# service opensmppbox start

# service opensmppbox stop

We check through monitoring through the browser http://<kannel-host>/kannel-

monitor/ and http://<kannel-host>/kannel-sendsms/ .

All is ready! Thank you for your attention. The article turned out to be long. If you
have any questions, write.

PS To send MMS and SMS, I configured the nowsms server, I get SMS and (MMS if
there is an authentication server). It works stably, the only drawback is that it is paid
and only for Windows.

PPS I posted my application on github , which I have been using for several years to
send SMS messages via kannel in python and django.
Repository https://github.com/sinyawskiy/djkannel

If the article was useful to you, please click on the advertisement. Thank you!
Using sqlbox and triggers to keep track of Kannel message
delivery reports
/*

This is a Mini HOW-TO in order to send sms messages via Kannel and sqlbox and keep track of
status information.
Author: Rene Kluwen <[email protected]>.
Many thanks to Alejandro to host this how-to on his Kannel blog. The text of this blog is
completely enclosed in comment blocks, so you can just copy and paste the whole post in your
favorite mysql editor and it will run the code (e.g. create the necessary tables, triggers and stored
procedures).
We only need sqlbox and bearerbox. In this example, smsbox is not used. Also we do not use an
http server for delivery reports.
Everything is done in Mysql.
To start, we assume that you have a working Kannel and Sqlbox installation. See the Kannel users
manual on how to set this up.
Next, we need to collect the following information:
– <sender_id>: The number (or text) that the messages appear to be sent from.
– <smsc>: The smsc that the messages will be submitted to.
– <sqlbox_id>: The ‘smsbox-id’ of your sqlbox instance.
We use these values as defaults in our trigger. Substitute them with your own values, below.

*/

/* first, we drop the table if it exists already, in case we are updating */

DROP TABLE IF EXISTS snd;


/* The following table holds our messages. The messages that are inserted in this table will
automatically be sent by Kannel (see trigger below) and the status fields of the message are
automatically updated once DLR reports of the message come in (see second trigger). */

CREATE TABLE `snd` (


`snd_id` bigint(20) NOT NULL auto_increment COMMENT 'Every message has a unique
id',
`snd_to` varchar(255) default NULL COMMENT 'The number that the message is sent
to',
`snd_txt` longtext COMMENT 'The body text of the message',
`snd_sentat` timestamp NOT NULL default CURRENT_TIMESTAMP COMMENT 'The time that
the message is inserted',
`snd_success` datetime default NULL COMMENT 'The time that the message was
delivered to the hand set',
`snd_failure` datetime default NULL COMMENT 'The time that the message failed',
`snd_submitted` datetime default NULL COMMENT 'The time that the message is
submitted to the smsc',
`snd_buffered` datetime default NULL COMMENT 'The time that the message is
buffered at the smsc',
`snd_rejected` datetime default NULL COMMENT 'The time that the message was
rejected',
`snd_intermediate` datetime default NULL COMMENT 'Time of intermediate status',
`snd_last` int(11) NOT NULL default '0',
PRIMARY KEY (`snd_id`)
) DEFAULT CHARSET=latin1 COMMENT='This table holds the messages that are sent,
including DLR values.';
/* first, we drop the trigger if it exists already, in case we are updating */

DROP TRIGGER IF EXISTS after_snd_insert;


/* The following trigger inserts appropriate values into the send_sms table. Kannel scans this table
and sends out any message that is entered, subsequently deleting it. Our message keeps being
held in the ‘snd’ table. We keep a reference to our record in `snd` by inserting `snd_id` in the
dlr_url place holder. */

CREATE TRIGGER after_snd_insert


AFTER INSERT ON snd
FOR EACH ROW BEGIN
/* Below we use some default values. Replace them with your own. Also replace
send_sms in case you configured a different
name for sql-insert-table in your sqlbox.conf */
INSERT INTO send_sms (momt, sender, receiver, msgdata, smsc_id, sms_type,
dlr_mask, dlr_url, boxc_id)
VALUES ('MT', '<sender_id>', NEW.snd_to, urlencode(NEW.snd_txt), '', 2, 31,
NEW.snd_id, '<sqlbox_id>');
END;
/* first, we drop the trigger if it exists already, in case we are updating */
DROP TRIGGER IF EXISTS after_sent_sms_insert;
/* The second and final trigger updates the status fields of our ‘snd’ table.
Kannel inserts all dlr reports in the sent_sms table. We pick up the information from there and use
it to update our original record in the snd table. Remember, we have the `snd_id` in the dlr_url
field. */
CREATE TRIGGER after_sent_sms_insert
/* again, replace sent_sms if you configured a different name for your sql-log-
table. */
AFTER INSERT ON sent_sms
FOR EACH ROW BEGIN
IF NEW.momt = 'DLR' THEN
CASE NEW.dlr_mask
WHEN 1 THEN UPDATE snd SET snd_success = FROM_UNIXTIME(NEW.time) WHERE
snd_id = NEW.dlr_url;
WHEN 2 THEN UPDATE snd SET snd_failure = FROM_UNIXTIME(NEW.time) WHERE
snd_id = NEW.dlr_url;
WHEN 4 THEN UPDATE snd SET snd_buffered = FROM_UNIXTIME(NEW.time)
WHERE snd_id = NEW.dlr_url;
WHEN 8 THEN UPDATE snd SET snd_submitted = FROM_UNIXTIME(NEW.time)
WHERE snd_id = NEW.dlr_url;
WHEN 16 THEN UPDATE snd SET snd_rejected = FROM_UNIXTIME(NEW.time)
WHERE snd_id = NEW.dlr_url;
WHEN 32 THEN UPDATE snd SET snd_intermediate = FROM_UNIXTIME(NEW.time)
WHERE snd_id = NEW.dlr_url;
ELSE UPDATE snd SET snd_last = NEW.dlr_mask WHERE snd_id = NEW.dlr_url;
END CASE;
END IF;
END
/* In the end, a listing of this helper function we need because sqlbox expects the msgdata field
urlencoded. */

DROP FUNCTION IF EXISTS urlencode;


CREATE FUNCTION urlencode (s VARCHAR(4096)) RETURNS VARCHAR(4096)
DETERMINISTIC
CONTAINS SQL
BEGIN
DECLARE c VARCHAR(4096) DEFAULT '';
DECLARE pointer INT DEFAULT 1;
DECLARE s2 VARCHAR(4096) DEFAULT '';

IF ISNULL(s) THEN
RETURN NULL;
ELSE
SET s2 = '';
WHILE pointer <= length(s) DO
SET c = MID(s,pointer,1);
IF c = ' ' THEN
SET c = '+';
ELSEIF NOT (ASCII(c) BETWEEN 48 AND 57 OR
ASCII(c) BETWEEN 65 AND 90 OR
ASCII(c) BETWEEN 97 AND 122) THEN
SET c = concat("%",LPAD(CONV(ASCII(c),10,16),2,0));
END IF;
SET s2 = CONCAT(s2,c);
SET pointer = pointer + 1;
END while;
END IF;
RETURN s2;
END;
/* end of helper function urlencode */

/* Usage example; substitute the given number (and text) with your own: */

INSERT INTO snd (snd_to, snd_txt) VALUES ('1234567890', 'My first example text to
send...');
/* After inserting this message, Kannel will send it and update it’s status fields automatically. */

You might also like