Saturday, February 27, 2016

Tax Season

Canada Tax Planning for the Middle Class

Working class people need not do tax planning - they don’t have anything and don’t pay anything.  Rich people hire accountants to keep track of it all.  The rest of us, need to do tax planning.

As Joe Walsh put it:

I have a mansion, forget the price
I've never been there, they tell me it's nice
I live in hotels, I stare at the walls
I have accountants who pay for it all. 

The general solution to tax problems is to use corporate law to your advantage.  Corporate law changes very slowly and is fairly uniform across the world.  Large companies do not like it when governments touch corporate law, so politicians mostly keep their hands off it, since it can be political suicide.  Don't rely on Trusts.  Trust law is very hazy and therefore dangerous and changed for the worse recently, causing many tax problems. The worst thing is personal tax law - it changes with every budget, so it is hopeless to do long term planning for personal taxes.

I started to read up on tax and corporate law during the dotcom boom, when I suddenly got hit with a $25,000 extra tax bill and could not figure out how to reduce it.  That could have been a nice new car or a down payment on another little apartment.  Instead, I had to get a loan to pay my tax - bah, humbug.  Ever since then, I have been trying my best to claw my 25k back little by little.  One year, I paid only $11 personal tax.

The downside was that I also had to eat a lot of macaroni and cheese, because I did not earn a salary and my money stayed in my company.  The last few years, I am blissfully non-resident, living in the UAE, but then I ran into the non-resident rental income tax problem and had to cough up another unexpected few thousand, so one needs to stay vigilant and clued up and I had to start reading tax laws again.

Medical treatment keeps improving.  For middle class people, the average life span now, is 85 years.  Most people live ten years longer than they thought they would.  So, if you don’t want to die of hunger when you are 80, then you got to do a little thinking now.

The conventional wisdom is to get into the real estate rat race as soon as possible and then keep upgrading, and one day when you want to retire, downgrade to free up some capital and slowly consume it.

However, keeping all your eggs in one basket is risky and the above only works if the population is growing.  What if everyone is old, wants to sell and prices are down?  Then you either have to take the loss, or wait another five to ten years, while on a macaroni and cheese diet and once you consumed your capital, you are doomed.

Different Strategy - Cash Flow

I suggest a slightly modified strategy:  Don’t build Capital.  Build Cash Flow.

A big diamond is a capital investment.  It may be fantastic looking, but you cannot eat it.  To do anything useful with it, you have to sell it and diamonds seem to halve in value every ten years, so diamonds are a particularly bad investment actually, but it makes the point.

In contrast to useless fixed capital, if you have cash flow and you need more money - then you just wait a few weeks and then you have more money.

That first little apartment you bought?  Don’t sell it when you upgrade to a house, keep it, mortgage it, use it as collateral, let it.  Let the renter pay the mortgage.  Build your own small private real estate business starting on day one.

If you want to live somewhere else, then you can either buy or rent.  Depending on your citizenship, you can more easily buy property in certain countries, but you can rent anywhere in the world.  If you own five apartments in Canada, then you can rent one on a Greek island and live happily ever after.  You don’t have to buy an apartment in Greece.

OK, so you didn’t do all that and now want to sell your mini mansion?  Go ahead, but immediately buy four or five little apartments and let them.  Now, you have cash flow.  You also still have the capital, so if you want to buy something else, then you have collateral and cash flow and can negotiate a very low interest rate on your new mortgage, because you are a low risk lender with a profitable real estate business.

Caveats

The only certainties in life are death and taxes.  It is important to manage your tax liability from day one, since at 15%, it is your biggest single expense.

Did I say 15%?  You are paying 33%?   The way to get 15% is to register a private company.

That first little apartment?  Register a company and transfer the apartment to the company before you start letting it.  If you really have to sell the apartment - don’t!  Sell the shares in the company instead.  That way, you only pay about 12% tax effectively while you rent it out and you don’t incur capital gains tax when you sell it, due to the lifetime capital gains exemption (about $800,000) on selling shares in small companies. (The apartment belongs to the company and doesn’t actually get sold - it still belongs to the same company - so no real-estate registration fees and taxes).

Non-resident Status

There is another problem with taxes for non-residents.  One day when you are old and grumpy, you may want to live somewhere else with a milder climate, which could make you a Non-Resident Canadian.   The effective tax rate for non-residents is higher than for residents.  The way to side step that to some degree, is to register a private company in BC (one of the provinces where a non-resident citizen is allowed to own a private company).  Then transfer whatever you owned to the company.  If you own multiple properties, register one company for each property - so that you can sell one, without affecting your other properties.

