Bringing Telecommunications In-House - Part 1:
Asterisk

The first part in the series bringing my telecommunications in-house. This article will cover getting Asterisk working on my Home Server.

Telecommunications Versus E-Mail

This series of articles will undoubtedly cross with some of the other articles in the "Bringing E-Mail In-House" series of articles.

This series is also a continuation of my article/blog post on cheaper telephone calls. "Telecommunications" deserves to be its own series, however, because although the E-Mail series encompasses a lot of the things I have done (and will do) with regards to my network and ULA IPv6 network, and will undoubtedly involve things like DNS and (potentially) will later involve other things that should belong in this series, telecoms is probably just as complex as e-mail.

For the purpose of this series, references to "telecommunications" and "telecoms" excludes electronic mail, with "telecoms" being in reference to the traditional telco stuff - voice and text.

My previous article on SIP was less technical, so I will leave it in the money saving section. As this series is more technical and involves my home server (and probably my VPS at some point), I will place it in the computing articles section.

Just to recap: my Home Server is using Debian Stable, and the domain home.thejc.me.uk is updated by my Home Server using a script whenever it gets a new IP address from my ISP. It should be noted that I sometimes have to run that script manually, so I expect to have to deal with those issues at some point so I don't suddenly lose the ability to receive calls.

Installing Asterisk

The first thing to do is install Asterisk:

sudo apt-get install asterisk

When asked if I wanted to install all those packages, I entered y.

As I am in the UK, when setting up libvpb0 my answer was as follows:

ITU-T telephone code
44

Reasoning for Asterisk on My Home Server and The Plan

It has been years since I last used Asterisk. At the time I was running it on my Raspberry Pi. In fact one of the reasons for building my home server was because everything I needed my Raspberry Pi to do was too much for it to do. Anyway, the length of time combined with my poor memory means I need to look at some articles again.

The reason I am currently looking at using my Home Server instead of my VPS is similar to the reason I am not using my Raspberry Pi - resource usage. My Home Server currently has 8 GiB of RAM installed, whereas my VPS has 512 MiB of RAM. My VPS might have access to more powerful CPU(s), but the resources are shared with others and no amount of priority settings by me will give me higher priority for resources than what has been allocated to me (presumably time-based).

Anyway, I don't make that many phone calls nor do I send a lot of texts (as evidenced by my previous money saving SIP article), and I am regularly unreachable due to mental health issues, so the question of "high availability" is one that I'll need to balance. If my ISP connection (or the power) goes down, I will always have Groundwire on my mobile to fall back on.

In a later article I will deal with the issue of SMS, but at present I am undecided how I am going to actually do things. My current thought is that I will send them to my phone using some form of instant messenger (preferably encrypted).

Battery life on my iPhone 4S, and the fact there is no native SIP client like there is on Android is one of the issues I have recently been debating. The Three mobile network have a 321 pay as you go (PAYG) SIM available that offers texts at 2 pence each, data at 1 pence per Megabyte (Mebibyte?) and calls at 3 pence per minute. Although I was considering using it for my mobile, testing proved that SIP calls over the network were unreliable so I am instead going to use that SIM in my server for SMS only, and will be using an Andrews & Arnold (AAISP) SIP2SIM SIM for voice.

The other factor is that a decent Android phone is currently too expensive for my circumstances, and an AAISP SIP2SIM is relatively too expensive for voice calls. Outgoing calls using Groundwire have, for the most part, been OK over Wi-Fi and the O2 network, although I have had dropouts on my home Wi-Fi and incoming calls using Groundwire have been problematic at times with one-way audio.

I have unlocked my Huwai E220 modem for a few mBTC (milli-BitCoins) - it cost approximately 4 GBP; and I will be using my modem for sending/receiving SMS (proxying to my phone in some manner) although I am yet unsure whether I will be sending directly to the phone using AAISP's SMS thing. Calls will be dealt with on my Home Server using Asterisk, with the plan being to ring both my mobile (using SIP2SIM) and a home SIP phone that I am yet undecided which to purchase, although the D70/D71 does look like it will be the one I go with.