To become non-resident, first, don’t have an available residence.  If you do own a house, rent it to someone else, not a family member and don't let it sit empty either - because then it is 'available'.   The best solution is to transfer the house to a company and let the company rent it.  (Note that in Canada, a non-resident citizen is allowed to have a RRSP, but can only get further contribution headroom from Canadian earnings.  So when you leave Canada, you don't have to wind up your RRSP and you don't have to sell your house to become non-resident.)

Then, get on a plane, go somewhere far away, rent a little place on a beach and stay there.  Preferably do this in late December - it makes the taxes easier, since you need not prorate.  Don’t go back.  You are now non-resident - don’t ruin it.  The next year, file a Non-Resident Tax Return (5013-R T1 and Guide T4058) before 30 April.  Simple as that.

There is a special form NR74, which one can use to ask Revenue Canada to rule on your tax resident status.  That is not a good idea.  What if they rule against you?  It is likely best to assume that you have non-resident status and simply file the non-resident tax return.   Then, if they want to dispute your assumed tax status, they have to prove their case, which would be impossible for them to do after you already lived overseas for a year or two.

If you are non-resident, you have to pay 25% tax on gross rent received - no expense deductions allowed.  A small company pays about 15% on the net profit after expenses, so about 12% on average.  Therefore registering a company to handle your real estate is a no brainer if ever there was one.

When you need to take money out of the company, pay yourself a dividend, not a salary and file a T5.  A dividend, up to about $48,000, is not taxed again in your hands.

Why do small companies pay so little tax?

Small companies create employment.  Large companies destroy employment - that is called increasing productivity.  The government doesn’t want unemployed youths rioting in the streets.  Your little real estate company will employ young people to fix the plumbing, service the furnaces, replace the carpets, paint the walls, collect the rent, do the contracts and file your tax return, while you are in your canoe, fishing.  That is why.



See the nice beach volley ball court behind my car?  That is what a front yard lawn looks like in the UAE and those little bonzai trees are five years old already.  Al Ain has the widest beaches in the world.  We have 150 km of sand between us and the water.  It isn't quite walking or portage distance - so I got to stick my Bic canoe (Yes, of ballpoint pen fame - I'm a writer, eh?) on the car.

Why would you want to be a Non-resident Canadian?

Non-residents pay higher tax in Canada than residents, they don’t get the personal exemption of $11,000 and they don’t get free health care, so for some people, it is not a good idea to be non-resident.  If you or your wife has dual citizenship, then it may be a good idea though, since you may get better health care elsewhere (Canadian health care is neither the best, nor the worst in the world - Europe is probably the best). 

If you live and work in a low/tax free country for an extended period, then it is best to be non-resident Canadian, else you need to pay tax in Canada on your foreign income.

Only taxpayers resident in Canada have to file Form T1135 - Foreign Income Verification Statement.  So one day when you move back, you may have some explaining to do.


Further, if you go and live somewhere else for more than 6 months, then you could become non-resident, whether you wanted to be or not and if you live on a yacht, or always travel between 3 countries, then you may be non-resident everywhere.  So you need to be aware of the rules and it is possible to structure your tax obligations such that it works best no matter where you live and then you won’t get hit with an unexpected tax bill.

Lastly, be careful when you return!  It is best to return in the second half of the year, so that you are deemed non-resident the whole year, otherwise foreign earned income from the first half of the year may become taxable in Canada, saddling you with a bill, while it may have been much nicer to use that money for a holiday until the end of June.

RRSPs

If you have RRSP headroom when you leave Canada (who doesn't?), then you could stuff your rental income in there and thereby defer the 25% tax due, until the previously earned headroom is all used.  However,  one day when you retire and draw money, you may have to pay about 22% tax on the withdrawals, so it won't necessarily make much difference and you would need a lot of headroom, which you may not have.   Registering a company is still better by a good margin and you also avoid an ever growing capital gains tax problem.

If you end up living elsewhere and want to withdraw from your RRSP, then it will cost you 15% to 25%, depending on the tax treaty with your country of residence and whether it is a lump sum or a periodic withdrawal.  It may be a good idea to settle down in the ex-communist Central Europe - many hot springs, nice lakes and rivers, good health care and 15% withdrawal rates for most of them.

How?

If you are a masochist/bored, read up and do it all yourself at a registry shop, or find a young lawyer to do it all for you.  Your lawyer should be 30 years younger than you, so he/she can still do it for you when you are old and grumpy...

Notice of Assessment

I just received my Notice of Assessment - $0.00 due.  That is the way I like it.

Brexit

The British exit from the EU in 2017 is a new wrinkle/opportunity.  In order to be non-resident everywhere and pay personal income tax nowhere - you need to travel between three countries every year, so that you spend less than 6 months in any one tax jurisdiction.  That is why there are so many yachts rotting in marinas in and around Croatia.  With the UK exiting the EU, that trick may become a little easier again for some people and it could drive a new boom in the UK yachting business.

La Voila!

Herman

Monday, February 15, 2016

Network Emulator

In my experience, it doesn't help telling developers that a radio data link is inherently slow and unreliable and that it gets worse with increasing distance.  They will always design for the best case - 1 meter of copper wire in a lab - and then be all upset when it doesn't work so well in reality.

The solution is to make them a configurable network emulator from an old laptop PC (with a USB ethernet adaptor for a second port), put it between two of their machines and then stand back at a safe distance from any nerf guns or rubber band rifles and watch the wheels fall off the software.

This network torture tool uses netem and bridge-utils to create a transparent bridge between two ethernet ports.  This cruel script is prettied up with Zenity, so that one can use sliders to vary the delay and packet loss.

Either make the network utilities SUID root, or run the script as root.

#! /bin/bash
# Network Emulator
# Version 0.1, Copyright GPL, Feb 2016, Herman Oosthuysen
# Depends upon: zenity, ebtables, bridge-utils, netem
# SUID root: systemctl, killall, ethtool, ifconfig, brctl, iptables, ebtables, tc

# Configuration
export PORT0="eth0"
export PORT1="eth1"
export BR0="br0"
export SPEED="10"
export DUPLEX="full"
export IP0="0.0.0.0"
export IP1="192.168.1.1"
export MSK="255.255.255.0"
export DELAY="0"
export LOSS="0"
export RETURN="0"

zenity --question \
  --width=350 \
  --title="Network Emulator" \
  --text="Continue?"
 
if [ "$?" == "1" ]; then
  echo "Cancel"
  exit 0
fi


# First of all, disable NetworkManager and dhclient, 
# to prevent arguments over control of the ports.
systemctl stop NetworkManager
systemctl disable NetworkManager
killall dhclient
 
echo "Create a transparent bridge $BR0"
brctl addbr $BR0
brctl stp $BR0 off
brctl addif $BR0 $PORT0
brctl addif $BR0 $PORT1

echo "Full duplex, $SPEED bps"
ifconfig $PORT0 up
ethtool $PORT0
ethtool -s $PORT0 speed $SPEED duplex $DUPLEX autoneg off

ifconfig $PORT1 up
ethtool $PORT1
ethtool -s $PORT1 speed $SPEED duplex $DUPLEX autoneg off

echo "Enable IP4 forwarding"
ifconfig $PORT0 $IP0 promisc up
ifconfig $PORT1 $IP0 promisc up
echo "1" > /proc/sys/net/ipv4/ip_forward

# Give the bridge a pingable address
echo "Bridge IP = $IP1, Netmask = $MSK"
ifconfig $BR0 $IP1 netmask $MSK up

echo "Open iptables and ebtables to allow everything, INPUT, OUTPUT and FORWARD" 
iptables -F
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
iptables -P FORWARD ACCEPT

ebtables -F
ebtables -P INPUT ACCEPT
ebtables -P OUTPUT ACCEPT
ebtables -P FORWARD ACCEPT


# Create an initial rule
tc qdisc add dev $BR0 root netem delay $DELAYms 10ms 25%

(
while TRUE; do
  # Update the progress bar
  echo "#DELAY=$DELAY LOSS=$LOSS"
 
  # Get the packet delay in ms
  DELAY=$(zenity --scale \
    --text="Packet Delay milliseconds" \
    --value="0" \
    --min-value="0" \
    --max-value="100" \
    --step="1")
   
  # tc qdisc change dev eth0 root netem delay 100ms 10ms 25%
  tc qdisc change dev $BR0 root netem delay $DELAYms 10ms 25%
 
  # Update the progress bar
  echo "#DELAY=$DELAY LOSS=$LOSS"
 
  # Get the packet loss in 1/x%
  LOSS=$(zenity --scale \
    --text="Packet Loss Fraction %" \
    --value="0" \
    --min-value="0" \
    --max-value="100" \
    --step="1")
   
  LOSS=1/$LOSS
  # tc qdisc change dev eth0 root netem loss 0.3% 25%
  tc qdisc change dev $BR0 root netem loss $LOSS% 25%
 
  # Update the progress bar
  echo "#DELAY=$DELAY LOSS=$LOSS"
 
  zenity --question \
    --width=350 \
    --title="Network Emulator" \
    --text="Continue?"
   
  if [ "$?" == "1" ]; then
    echo "Cancel"
    echo "100"
    exit 0
  fi
done
) | zenity --progress \
  --width=350 \
  --title="Network Emulator" \
  --text="Running..." \
  --no-cancel \
  --auto-close \
  --pulsate

echo "Done!"
exit 0


La voila!

Herman

Friday, February 12, 2016

Mirror, Mirror on the Wall...

A Private Linux Mirror

Debian/Ubuntu mirroring is also described down at the bottom - it is super simple.

A Private Fedora Mirror

If you need to replicate Fedora based machines, then you need to set up your own rpm file mirror.  This allows you to automate the whole install with Kickstart off your own server on a LAN and you can then freeze your server at arbitrary points to facilitate a production run of identical machines.

The installation server can be an old laptop PC with a huge USB disk (reformat the disk with gparted to ext4.  The file system must support UNIX permissions and links).  The file server doesn't have to be very fast.  To do an install, you only need this server machine, a big switch and bunch of target machines with Kickstart (https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Installation_Guide/ch-redhat-config-kickstart.html) and do a netboot, using DHCP and a web server such as lighttpd.

To make your own mirror server, you should set up an account with Fedora, so that you can get access to their servers and allow them to transparently redirect your machines to your own server if necessary.

Once you opened an account, you can set up a rsync script to download and save only what you need.  The secret to success with rsync is the EXCLUDES file.  In there, list patterns of directory names and files to avoid.  For example, if you only want Fedora 22, then you do that, by excluding 4, 5, 6... 21 and 23, plus a few other junk things that will show up once you try it.

More details here: https://fedoraproject.org/wiki/Infrastructure/Mirroring#Mirroring

FAS Account

Open an account here: https://admin.fedoraproject.org/mirrormanager - Without an account, you won't be able to download anything with rsync.

Create a new Site, for example mirrors and set the password to something secure.  Specify the Organization URL if you have one and be sure to select the Private checkbox and then save the site.

Now create a Host with a FQDN of fedora.example.com.  Set the Country code to US and again make sure the Private checkbox is enabled and save the Host.  Once saved, add a new Site-local Netblock.  Go to http://whatismyip.com and make a Netblock 1.2.3.4/32.

Once this is saved, still under the Host setting, add a new Category. This will tell the Mirror Manager what categories of software this host carries. Examples include Fedora Linux and add a URL serving the content definition, such as http://fedora.example.com/mirrors which you need to use in your Lighttpd or Apache web server setup.

Note that if you don't want to do the FAS thing, you can do the same as below with any other Fedora mirror close by at a university or Telco that you trust, but you'll have to research the excludes list and rsync group carefully.

For a full public mirror list, click on something in the matrix here:
https://admin.fedoraproject.org/mirrormanager


e.g.:
https://admin.fedoraproject.org/mirrormanager/mirrors/Fedora/22/aarch64


and

http://ftp-stud.hs-esslingen.de/pub/fedora/linux/releases/22/

Excludes

The most important thing is the excludes file and nobody ever tells what needs to be in there, which prompted me to write this article.  If this file is not good, then rsync will download everything since the abacus was invented and your disk drive is bound to fill up.  The file excludes.list below will exclude everything but Fedora 22:

*/alt*
*/archive*
*/epel*
*/fedora-secondary*
*/atomic*
*/core*
*/development*
*/extras*
*/test*
*/Docker*
*/Cloud*
*/releases/4/*
*
/releases/5/*
*
/releases/6/*
*/epel-release-latest-5*
*/epel-release-latest-6*
*/epel-release-latest-7*
*
/releases/7/*
*
/releases/8/*
*
/releases/9/*
*
/releases/10/*
*
/releases/11/*
*
/releases/12/*
*
/releases/13/*
*
/releases/14/*
*
/releases/15/*
*
/releases/16/*
*
/releases/17/*
*
/releases/18/*
*
/releases/19/*
*
/releases/20/*
*
/releases/21/*
*
/releases/23/*

The only thing not in there, is 22.  As you can see I also don't want Cloud and Docker schtuff, but I do want Arm, i386 and X64 - you may want to tweak it some more.

You can see all the directories you may need to exclude by trolling up and down the tree of the mirror server here: https://dl.fedoraproject.org/pub/fedora/linux/releases/

Rsync vs Wget

The mirroring is recommended to be done with rsync, which will download a group on the server called fedora-enchelada (which plays on 'the whole enchelada' - everything since the abacus).

I have in the distant past made mirrors using wget, but rsync is more efficient and easier to control.  Rsync will honour the excludes list and will not traverse outside its designated directory, but wget will invariably start to walk across to other directories at the same level, thereby downloading more files than it was supposed to, so you have to keep an eye on it and quit it when you think that it is done with what you want (or set it to one directory deeper than what you actually want - like the example below and then let it be).

If you want to use wget, here is an example:
$ wget --continue --recursive --no-parent --no-clobber \
    http://ftp-stud.hs-esselingen.de/pub/fedora/linux/releases/22/Live/x86_64

The above wget script will also download other directories under the Live subdirectory, not only the x86_64 one, so you have to watch it.  Wget also has an exclude directive that doesn't work.  Despite these issues, it does work and can be used to download a mirror that doesn't support rsync, or for which you don't have a download account.

Mirror Script

For testing the rsync script below, I made a mirror directory tree in my home directory ~/mirrors

This tree actually needs to be in the web server root which is usually /var/www to serve the files to Kickstart and dnf.


The rsync script called mirror.sh looks like this:

#! /bin/bash
# Mirror Fedora 22 only - at least, that is the idea
# See the exludes.list file - rsync will download everything, except for the patterns in this file
# See the mirroring wiki for details: https://fedoraproject.org/wiki/Infrastructure/Mirroring#Mirroring

export EXCLUDES="excludes.list"

rsync -vaH --exclude-from=${EXCLUDES} \

 --numeric-ids --delete --delete-after --delay-updates \
 rsync://dl.fedoraproject.org/fedora-enchilada ~/mirrors


Make this file executable with chmod 755 mirrors.sh, run it and see what happens.

The first thing rsync does is to download the files list and build a directory tree in ~/mirrors.  While rsync runs, view this growing tree and make sure that it only includes what you want and that unwanted directories remain empty.

If there is a growing pile of files that you don't want, press Ctrl-C to quit the script, add a pattern to the excludes.list file, delete the junk and try again.  Don't leave the machine alone until you are sure that you get only what you want and no more, or you may end up with a terabyte of useless files.



A Private Ubuntu Mirror

On Ubuntu mirrors, all the files are stored in a single directory called pool.  In there, you find all versions of everything.  The releases are controlled through a system of Master Record Index files that list everything about every file in a release.  These index files are zipped up and kept in a directory tree using the release names like Trusty or whatever.  These files will keep your CM manager as happy as a piggy in a mud bath.

The problem with this system is that you cannot replicate an Ubuntu mirror with rsync, unless you copy everything since Adam invented the Abacus, which is about 800 GB.  To get only the files belonging to a specific release, you need a utility that can parse the index files.  This utility is called apt-mirror and it will download about 100 GB of executables for the Trusty release.

Apt-mirror does exactly what is written on the tin.  It Just Works (TM).



The easiest way to run apt-mirror is to make a server with the same release as what you want to mirror and install the package apt-mirror.  You then only need to change one single line in /etc/apt/mirror.list to point to the place where you want to keep all the files and run apt-mirror (The directory must exist). That is all there is to it.

The most important thing with mirroring is to avoid using a Seagate USB disk that shuts itself down every once in a while.

What I eventually did was to uncomment the lines in mirror.list one by one and save the files on USB sticks.  The first line for main needs about 60 GB, which fits on a modern 64 GB schtick. The following lines of updates and security fixes require about 30 GB storage, about 90 GB total for the compiled code and goodness knows how much for the C-code.

Downloading 100 GB will take about 2 days on a typical 4 Mbps home fibre net, vs weeks on a typical overloaded corporate network.

Note that you can interrupt and restart apt-mirror.  It will figure out what happened and carry on where it left off without a complaint.

Apt-mirror is pretty robust.  I managed to fill up my USB thingies to the max on an Ubuntu VM, then copied them together with rsync -a to a larger SD card, made a raw device file for VirtualBox so it could access the SD card, mounted the SD card in the same path and carried on with apt-mirror and finally copied the SD card to my Fedora mirror server.  All done with nary a hiccup.


GPG - InRelease Clearsigned file isn't valid, got 'NODATA'

This error drove me up the wall.  The InRelease file seems to be somehow corrupted by apt-mirror. The solution is to delete the InRelease file from the mirror server.

Another one of life's little mysteries...

Seagate USB Disks

Those infernal Seagate USB disks need something like this command to stay awake:
$ sudo sdparm --clear STANDBY -6 /dev/sdb -S

In addition, if you are running a Virtualbox virtual machine, do not use a USB3 port (yellow) for an external disk.

How to Add a Repo to Ubuntu

I simply hack the /etc/apt/sources.list file. 

The politically correct way is to add a .list file to /etc/apt/sources.list.d/


La voila!

Happy mirroring...

Herman