By cutting SIP connectivity from running on my mobile, I might be able to save a bit of battery life (although since I use Push instead of backgrounding, I don't know how much life will be saved). By using SIP2SIM instead of Groundwire for incoming calls, I will be paying for incoming calls when mobile. Since I am typically at home, however, when I receive calls, a "landline" SIP phone will likely get more use than my mobile for calls.

Currently my phone's Groundwire connects to Sipgate(.co.uk), Localphone, netSIP, and sip2sip. Although it uses push, when it is in the foreground I believe that is 4 different servers it actively connects to and keeps alive. I might be able to save some data, although I expect it will not be enough to outweigh the cost of incoming calls. With a home SIP phone, however, this might be somewhat mitigated but more data is needed before reaching a conclusion.

For the time being, I am going to be using Groundwire for my Asterisk setup. If it works on Groundwire, then it will likely work on a SIP phone and on AAISP SIP2SIM, so with less than 2 weeks to go before I planned on ditching my mobile number (that I might now port to Three) I need to get Asterisk set up, working, and tested. When it is working, I can look at the next stages.

I expect that switching to SIP2SIM on my mobile, Three 321 for SMS, and a D70/D71 for home calls, will work out cheaper than buying an Android phone that can do what I want. As an Android phone would seem to drain battery power if using the SIP client (like an iOS phone would if Groundwire were running actively), this does seem like it will be the best solution with fewer drawbacks. The reason I am giving my server the ability to send/receive SMS is because I realised that were I to just go with SIP2SIM I would lose the ability to receive SMS as neither Localphone nor Sipgate have incoming SMS for their numbers, and no incoming SMS would (as I have experienced) cause issues with companies that demand a mobile telephone number for "security" reasons.

Configuring Asterisk

I have done most of what is described in Installing Asterisk in Ubuntu already, so I will do the last step which is to run sudo asterisk -r and, if it works, exit. It works.

I am going to use Advanced Asterisk configuration in Ubuntu as a base for my Asterisk set-up. Given that I mainly use Localphone for outgoing calls, and that I have two iNums linked to my Localphone account (one of which Nominet have called several times regarding my Registrar account) and that unlike netSIP I do not keep forgetting my login details, I will be configuring Localphone first.

As I have numerous SIP providers, and I will want to use a provider because (a) I am calling an iNum or 0800 number, (b) I am calling someone and want my CLID to be a particular number, or, (c) it is the cheapest provider for that call, I will need a more granular setup than what that URL provides. In fact, since a quick glance suggests that encryption is not mentioned I will need quite a bit of modification of that tutorial, but I need to start somewhere.

For the settings, I will be referncing Localphone's Configure Asterisk page.

Backup sip.conf

sudo mv /etc/asterisk/sip.conf /etc/asterisk/sip.conf.orig

Create and Edit sip.conf

sudo nano /etc/asterisk/sip.conf

A note on the settings: all settings with spaces either side of the equals sign are settings I am sure of (either by testing or the SIP provider says to use them) whereas those without spaces are not tested/verified.

[general]
context = internal
register => [SIP ID]:[SIP Password]@localphone.com/[SIP ID]
allowguest=no
allowoverlap=no
bindport=5060
bindaddr=0.0.0.0
srvlookup=no
disallow=all
allow=ulaw
alwaysauthreject=yes
canreinvite=no
nat=yes
session-timers=refuse
externhost = home.thejc.me.uk
externrefresh = 15
localnet = 192.168.1.0/255.255.255.0

[localphone]
type = friend
insecure = very
nat = no
canreinvite = no
authuser = [SIP ID]
username = [SIP ID]
fromuser = [SIP ID]
fromdomain = localphone.com
secret = [SIP Password]

host = localphone.com
dtmfmode = rfc2833
context = localphone-in ;extensions.conf context for inbound calls
disallow = all
allow = ulaw
allow = alaw

Save and exit.

sudo asterisk -r
sip reload
WARNING[...]: chan_sip.c[...]: Unknown insecure mode 'very' on line 21
NOTICE[...]: chan_sip.c[...]: The 'username' field for sip peers has been deprecated in favour of the term 'defaultuser'
exit
sudo nano /etc/asterisk/sip.conf
[general]
context = internal
register => [SIP ID]:[SIP Password]@localphone.com/[SIP ID]
allowguest=no
allowoverlap=no
bindport=5060
bindaddr=0.0.0.0
srvlookup=no
disallow=all
allow=ulaw
alwaysauthreject=yes
canreinvite=no
nat=yes
session-timers=refuse
externhost = home.thejc.me.uk
externrefresh = 15
localnet = 192.168.1.0/255.255.255.0

[localphone]
type = friend
insecure = invite,port
nat = no
canreinvite = no
authuser = [SIP ID]
defaultuser = [SIP ID]
fromuser = [SIP ID]
fromdomain = localphone.com
secret = [SIP Password]

host = localphone.com
dtmfmode = rfc2833
context = localphone-in ;extensions.conf context for inbound calls
disallow = all
allow = ulaw
allow = alaw

Save and exit, and test again.

sudo asterisk -r
sip reload
sip show registry
Host                                    dnsmgr Username       Refresh State                Reg.Time
localphone.com:5060                     N      [SIP ID]            105 Registered           Tue, 25 Nov 2014 00:09:01
1 SIP registrations.
exit

Firewall

At present, home.thejc.me.uk is only IPv4. A grep of netstat -antpu | grep 5060 says that Asterisk is only listening on IP address(es) 0.0.0.0 which excludes IPv6.

As I use Groundwire behind my firewall, and my iptables rules are modified from my Raspberry Pi, sudo iptables -L -n -v | grep 5060 shows that 5060 and 5061 (tcp) are allowed through the firewall, and that 5060, 5061, and 10000-20000 (udp) are allowed through.

ip6tables also allows SIP traffic through. This should allow direct SIP connections to IPv6 devices on the LAN without Asterisk interfering, although some IPv6-only clients outside the network may have trouble connecting to me since home.thejc.me.uk is IPv4-only.

For the time being, this should suffice. The only issue now, however, is the question of whether Asterisk will intercept incoming calls that would normally reach Groundwire on my mobile phone. The issue, however, is that I have no way of testing this because Localphone incoming does have issues with "signal strength". Thus I am currently in the situation of not knowing what works and what doesn't.

Adding Extensions to sip.conf

I am in the UK. 0 is the trunk code, 00 is the international dialing code, 3 digit emergency numbers start with a 1 or 9, the Watford dialing code is 01923 (with 6 digits being a local number), an 8 digit local number will be treated as presumably being for the London 020 dialling code (with current 4th digits being 3, 7, 8, and 0200 and 0201 for national dialling only), a 7 digit local number will be treated as an unknown number (because Sipgate and Localphone both have 7 digit long User IDs), and 10000 and similar numbers used for Sipgate testing (e.g. 10004 for echo test) ruling out extensions with a length of 5.

Extensions with 4 digits, beginning with a 6, seems like the most sound way of doing things, although it may cause issues with local Watford numbers if slow dialling them. However, 01923 numbers are less likely to start with a 6 than a local extension, and 020 numbers (assuming the next reserved 4th digit to be used is '4') are not going to use 6xxx xxxx for a few years.

A lot of Watford local numbers are 2xx xxx, and a lot of London numbers are 7xxx xxxx and 8xxx xxxx and now 3xxx xxxx, so if I am also ruling out 0, 1, and 9, then 6 seems to be the best bet. So, 6xxx.

I did, an hour or so ago, come across an Asterisk setting that assumes no wait between dialling digits and a 2 second wait. As picking up and dialling is less likely than dialling all at once, and a phone that you can pick up and dial will likely have an option for a default line, whether or not to use such an Asterisk setting is something I will have to come back to.

sudo nano /etc/asterisk/sip.conf
[6001]
type = friend
host = dynamic
secret = [extension 6001 password]
context = internal

[6002]
type = friend
host = dynamic
secret = [extension 6002 password]
context = internal

Save and exit.

sudo asterisk -r
sip reload
sip show peers

The extensions are now visible. Now in Groundwire on my iPhone I'm going to create an account for extension 6001.

Title
John Cook
Username
6001
Password
[extension 6001 password]
Domain
home.thejc.me.uk
Display Name
6001

And now advanced settings:

Auth User Name
6001

After saving the settings, Asterisk says it received a SIP subscribe for peer without mailbox, and sip show peers shows that extension 6001 is online. After my phone has been asleep for a few minutes, the same command shows a different external IP address, which is presumably the push server.

So far, so good. The next question on my mind is: is that password being sent in plain text?

In sip.conf, add realm = home.thejc.me.uk under [general] and then under [6001] replace secret = [extension 6001 password] with md5secret = and the shell result of echo -n "6001:home.thejc.me.uk:[extension 6001 password]" | md5sum, i.e. md5secret = md5hashOfUser:Realm:Password.

A sip reload and sip show peer 6001 shows that md5secret is <Set> and secret is <Unset>, so that seems OK for now.

It is still unencrypted, however. Although I am currently sharing my password with a push server, I would rather my ISP (and other intermediaries) do not have the opportunity to see my password. All my SIP providers are pre-pay so I can't rack up a load of premium rate calls, but encryption is still a best practice. I think a StartSSL certificate for home.thejc.me.uk will be more widely compatible than a self-signed one, and I'm unsure whether SIP2SIM or Groundwire (or a D70/D71) support client certificates, so I think the best way to do things for now will be a server certificate and md5 hashed passwords.

TLS Server Certificate and Encryption

There are two things that need encryption - signalling and media. Encrypted SIP (SIPS) uses port 5061 by default, and media stream encryption uses SRTP with key exchange performed either with SDES or ZRTP. As SDES is more widely supported, I will not be going with ZRTP for the time being.

As we all know, a certificate signing request (CSR) should now use SHA2 hashing.

exit
sudo su
cd /etc/ssl/
mkdir asterisk
cd asterisk/
openssl req -nodes -newkey rsa:4096 -sha256 -keyout home_thejc_me_uk.key -out home_thejc_me_uk.csr
Country Name (2 letter code) [AU]
GB
State or Province Name (full name) [Some-State]
Hertfordshire
Locality Name (eg, city) []
Watford
Organization Name (eg, company) [Internet Widgits Pty Ltd]
home.thejc.me.uk
Organizational Unit Name (eg, section) []
[blank]
Common Name (e.g. server FQDN or YOUR name) []
home.thejc.me.uk
Email Address []
hostmaster@[example.com]
A challenge password []
[blank]
An optional company name []
[blank]

Now find the Web browser with my StartSSL client certificate installed, and visit StartSSL.com and verify ownership of thejc.me.uk and request a certificate using the content of the home_thejc_me_uk.csr file.

Do all that and get an error message that an SSL certificate for that domain already exists. It expires next April, and looking at the dates in my E-Mail series of articles it looks like that certificate, if it still exists, is on my old server. It will be simpler if I just use a new domain.

I am therefore going to request a certificate for sip.thejc.me.uk, which already exists, so I will modify my DNS entries removing the old sipthor ones (that I believe are still in use on some of my devices) and create a CNAME record for sip.thejc.me.uk to home.thejc.me.uk.

mv home_thejc_me_uk.csr sip_thejc_me_uk.csr
mv home_thejc_me_uk.key sip_thejc_me_uk.key
nano /etc/asterisk/sip.conf

Change home.thejc.me.uk to sip.thejc.me.uk and recreate the md5secret(s) using the new realm. Login to dns.he.net and validate thejc.me.uk so that it pulls changes in a few minutes. Now all I can do is wait.

While I'm waiting, let me talk about DNS. Some of those DNS records I have commented out include SRV records. Had I not done that, then an Asterisk configuration with srvlookup=yes would have had trouble connecting calls through my domain.

As it stands, I'm unsure whether a CNAME for SIP is a good idea or not, but my impatience means I simply commented out the SRV records for sip.thejc.me.uk. I will probably need to do some Googling to see how CNAME records work, but what I am hoping is that a SIP client will use the hostname sip.thejc.me.uk and the IP for home.thejc.me.uk.

Well, the certificate is ready so I'm saving that to /etc/ssl/asterisk/sip_thejc_me_uk.crt, and the DNS has updated, so I can now continue.

Configuring Asterisk for SIPS

cat sip_thejc_me_uk.key sip_thejc_me_uk.crt > sip_thejc_me_uk.pem
exit
sudo nano /etc/asterisk/sip.conf

Inside the [general] section, add:

tlsenable = yes
tlscertfile = /etc/ssl/asterisk/sip_thejc_me_uk.pem
tlscapath = /etc/ssl/certs
tlscipher = ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS

Save and exit.

sudo asterisk -r
sip reload
SSL certificate ok

Now, in Groundwire Advanced Settings:

Transport Protocol
tls (sips)

OK, my iPhone is getting a security warning and my Asterisk is giving FILE * open failed! errors, so it might be a permission issue (although my iPhone is saying the certificate for home.thejc.me.uk is not valid, so it might be the CNAME issue).

Ah, might be the intermediate certificate being missing.

sudo su
cat sip_thejc_me_uk.crt sub.class1.server.sha2.ca.pem > sip_thejc_me_uk.pem
nano /etc/asterisk/sip.conf

Add to the [general] section:

tlsprivatekey = /etc/ssl/asterisk/sip_thejc_me_uk.key
asterisk -r
sip reload

As I am still getting the error messages, I have no choice but to delegate sip.thejc.me.uk to Hurricane Electric and to set-up an additional dynamic DNS entry.

Update DNS on VPS

After commenting out all sip.home.thejc.me.uk related lines, add the following:

# SIP DNS Delegated
&SIP.thejc.me.uk::ns2.he.net:3600
&SIP.thejc.me.uk::ns3.he.net:3600
&SIP.thejc.me.uk::ns4.he.net:3600
&SIP.thejc.me.uk::ns5.he.net:3600

Update the SOA, and then validate thejc.me.uk again at dns.he.net so they check for an update. Again, wait for the update. The one issue I might have with Hurricane Electric is a minimum TTL. If, as I believe, it is 300 seconds that will mean that after my Home Server changes public IP then calls might be down for 5 minutes. On the plus side, however, by delegating to Hurricane Electric DNS resolution won't go down when I'm rebooting my VPS for kernel (and similar) updates.

Create a dynamic DNS key, and modify my dynamic dns updating script. As expected, I have just discovered the issue for updating dynamic DNS consistently and have (hopefully) fixed it:

#!/bin/sh
wget -q -4 -O /dev/null --no-http-keep-alive "https://[he.net tunnelname]:[DDNS key for home.thejc.me.uk]@ipv4.tunnebroker.net/nic/update?hostname=[he.net tunnel id]"
wget -q -4 -O /dev/null --no-http-keep-alive --no-check-certificate "https://sip.thejc.me.uk:[DDNS key for sip.thejc.me.uk]@dyn.dns.he.net/nic/update?hostname=sip.thejc.me.uk"

TODO: Scrap --no-check-certificate if Hurricane Electric start to use a certificate that has a valid trusted chain.

Finally, the reason for the actual error is that I didn't change the domain in Groundwire. Once I changed that to sip.thejc.me.uk and flushed the DNS cache entry on my VPS and Home Server, the error warning disappeared even though it should still display an error.

TODO: Find out how to get Asterisk to actually send the intermediate certificate. Does it need a later or patched version?

Anyway, I think encryption is working now.

Call prices

The one question I am obviously going to find is whether making calls using SIP2SIM and my SIP providers will work out cheaper than if I were to use Three's 321 tariff. At first I assumed the answer was no, because AAISP's SIP2SIM is 2.4 pence per minute including VAT, and Three's 321 is 3 pence per minute including VAT, but in the back of my mind is the 0.5 pence per minute rate including VAT that one of my SIP providers charged for some calls.

netSIP Prices (as of 2014-11-25)

UK Fixed
0.00686 GBP/min
UK Freephone
0.00294 GBP/min
UK Mobiles
0.01372 GBP/min
UK Mobiles Band 2
0.1372 GBP/min
UK National Rate
0.01568 GBP/min
UK Personal Numbers
0.22344 GBP/min
UK Special Numbers
0.08232 GBP/min

Sipgate.co.uk Prices (as of 2014-11-25)

UK Fixed
0.0119 GBP/min
UK Mobiles
0.099 GBP/min
UK 0845
0.03 GBP/min
UK 0870
0.0751 GBP/min
UK 0843/0872
0.25 GBP/min
UK 0844
0.05 GBP/min
UK 0871
0.1 GBP/min

Localphone Prices (as of 2014-11-25)

UK Landlines 01/02/03
0.005 GBP/min
UK Mobiles (All Networks)
0.018 GBP/min
UK Freephone
0.00 GBP/min

So, calls using SIP2SIM and Localphone to UK landlines will cost 2.4 + 0.5 = 2.9 pence per minute, and calls to major UK mobile networks using SIP2SIM and netSIP will cost 2.4 + 1.372 = 3.772 pence per minute.

However, I will probably continue to use Groundwire for outgoing calls when mobile, so assuming 87.2 Kb/s in each direction, that is 174.4 * 60 /8 = 1.308 MB/min = 3.1392 pence/min data, if using the G.711 codec and both sides are talking at the same time. That actually makes it more expensive than not using data.

Given that I will most likely just use my mobile for calls when I'm not at home, rather than Groundwire, I can estimate whether I will be saving money or not.

Typical Mobile Usage

I am going to assume that on average I use 250 Megabytes of mobile data per month. This is based on me buying the All Rounder bundle on O2 that comes with 500 Megabytes per month because 100 Megabytes just wasn't enough for me.

The All-Rounder costs 6.00 GBP/month.

Estimated Costs with SIP2SIM

Line Rental is 2.40 GBP/month, so if my calls and data combined cost less than 3.60 GBP/month I will be spending less.

3.60 / 0.024 = 150 minutes/Megabytes per month.

250 minutes/Megabytes * 0.024 = 6.00 GBP/month.

500 minutes/Megabytes * 0.024 = 12.00 GBP/month.

Will I Save Money?

At the moment, most of the calls I receive on my mobile are to my mobile number when I am at home. Virtually all of my outgoing calls when at home and not at home are done using Groundwire over Wi-Fi or 3G.

Based on this usage pattern, when I switch to SIP2SIM and have a SIP phone (D70/D71?) all of my incoming calls will instead be going over SIP trunks as I will no longer have a mobile number (except for SMS).

As for data usage, my iPhone says I have used 1.2 GB (assuming Gibibytes) since 12:42 on 2014-02-13. Assuming that is 285 days, then 1.2 / 2^30 * 10^9 / 285 * 31 * 1000 = approximately 121.6 Megabytes per month.

As for Groundwire usage, I have made/received 39 minutes of calls this month and 135 minutes of calls last month. Now, last month I made 1 hour 57 minutes of calls through Localphone (117 minutes) but those dates don't align on calendar month boundaries.

If I do in fact use 150 Megabytes per month and 150 minutes per month, then the cost of my mobile will be 2.40 GBP + 300 * 0.024 GBP = 9.60 GBP/month, or 3.60/month more, which equates to 43.20 GBP more per year (or 115.20 GBP per year total).

Now, however, is the Android question. The phone I have had my eye on is the LG G3 with 3 GiB RAM. That phone looks like it costs around 380 GBP. A Digium D71 costs around 180 GBP. A 200 GBP saving would cover my mobile expenditure for a year, or would cover the cost of switching from ADSL2+ to 152 Mb/s (down) 12 Mb/s (up) cable (with upstream being rate limited to 6 Mb/s after an hour and 4.3 Mb/s after two hours when being utilised).

The one thing I haven't accounted for are the text message savings. If sent from my mobile, they will be 2.4 + 2.0 pence, or 4.4 pence per 160 character message. Localphone charge 6.2 pence per UK text including VAT, and Sipgate.co.uk charge 5.9 pence per SMS. I will be saving 1.5 pence per SMS sent from my mobile, and 4.2 pence per SMS sent using an as yet undetermined method through my home server.

Although Three's 321 SIM would work out cheaper overall, I do not want to stop using SIP. By creating a WebRTC client on my Web site, I will be able to let people call me at home for free even if they do not have a SIP client. I will also be able to control when calls go through to my mobile, and instead of enabling voice mail on a mobile network (which is rather insecure) I can do everything on Asterisk if I so wish.

I have just added up my total Localphone/Sipgate/netSIP deposits and subtracted my current balances. In the last 2 years 2 months, I have spent a total 23.28 GBP on SIP calls. If I divide that by 26, I have spent approximately 0.90 GBP per month on SIP calls.

By adding the 6.00 GBP/month on mobile Internet (give or take a VAT rate change), and dividing my iPhone purchase by 27 months (~25.89 GBP/month), and my Groundwire purchase (6.99/26 GBP) and my Groundwire G729 in-app purchase (6.99/26 GBP) and my Groundwire ZRTP in-app purchase (17.49/26 GBP), the calculation is 0.90 + 6.00 + 25.89 + (6.99/26) + (6.99/26) + (17.49/26) = 34.00 GBP/month.

Of course, this excludes calls and texts made from my mobile phone credit, but it would be hard to determine how much that has cost because I have no way to determine it. It is probably worth noting, however, that until earlier this year most of my outgoing text messages were sent using iMessage, and I haven't made a chargeable call from my mobile credit for several months, so I can probably bump the cost to 35.00 GBP/month and it is probably around that figure.

Now, I can't remember the cost of the available price plans at the time I got my phone, but the purchase price of that phone is the same as an iPhone 6 128GB currently costs on the Apple store. The cheapest contract appears to be 423.99 GBP up front and 24.99 GBP per month, which after a 24 month contract equates to ((24.99*24)+423.99)/24 = 42.66 GBP per month, or after 27 months ((24.99*27)+423.99)/27 = 40.69 GBP per month.

One thing I haven't included are the costs of cases, charging cables, and earphones for my phone, but they would probably have been purchased anyway through wear. Had I not paid for my phone up front, it would probably have died by now rather than still functioning OK (albeit not having enough space to upgrade iOS, but that is a user issue).

Assuming I have saved 5.00 GBP per month over taking a contract, that is 135.00 not given to the mobile operators. By using SIP2SIM, it will be perfectly fine for me to make/receive mobile calls (as long as my broadband is working at home) over a 2G connection. I don't know what the latency will be like going over 2G then SIP to my Home Server and then SIP to a SIP provider and then over a link to the PSTN network, but it will hopefully be manageable.

Anyway, I will either spend less, the same, or more using SIP2SIM than O2, and the same or more than if I were to use 321, but until I have some usage data I will not know.

The other question I don't think I've touched on is fax. From the look of things I will have to ditch fax support if I ditch my landline for cable, at least until I do more research on fax over IP (FoIP).

Incoming Calls from Localphone

The following needs to be added to /etc/asterisk/extension.conf, and from first glance I don't want anything already in that file.

sudo mv /etc/asterisk/extensions.conf /etc/asterisk/extensions.conf.orig
sudo nano /etc/asterisk/extensions.conf
[localphone-in]
exten => [SIP ID],1,Set(thedid=${SIP_HEADER(To)})
exten => [SIP ID],2,Set(thedid=${CUT(thedid,@,1)})
exten => [SIP ID],3,Set(thedid=${CUT(thedid,:,2)})
exten => [SIP ID],4,GotoIf($["${thedid}" = "+[Localphone DID #1]"]?6:5)
exten => [SIP ID],5,GotoIf($["${thedid}" = "+[Localphone DID #2]"]?7)
exten => [SIP ID],6,Dial(SIP/6001&SIP/6002,60,tr) ; phone must be registered
exten => [SIP ID],7,Dial(SIP/6001&SIP/6002,60,tr) ; phone must be registered
exten => [SIP ID],8,Hangup

What this does, it get the DID (thedid) from the To SIP Header, and if it is [Localphone DID #1] then it goes to 6, else it goes to 5 and if it is [Localphone DID #2] then it goes to 7. I have modified what is posted as an answer at stackoverflow How to route an incoming call when I have multiple phone numbers with the same SIP provider?.

Fixing Annoying Encryption Issues

The one issue I have stumbled upon with encryption is when the phone is on the LAN, where there is a problem because Asterisk gives the LAN IP causing a certificate name mismatch.

To fix the dialog on the phone issue (which also prevents hanging up and presumably other actions), call the phone, answer it, hang up on the callee end, and then trust the static Home Server IP address. It is not an ideal solution, but I can't find a way to force Asterisk to use sip.thejc.me.uk for everything on the LAN.

Incoming Localphone Calls Work

At this stage, incoming calls to my Localphone DID numbers now ring on my iPhone. There is currently an error in Asterisk, however, but that is presumably because extension 6002 is not registered.

Outgoing calls through Localphone are not yet configured, nor are dialling internal connections. I am going to work on internal connections next because that could possibly be why Groundwire is unable to hold or transfer calls.

Internal Extensions

sudo nano /etc/asterisk/extensions.conf

Add the following to the file.

[internal]
; All internal extensions are 4 digits and start with 6.
exten => _6XXX,1,Dial(SIP/${EXTEN})
sudo asterisk -r
dialplan reload

The extensions can now dial each other. Hold and transfer are still not working in Groundwire, however, so this will have to be something I need to look at later.

Localphone Outgoing Calls

Now for the localphone-out context, so that calls that are cheapest to make using Localphone use Localphone.

Based on the section above, these calls are UK landlines and UK mobiles (major networks, but that plan will be too complex).

I am actually going to put all external dialling in the same context, no matter what SIP provider is cheaper, so that I just need to change @localphone to @sipgate (for example) if Sipgate becomes cheaper for one of these numbers.

sudo nano /etc/asterisk/extensions.conf
[external-permitted]
; All extensions/users that are permitted to make external calls
;  belong to this context.
; Import the internal context so internal extensions work.
include => internal

; Replace 00 with +
exten => _00.,1,Noop(Replacing 00 with +)
exten => _00.,n,Goto(+${EXTEN:2},1)

; Replace 0 with +44
exten => _0.,1,Noop(Replacing 0 with +44)
exten => _0.,n,Goto(+44{EXTEN:1},1)

; All outgoing calls use this context.
; When the call rates for SIP providers change, the @trunk-context can be modified.

; Assume all 6 digit length numbers are Watford area code, 0 is trunk, 1 is national.
; TODO: If at a later date Watford (01923) requires dialling of the area code
;  because there are not enough available phone numbers, so that 01923 1XX XXX
;  and 01923 0XX XXX can start to be allocated, comment out _ZXXXXX lines.
exten => _ZXXXXX,1,Noop(Adding Watford Area Code)
exten => _ZXXXXX,n,Goto(+441923${EXTEN},1)
; Assume all 8 digit length numbers are London area code, 0 is trunk, 1 is national.
exten => _ZXXXXXXX,1,Noop(Adding London Area Code)
exten => _ZXXXXXXX,n,Goto(+4420${EXTEN},1)

; UK Landline Calls are country code 44, and begin with 1, 2, or 3 (01/02/03).
; Because some short codes start with 1 (e.g. 118118)
;  I want there to be at least 6 digits (X) after the 1.
; 441XXXXXX = +44 1xxx xxx, so won't conflict with "local" Watford/London numbers.

; According to Wikipedia, Jersey numbers start with 01534.
; Localphone charge 0.4p per minute.
exten => _+441534.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
; Also according to Wikipedia, Guernsey numbers start with 01481.
; Localphone charge 0.4p per minute.
exten => _+441481.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
; Also according to Wikipedia, Isle of Man numbers start with 01624.
; Localphone charge 0.3p per minute.
exten => _+441624.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

exten => _+441XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+442XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+443XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; UK Personal numbers are premium rate, and are thus prohibited.
; Because some mobiles have voicemail on 701, require at least 2 digits after +44 70.
exten => _+4470XX.,1,Playback(beeperr)
same => n,Playback(vm-goodbye)
same => n,Hangup()
; Likewise for 09 numbers and 901 voicemail.
exten => _+449XXX.,1,Playback(beeperr)
same => n,Playback(vm-goodbye)
same => n,Hangup()

; According to Wikipedia, 07624 is for Isle of Man mobiles,
;  and other 076 numbers are for pagers.
; Localphone charge 1.5p per minute to IoM mobiles, 125p/min to pagers.
exten => _+447624.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

exten => _+4476.,1,Playback(beeperr)
same => n,Playback(vm-goodbye)
same => n,Hangup()

; Also according to Wikipedia, Wi-Fi numbers start with 07911 2 or 07911 8.
exten => _+447911[28].,1,Playback(beeperr)
same => n,Playback(vm-goodbye)
same => n,Hangup()

; TODO: Filter mobile numbers that are more expensive.

; Most other UK major mobiles start with 074, 075, 077, 078, and 079.
exten => _+447[45789]XX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; UK Freephone numbers are country code 44, and begin 80 or 500 (080/0500).
exten => _+4480X.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+44500X.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; Internataion numbers (inum) are free and available through ENUM, and are +883 5100.
exten => _+8835100X.,1,Set(enumresult=${ENUMLOOKUP(${EXTEN:1})}
same => n,Dial(SIP/${enumresult},30,tr)
; International disaster relief operations (United Nations) have international
;  code +888, which should be resolvable using ENUM.
exten => _+888X.,1,Set(enumresult=${ENUMLOOKUP(${EXTEN:1})}
exten => _+888X.,n,Dial(SIP/${enumresult},30,tr)


; National Grid is the same throughout the country for gas emergencies
exten => gasemergency,1,Goto(+44800111999,1)

; Electricity Emergency contact numbers depend on the distribution zone.
; http://utilitiessavings.co.uk/resources/emergencies/
; TODO: Create a menu, so the only number I need in my phones is that for
;  UK Power Networks (East England): +448007838838
;  but it gives the option to call another supplier if not at home.

; TODO: Create an operator menu at extension 100.
;  Create voice prompts for different types of numbers.

;  For example:
;  Please hold for the internal automated operator service.
;  To return to the main menu at any time, press star.
;  To repeat a menu list from the beginning, press hash.
;  Main Menu.
;  For any type of emergency, please press 1.
;   Emergency Menu.
;   For all life threatening emergencies, please hang up and dial 112.
;   To report a gas leak, please press 1.
;   To report an electricity emergency or fault, please press 2.
;   For non-life-threatening medical assistance, please press 3.
;    NHS 111 is not available from this system. Entering medical dialling menu...
;     To connect to GP, please press 1.
;     To conect to Dentist, please press 2.
;     To connect to Community Mental Health Team, please press 3.
;     To connect to Out of Hours GP, please press 4.
;     To connect to Out of Hours Mental Health Team, please press 5.
;     For EU harmonised services of social value, please press 6.
;      The following harmonised numbers have been allocated by Ofcom:
;      For the Hotline for missing children, please hang up and dial 116000 from a normal landline or mobile phone. You will be connected to the UK organisation Missing People.
;      No Helpline for victims of crime has currently been allocated by Ofcom.
;      For the child helpline, please press 3 or hang up and dial 116111. You will be connected to the UK organisation NSPCC.
;      No Non-emergency medical on-call service has currently been allocated by Ofcom.
;      For the emotional support helpline, please press 5 or hang up and dial 116123. You will be connected to UK organisation The Samaritans.
;   To report a burst water main or sewage emergency, please press 4.
;   To contact <name> to report something to the landlord, please press 5.
;   For an emergency server shutdown, please press 6.
;   To contact Hertfordshire County Council Highway Fault Reporting, please press 7.
;   To report a noise nuisance to Watford Borough Council, please press 8.
;   To return to the main menu, please press star.
;  To ask Google something using Google Speech API, please press 4.
;  To be connected to an internal extension, please press 6.
;   Please enter the 4 digit extension number now. Press hash if you make a mistake.
;  To contact John Cook, please press 0.
;   Contact John Cook Menu.
;   You now have several options that will offer more options.
;   To contact John Cook at a phone that is wired or wireless, press 1.
;    100% Internet Protocol Call John Cook Menu.
;    For wired ethernet, please press 1.
;    For Wi-Fi or 3G, please press 2.
;     Please hold. In order to avoid one-way audio, I will connect you as soon as
;   To inform John Cook that you have called, press 2.
;    Please say your name after the beep. To re-record, press hash. Beep.
;   To request a call back from John Cook to this extension, press 3.
;    Call back this extension menu.
;    To send the request over XMPP, the preferred method, please press 1.
;    To send the request over SIP SIMPLE, please press 2.
;    To send the request over SMS, the last resort method, please press 3.
;   To request a call back from John Cook to another number, press 4.
;    Call back another number menu.
;    To send the request over XMPP, the preferred method, please press 1.
;    To send the request over SIP SIMPLE, please press 2.
;    To send the request over SMS, the last resort method, please press 3.
;   To contact John Cook over the mobile network, the least preferred method, please press 5.
;   To hear this menu again, please press hash.
;   To return to the main menu, please press star.
;  To hear this menu again, please press star or hash.

Now, Sipgate also have dialling for emergency services. Although I haven't yet created the Sipgate peer, I can add the following to extensions.conf for future support:

[external-permitted-fixed]
; Sipgate permit dialling of emergency service numbers, but
;  the location given to the emergency call handler is a fixed address.
; Because of this, only extensions in this context are permitted to dial the
;  emergency services, and only extensions that are fixed (i.e. akin to a landline)
;  are allowed to be in this context.

exten => 999,1,Goto(emergencyservices,1)
exten => 9999,1,Goto(emergencyservices,1)
exten => 911,1,Goto(emergencyservices,1)
exten => 9911,1,Goto(emergencyservices,1)
exten => 112,1,Goto(emergencyservices,1)
exten => 9112,1,Goto(emergencyservices,1)

exten => emergencyservices,1,Verbose(1,Call initiated to Emergency Services!)
same => n,Dial(SIP/999@sipgate,30,tr)

; Likewise, the NHS 111 Emergency Number and the Police 101 Emergency Numbers
; These, however, may not be available from a SIP provider, so alternative
;  numbers are going to be used here.

; From http://www.police.uk/contact/alternative-non-emergency-numbers/
; Police force: Hertfordshire Constabulary
; Telephone number: 01707 354000
; From abroad: +44 1707 354000
exten => 101,1,Verbose(1,Call initiated to Hertfordshire Constabulary!)
same => n,Goto(+441707354000,1)

; TODO: Find alternative number for NHS 111 West Hertfordshire

; There are harmonised numbers in the EU for some services of social value.
; http://en.wikipedia.org/wiki/Harmonised_service_of_social_value

; 116000 is the Hotline for missing children.
; 116000 has been awarded to http://en.wikipedia.org/wiki/Missing_People by Ofcom
; TODO: Find alternative number.

; 116111 is for child helplines (for children to call)
; 116111 has been awarded to the NSPCC by Ofcom
exten => 116111,1,Goto(+448001111,1)

; 116123 is for emotional support helplines
; 116123 has been awarded to The Samaritans by Ofcom
exten => 116123,1,Goto(+448457909090,1)

include => external-permitted

Configuration Overview

At this point, incoming and outgoing calls using Localphone and ENUM SIP (for +883 5100 and +888) are working, and prohibited numbers currently give a "ding, goodbye" and hangup, to the caller, at least until I record a more meaningful message.

Calling UK landlines, mobiles, and freephone numbers now work, as well as inum, UN disaster relief, and harmonised services of social value numbers that I have an alternative number for which falls into one of the previous categories (i.e. 116111 redirecting to a freephone number that then should dial out using Localphone).

One of the issues I ran into whilst creating my dial plan was that of the plus symbol and priorities. I erroneously though that priorities are numeric based on the context, not the "extension", so +441 had a priority of 1 and +442 had a priority of 2, which obviously (to me now, at least) did not work.

I also thought that the plus symbol was causing the issue, rather than priorities being the cause. So far testing suggests that the dial plan works as it is supposed to.

As this article has reached a rather long length, I am going to finish by displaying my current sip.conf and extensions.conf files, with personal stuff redadcted.

nano /etc/asterisk/sip.conf
[general]
context=internal
register => [SIP ID]:[SIP Password]@localphone.com/[SIP ID]
allowguest=no
allowoverlap=no
bindport=5060
srvlookup=no
disallow=all
allow=ulaw
alwaysauthreject=yes
canreinvite=yes
nat=yes
session-timers=refuse
externhost=sip.thejc.me.uk
externrefresh=15
realm=sip.thejc.me.uk
tlsenable = yes
tlscertfile = /etc/ssl/asterisk/sip_thejc_me_uk.pem
tlsprivatekey = /etc/ssl/asterisk/sip_thejc_me_uk.key
tlscapath = /etc/ssl/certs
tlscipher = ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3D$
domain=sip.thejc.me.uk


[localphone]
type = friend
insecure = invite,port
nat = no
canreinvite = no
authuser = [SIP ID]
defaultuser = [SIP ID]
fromuser = [SIP ID]
fromdomain = localphone.com
secret = [SIP Password]

host = localphone.com
dtmfmode = rfc2833
context = localphone-in ;extensions.conf context for inbound calls
disallow = all
allow = g722
allow = g729
allow = ulaw
allow = alaw

[6001] ; John Cook (iPhone Groundwire)
type = friend
host = dynamic
md5secret = [redacted]
context = external-permitted
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=1
pickupgroup=1-8

[6002] ; John Cook (iPad Groundwire)
type = friend
host = dynamic
md5secret = [redacted]
context = external-permitted
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=1
pickupgroup=1-8

[6003] ; D71 Line 1
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=1
linenumber=1

[6004] ; D71 Line 2
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=2
linenumber=2

[6005] ; D71 Line 3
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=3
linenumber=3

[6006] ; D71 Line 4
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=4
linenumber=4

[6007] ; D71 Line 5
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=5
linenumber=5

[6008] ; D71 Line 6
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=6
linenumber=6

[6009] ; David Lane (Android)
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=9
pickupgroup=9

[6010] ; John Cook (SIP2SIM)
type = friend
host = dynamic
md5secret = [redacted]
context = internal
transport = tls
port = 5061
disallow = all
allow = g722
allow = ulaw
allow = alaw
allow = g729
allow = gsm
allow = ilbc
callgroup=10
pickupgroup=1-9,10

This is not the final version of sip.conf, and there are a lot of extensions that are placeholders for future use. Call groups, pickup groups, line numbers, and everything with an "internal" context, are some of the things that are not set in stone and won't be finalised until a later date.

nano /etc/asterisk/extensions.conf
[localphone-in]

exten => 1663931,1,Set(thedid=${SIP_HEADER(To)})
same => 2,Set(thedid=${CUT(thedid,@,1)})
same => 3,Set(thedid=${CUT(thedid,:,2)})
same => 4,GotoIf($["${thedid}" = "+8835100[redacted]"]?6:5)
same => 5,GotoIf($["${thedid}" = "+8835100[redacted]"]?7)
same => 6,Dial(SIP/6001&SIP/6002&SIP/6004&SIP/6010,60,tr) ; phone must be registered
same => 7,Dial(SIP/6001&SIP/6002&SIP/6003&SIP/6010,60,tr) ; phone must be registered
same => 8,Hangup

[internal]
; All internal extensions are 4 digits and start with 6.
exten => _6XXX,1,Dial(SIP/${EXTEN})

[external-permitted]
; All extensions/users that are permitted to make external calls
;  belong to this context.
; Import the internal context so internal extensions work.
include => internal

; Replace 00 with +
exten => _00.,1,Noop(Replacing 00 with +)
exten => _00.,n,Goto(+${EXTEN:2},1)

; Replace 0 with +44
exten => _0.,1,Noop(Replacing 0 with +44)
exten => _0.,n,Goto(+44{EXTEN:1},1)

; All outgoing calls use this context.
; When the call rates for SIP providers change, the @trunk-context can be modified.

; Assume all 6 digit length numbers are Watford area code, 0 is trunk, 1 is national.
; TODO: If at a later date Watford (01923) requires dialling of the area code
;  because there are not enough available phone numbers, so that 01923 1XX XXX
;  and 01923 0XX XXX can start to be allocated, comment out _ZXXXXX lines.
exten => _ZXXXXX,1,Noop(Adding Watford Area Code)
exten => _ZXXXXX,n,Goto(+441923${EXTEN},1)
; Assume all 8 digit length numbers are London area code, 0 is trunk, 1 is national.
exten => _ZXXXXXXX,1,Noop(Adding London Area Code)
exten => _ZXXXXXXX,n,Goto(+4420${EXTEN},1)

; UK Landline Calls are country code 44, and begin with 1, 2, or 3 (01/02/03).
; Because some short codes start with 1 (e.g. 118118)
;  I want there to be at least 6 digits (X) after the 1.
; 441XXXXXX = +44 1xxx xxx, so won't conflict with "local" Watford/London numbers.

; According to Wikipedia, Jersey numbers start with 01534.
; Localphone charge 0.4p per minute.
exten => _+441534.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
; Also according to Wikipedia, Guernsey numbers start with 01481.
; Localphone charge 0.4p per minute.
exten => _+441481.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
; Also according to Wikipedia, Isle of Man numbers start with 01624.
; Localphone charge 0.3p per minute.
exten => _+441624.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

exten => _+441XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+442XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+443XXXXXX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; UK Personal numbers are premium rate, and are thus prohibited.
; Because some mobiles have voicemail on 701, require at least 2 digits after +44 70.
exten => _+4470XX.,1,Goto(barred-expensive)
; Likewise for 09 numbers and 901 voicemail.
exten => _+449XXX.,1,Goto(barred-expensive)

; According to Wikipedia, 07624/07425/07924 is for Isle of Man mobiles,
;  and other 076 numbers are for pagers.
; Localphone charge 1.5p per minute to IoM mobiles, 125p/min to pagers.
exten => _+447[69]24.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+447425.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

exten => _+4476.,1,Goto(barred-expensive)

; Guernsy Mobiles start 07781/07839/07911
; 07881 cost 11.9p/min from Localphone.
; 07839 cost 8.2p/min from Localphone.
; 07911 cost 8.2p/min from Localphone.
exten => _+447881.,1,Goto(barred-expensive-mobile)
exten => _+447839.,1,Goto(barred-expensive-mobile)
exten => _+447911.,1,Goto(barred-expensive-mobile)

; Jersey Mobiles start 07590/07797/07937/07700/07829
; Localphone charge 8.2p/min to Jersey Mobiles
exten => _+447590.,1,Goto(barred-expensive-mobile)
exten => _+447797.,1,Goto(barred-expensive-mobile)
exten => _+447937.,1,Goto(barred-expensive-mobile)
exten => _+447700.,1,Goto(barred-expensive-mobile)
exten => _+447829.,1,Goto(barred-expensive-mobile)

; Also according to Wikipedia, Wi-Fi numbers start with 07911 2 or 07911 8.
exten => _+447911[28].,1,Goto(barred-expensive)

; TODO: Filter other mobile numbers that are more expensive.

; Most other UK major mobiles start with 074, 075, 077, 078, and 079.
exten => _+447[45789]XX.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; UK Freephone numbers are country code 44, and begin 80 or 500 (080/0500).
exten => _+4480X.,1,Dial(SIP/${EXTEN}@localphone,30,tr)
exten => _+44500X.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; International freephone numbers have international code +800
exten => _+800X.,1,Dial(SIP/${EXTEN}@localphone,30,tr)

; Internataion numbers (inum) are free and available through ENUM, and are +883 5100.
exten => _+8835100X.,1,Set(enumresult=${ENUMLOOKUP(${EXTEN:1})}
same => n,Dial(SIP/${enumresult},30,tr)
; International disaster relief operations (United Nations) have international
;  code +888, which should be resolvable using ENUM.
exten => _+888X.,1,Set(enumresult=${ENUMLOOKUP(${EXTEN:1})}
exten => _+888X.,n,Dial(SIP/${enumresult},30,tr)

; National Grid is the same throughout the country for gas emergencies
exten => gasemergency,1,Goto(+44800111999,1)

; Electricity Emergency contact numbers depend on the distribution zone.
; http://utilitiessavings.co.uk/resources/emergencies/
; TODO: Create a menu, so the only number I need in my phones is that for
;  UK Power Networks (East England): +448007838838
;  but it gives the option to call another supplier if not at home.

; TODO: Create an operator menu at extension 100.
;  Create voice prompts for different types of numbers.
;  For example:
;  Please hold for the internal automated operator service.
;  To return to the main menu at any time, press star.
;  To repeat a menu list from the beginning, press hash.
;  Main Menu.
;  For any type of emergency, please press 1.
;   Emergency Menu.
;   For all life threatening emergencies, please hang up and dial 112.
;   To report a gas leak, please press 1.
;   To report an electricity emergency or fault, please press 2.
;   For non-life-threatening medical assistance, please press 3.
;    NHS 111 is not available from this system. Entering medical dialling menu...
;     To connect to GP, please press 1.
;     To conect to Dentist, please press 2.
;     To connect to Community Mental Health Team, please press 3.
;     To connect to Out of Hours GP, please press 4.
;     To connect to Out of Hours Mental Health Team, please press 5.
;     For EU harmonised services of social value, please press 6.
;      The following harmonised numbers have been allocated by Ofcom:
;      For the Hotline for missing children, please hang up and dial 116000 from a normal landline or mobile phone. You will be connected to the UK organisation Missing People.
;      No Helpline for victims of crime has currently been allocated by Ofcom.
;      For the child helpline, please press 3 or hang up and dial 116111. You will be connected to the UK organisation NSPCC.
;      No Non-emergency medical on-call service has currently been allocated by Ofcom.
;      For the emotional support helpline, please press 5 or hang up and dial 116123. You will be connected to UK organisation The Samaritans.
;   To report a burst water main or sewage emergency, please press 4.
;   To contact <name> to report something to the landlord, please press 5.
;   For an emergency server shutdown, please press 6.
;   To contact Hertfordshire County Council Highway Fault Reporting, please press 7.
;   To report a noise nuisance to Watford Borough Council, please press 8.
;   To return to the main menu, please press star.
;  To ask Google something using Google Speech API, please press 4.
;  To be connected to an internal extension, please press 6.
;   Please enter the 4 digit extension number now. Press hash if you make a mistake.
;  To contact John Cook, please press 0.
;   Contact John Cook Menu.
;   You now have several options that will offer more options.
;   To contact John Cook at a phone that is wired or wireless, press 1.
;    100% Internet Protocol Call John Cook Menu.
;    For wired ethernet, please press 1.
;    For Wi-Fi or 3G, please press 2.
;     Please hold. In order to avoid one-way audio, I will connect you as soon as
;   To inform John Cook that you have called, press 2.
;    Please say your name after the beep. To re-record, press hash. Beep.
;   To request a call back from John Cook to this extension, press 3.
;    Call back this extension menu.
;    To send the request over XMPP, the preferred method, please press 1.
;    To send the request over SIP SIMPLE, please press 2.
;    To send the request over SMS, the last resort method, please press 3.
;   To request a call back from John Cook to another number, press 4.
;    Call back another number menu.
;    To send the request over XMPP, the preferred method, please press 1.
;    To send the request over SIP SIMPLE, please press 2.
;    To send the request over SMS, the last resort method, please press 3.
;   To contact John Cook over the mobile network, the least preferred method, please press 5.
;   To hear this menu again, please press hash.
;   To return to the main menu, please press star.
;  To hear this menu again, please press star or hash.

[external-permitted-fixed]
; Sipgate permit dialling of emergency service numbers, but
;  the location given to the emergency call handler is a fixed address.
; Because of this, only extensions in this context are permitted to dial the
;  emergency services, and only extensions that are fixed (i.e. akin to a landline)
;  are allowed to be in this context.

exten => 999,1,Goto(emergencyservices,1)
exten => 9999,1,Goto(emergencyservices,1)
exten => 911,1,Goto(emergencyservices,1)
exten => 9911,1,Goto(emergencyservices,1)
exten => 112,1,Goto(emergencyservices,1)
exten => 9112,1,Goto(emergencyservices,1)

exten => emergencyservices,1,Verbose(1,Call initiated to Emergency Services!)
same => n,Dial(SIP/999@sipgate,30,tr)

; Likewise, the NHS 111 Emergency Number and the Police 101 Emergency Numbers
; These, however, may not be available from a SIP provider, so alternative
;  numbers are going to be used here.

; From http://www.police.uk/contact/alternative-non-emergency-numbers/
; Police force: Hertfordshire Constabulary
; Telephone number: 01707 354000
; From abroad: +44 1707 354000
exten => 101,1,Verbose(1,Call initiated to Hertfordshire Constabulary!)
same => n,Goto(+441707354000,1)

; TODO: Find alternative number for NHS 111 West Hertfordshire

; There are harmonised numbers in the EU for some services of social value.
; http://en.wikipedia.org/wiki/Harmonised_service_of_social_value

; 116000 is the Hotline for missing children.
; 116000 has been awarded to http://en.wikipedia.org/wiki/Missing_People by Ofcom
; TODO: Find alternative number.

; 116111 is for child helplines (for children to call)
; 116111 has been awarded to the NSPCC by Ofcom
exten => 116111,1,Goto(+448001111,1)

; 116123 is for emotional support helplines
; 116123 has been awarded to The Samaritans by Ofcom
exten => 116123,1,Goto(+448457909090,1)

include => external-permitted

This is definitely not the final version of extensions.conf. Even if everything were set up how I want it to be, with everything working, there will always be changes to dialling codes, call rates, SIP providers, and everything else telephony related.

Speaking of changes, the next article is going to go through the process of setting up Kamailio to proxy SIP signalling traffic. This is because I am already seeing sipvicious attacks. I still cannot get Kamailio and Asterisk to work together properly, so I am going to skip it for now.

RTP Port Ranges and Port Forwarding

One thing that is worth noting is that it is not a good idea to use the same RTP port range on all devices that are being forwarded through the firewall. I am not sure if it is the cause of some one-way audio, but it might be.

The first port in a range in Asterisk should be even, and the last should be odd. Therefore, for Asterisk, I am going to use port range 15,000 to 19,999.

sudo nano /etc/asterisk/rtp.conf
rtpstart = 15000
rtpend=19999
sudo asterisk -rvvvvvv
module reload

Now, for the "John Cook" Groundwire account on my iPhone, I'm going to use ports 10100 to 10199, and on my iPad 10200 to 10299.

Assuming 4 ports are used per call, that gives each extension enough ports for 25 calls, and Asterisk enough ports for (19999-15000+1)/4 = 1,250 calls.

As I'm also basing the port range on the extension number (6001 = 10100) then extension 6010 will have a port range of 11000-11999, and 6050 will have port range 15000-15999, so extension 6049 will be 14900-14999.

Only having enough ports for 49 extensions may be a limitation in the future, but if I ever need more I can halve the range, so 6001 gets 10100-10149 and 6050 gets 10150-10199. I could even drop it to 10010-10019, but more is better for now.

Always Backup Before Making Big Changes

My home server does almost everything. If it goes down, so does my Internet. Unlike my VPS, if my home server goes down it affects me pretty quickly. Upon trying to get my server to relay SMS messages to me over SIP SIMPLE or XMPP, I hit the problem of everything being impossible to install because of incompatibilities with installed versions.

I know, this is as good a time as any to upgrade from Debian Wheezy to Jessie, I thought. Big mistake, but it could have been a lot worse. First thing I did wrong was run the upgrade over SSH. Second thing I did wrong was use top in a console to try and work out when it was going to hang for user input after the network connection went down.

The third mistake was rebooting and then running the upgrade again. By the time I had finished, I had a system that couldn't finish booting. I made things worse when I tried to copy the files across because glibc was missing which meant I could only use cp, and you can't copy stat libs using cp.

At that point I had access to all my files, but I couldn't chroot because chroot needed a different version of glibc, which I couldn't install because apt-get and aptitude also needed a different version of glibc that wasn't installed. As did dpkg. And rsync.

Only two days ago I tweeted about me thinking I had over-engineered my backup routine script because it not only asked for the device (e.g. /dev/sdg1) of the backup LUKS partition, but it also verified the LUKS UUID before continuing. I missed off the partition number and would have overwrote the entire drive, but my backup script not only prevented that from happening but made me realise that when I make a mistake I try to make it very difficult to repeat it.

So, my backup routine ran successfully two days ago. It may have taken me about four hours today from screwing up my server to restoring it, but it could have taken a lot longer than that if I didn't have a recent backup and couldn't fix it without doing a complete fresh install.

It also would have taken a lot longer to have fixed a messed up backup because I use encrypted backups, so I may not have gotten around to wiping the disk, repartitioning, and backing up again. The backup alone would have taken 4+ hours based on how long it took the first time.

I have thanked myself for writing that backup script twice this week. I have also realised that the hot-swappable "rack" (that fits in a standard 5.25 inch bay) I bought has paid for itself. Without either of those, I would be looking for the plug to my eSATA caddy, looking for the right cable and port, using dd or something, and pretty much doing things as inefficiently as possible.

Instead, my backup routine is as simple as unlocking the rack mount, sliding in a disk, typing sudo ~/Scripts/backup-WDRED-to-HomeServerBackup.sh, waiting for my SSD to be backed up to my WD RED, and then typing in the partition number (that is double-checked is correct before continuing) and waiting for all the partitions on my WD RED (including the backed up SSD ones) to rsync to my backup drive.

It then reminds me to check for any errors with umount or luksClose, and then I just run ~/Scripts/eject-drive.sh and enter the same as I entered for the backup minus the partition number (e.g. sdg). At that point, I just unlock the rack mount, open the bay (which removes the power from the disk) and wait 10 seconds before removing it and putting it away and locking the bay again.

By being able to backup my entire server (excluding my media drives) in 10 minutes, I can run a backup before I make any big changes. The fact is that after the restoration I dreaded the thought that I'd just wiped my new SSL key and certificate, but this article has actually taken 4 days to write so far meaning that I not only backed up the key and cert, but I'd run two backup routines since creating them.

As with the last time I screwed something up (that one resulted in me losing a year's worth of documents), I have adjusted things. Only a month ago I started my backup routine and a week or so later I added BitTorrent Sync on my home server to backup the content of the Documents and Downloads folders on my laptop.

What have I learnt this time?

  1. If I am going to upgrade and overwrite configuration files, back them up first.
  2. If I restore a backup and haven't got a duplicate of my current configuration files, back them up first.
  3. By not restoring /home I didn't lose any data stored in /home (including the SMS API I've wrote) but just because www is stored under there doesn't mean all Web data is safe from me.
  4. I need to backup my databases regularly, because they are easy to wipe.

So to summarise: backups are important, never backup during making big changes unless you have more than one backup copy, and try to minimise losses to data by refining backup routines when there is an obvious flaw or two. I may have lost all the SMS's I have received on my new SIM, but they were only for testing and nothing important.

A shorter summary: never test on a production system with your fingers crossed hoping everything will work. If you can't afford a test system (or would need to buy an identical machine just to test updates), be prepared for everything to go wrong.

Make sure you know that you have a DVD to hand that not only has a Linux OS on it that uses similar commands you use regularly (e.g. my Ubuntu DVD) but that it is a Live DVD/CD and can cope with whatever type of recovery you need to do without the need for an Internet connection (or at least supports your NIC's).

That DVD for me is a Ubuntu 10.04 Live DVD. With cryptsetup and kpartx included on it, it can manage my screw ups when nothing else can. Oh, and it also can throw grub-legacy on the MBR and at least allow me to boot my server without giving up after insmod'ing 30 different modules using their full paths (without tab completion) before reaching one that is needed that I can't find.

Getting back into my server from that grub shell, and then reinstalling grub-pc and getting everything back to how it was a couple of days ago... I'm just glad that DVD wasn't too scratched.

What Next?

Well, I have given up on the idea of getting Kamailio to work with ASterisk. Actually, because I have restored from a backup I am basically back where I was when I left this article, albeit with a sip.conf and extensions.conf that are not exactly compatible with this version of Asterisk.

So, the next article will be on installing a later version of Asterisk, probably Asterisk 11, depending on whether the Youtube video I'm currently watching (Asterisk 123: Installation and Dialplan Intro) convinces me to get a later version.

The reason for Asterisk 11? SIP MESSAGE support. I have now configured Groundwire with two profiles for my server, with one called "SMS" that allows me to send SMS messages to a contact using Groundwire's SMS API support (that took some debugging to work), and one that (until I lost my work) allows me to send SIP SIMPLE messages between extensions 6001 and 6002.

One issue I have with Asterisk 11 SIP SIMPLE messaging is that it gives an error message if it is addressed to a sips: URI rather than a sip: URI. Given I have ordered a Digium D70 phone now (those sellers calling it a D71 are mistaken), and my SIP2SIM SIM has also been ordered, and there are just 4/5 days until I run out of credit on my O2 PAYG phone, I am reaching the point where I need

Another thing that is missing now is my XMPP server.