Friday, 4 October 2013
Five years
I'm really surprised I've managed to keep on writing more or less regularly for five years on this blog. There are now about 360 articles on this site, which gives an average of about one per week. That's a nice metric, even if not very accurate. I spent almost a year without writing, while moving to a different country. Maybe I should start a blog about that too.
Here's for five years more!
Thursday, 3 October 2013
Setting up a Linux GW II: NATting and forwarding
We'll do this by setting up NAT with iptables. We'll also have to configure the OS to forward connections from one network card to the other:
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
# Add a line like this for each eth* LAN
iptables --append FORWARD --in-interface eth1 -j ACCEPT
We will also need to setup the IP for eth0, since there won't be a DHCP server (we ARE the server!). Open /etc/network/interfaces and add something like this:
# Configure the WAN port to get IP via DHCP
auto eth0
iface eth0 inet dhcp
# Configure the LAN port
auto eth1
iface eth1 inet static
address 192.168.10.1 # (Or whatever IP you want)
netmask 255.255.255.0 # Netmasks explanations not included
Once that's checked, restart networking services like this:
sudo /./etc/init.d/networking restart
Everything ready, now just plug your PC to the new router and test it. Remember to manually set your IP in the same network range as your router, since there's no DHCP at the moment. This may be useful to debug a problem.
In your client PC, set your IP address:
ifconfig eth0 192.168.10.10
Test if you IP is set:
ping 192.168.10.10
If you get a reply, your new IP is OK, if not there's a problem with your client. Second step, see if you can reach the router:
ping 192.168.10.1
Note that you may need to renew everything (i.e. restart networking and manually assign your IP) after you connect the cable.
Again, if you get a reply then you have connectivity with the router. So far we haven't tested the iptables rules nor the forwarding, so any issue at this point should be of IP configuration. If everything went well, it's time to test the NAT rules and the forwarding.
ping 192.168.1.1
That should give you an error. Of course, since there's no DHCP there's no route set. Let's manually set a route in the client:
sudo route add default gateway 192.168.10.1
Then again:
ping 192.168.0.1
Magic! It works! If it doesn't, you have a problem either in the NAT configuration or the IP Forwarding of the router. You can check this with wireshark, if the pings reach the server but they never get a reply back then it's the NAT, i.e. it can forward the IP packages on eth1 to eth0 but the router has no NAT, and it doesn't know how to route the answer back. If the pings never even reach eth0, then you have an ip forwarding problem.
Persisting the forwarding rules
In order to have the forwarding rules persisting after a reboot, we need first to change /etc/sysctl.conf to allow IP forwarding. It's just a mater of uncommenting this line:
net.ipv4.ip_forward = 1
We will also have a lot of iptables rules we need to setup during boot time. I have created a script at /home/router/set_forwarding.sh, which I also linked into /etc/init.d/rc.local so it's run whenever the system boots.
Next time we'll move on to something more complex: installing a DNS server and using domains instead of IPs.
Tuesday, 1 October 2013
C preprocessor VII: Recursive expansion on function macros
Clearly that's too easy for C. We need more complexity: we need to make the expansion rules interact with the argument substitution process and the preprocessor operators too!
How exactly? The whole process is specified by a very tiny paragraph, 16.3.1, on the standard, which despite being tiny contains a lot of information. Actually, it contains all the expansion and precedence rules for the preprocessor. And it's more or less like this:
- Argument scanning: the perprocessor binds a set of tokens to each argument name. If there are extra arguments and the token "..." is part of the macro's signature, a __VA_ARGS__ argument is created. (to put it simply: it will bind a set of tokens like "(a,b)" to an identifier like "ARG1").
- Stringify and token pasting is applied ONLY to the arguments, not to the body function.
- Each argument is recursively scanned for macro expansion, as if each argument was on a file on its own (imagine a new file is created with only preprocessor directives and the argument, then apply the expansion algorithm recursively to that file).
- After the arguments have been fully expanded, they are substituted on the macro's body.
- The resulting definition is then rescanned for macro expansions or token pasting operators.
- A side effect of this multi-phase macro expansion is that the nice expansion tree we used to have no longer works.
Let's take this example:
#define str(...) #__VA_ARGS__
#define foo(a, b) foo a bar str(b)
#define bar foo bar 1
foo(bar, (1, 2, 3))
How can we expand this macro call? Like this:
expand{ foo(bar) }
Match foo with definition of macro: foo(a)
Bind a to bar
Macro expand argument a -> expand{ bar }
bar takes no arguments, no binding is done
Apply rule bar -> foo bar 1
Scan the result for new expanions
foo was already expanded, no further expansion
Bind b to (1, 2, 3)
Macro expand argument b -> nothing to expand
Replace macro expanded arguments in body definition:
-> foo foo bar 1 bar str((1, 2, 3))
Rescan the body for further expansion:
foo: Already expanded on current scope
foo: Already expanded on current scope
bar: Already expanded (The compiler will have too keep a map of expanded macros for each identifier in a definition!)
bar: Needs expansion
Apply rule bar -> foo bar 1
Rescan for further expansion
foo: Already expanded on parent scope
bar: Already expanded on current scope
str((1, 2, 3)): Expand macro call
Bind (1, 2, 3) to __VA_ARGS__
Analyze (1, 2, 3) for further expansion
Apply operator '#' to (1, 2, 3) -> "(1, 2, 3)"
Replace #__VA_ARGS__
Replace the result of str((1,2,3)) -> "(1, 2, 3)"
Replace the original call "foo(bar, (1, 2, 3))" for the result
-> foo foo bar 1 foo bar 1 "(1, 2, 3)"
This last example should be a good representative of the complexities involved in a macro expansion; hopefully now you know more than you ever wanted to know about macros.
Thursday, 26 September 2013
Setting up a Linux gateway/router, a guide for non network admins
I'm going to write about how can you setup a regular Linux distro to be your border router/gateway for your LAN, but for easy of use I'll base my examples on Ubuntu.
As expected, if we are going to replace a device, say, a router, we need to replace it with something that can provide the same functionality. In this case, we have chosen a Linux server, so we need to figure out which services are provided by the router and then emulate them someway:
- DHCP to manage leases
- DNS to translate domains to IPs
- NAT, to multiplex a single connection
- Service forwarding, to expose internal services to an external network
- ISC for DHCP
- bind9 for DNS
- iptables for NAT
- iptables again, for service forwarding
Preliminary work, the hardware setup
Before you setup any services, you are going to need two things: first two network cards, one for the outgoing connection and another one for the (switched) LAN, and a way of telling your server that you want all traffic from network 1 forwarded to network 2. You may want to install more than two cards, in case you need to route several LANs. We'll see that later.You will also need an OS. I have chosen Ubuntu because it's very simple to install, and has all the software we need available in the repositories, but you can use any other distribution if it suits your needs.
Also, throughout this guide I will assume a setup like this:
- WAN access through eth0, DHCP address
- LAN routing in eth1, network 192.168.10.1/24
If you don't have all this hardware...
Not everyone may have two spare desktops with three NICs ready for testing. Even if you do, you may be too lazy to setup the physical part of your network. If this is your case, you can also setup a virtual machine to emulate your setup, and Virtualbox is great for the task:- Begin by creating what will be your router VM.
- Enable the first network adapter. This one should be able to see your physycal router (i.e. connect to a WAN).
- Enable a second network adapter. Use the 'Internal network' option in the 'Attached to' field. This will be your LAN interface.
- Create a second VM. This one will be your client.
- Enable a single network adapter, attached to an internal network as well. The name for this network should match that of the other VM.
Tuesday, 24 September 2013
C preprocessor VI: Recursive macro expansion rules
Let's start with a simple example:
#define foo bar 1
#define bar foo 2
foo
Luckily the preprocessor is smart enough not to trip up on this simple piece of code. When expanding foo on line three it will do something like this:
#define foo bar
#define bar foo
foo
// Applies foo -> bar 1
bar 1
// Applies bar -> foo 2
foo 2 1
// Scans foo again... but doesn't expand it
The second time the preprocessor scans foo it won't expand it: it "knows" foo was already expanded, so it won't do it again. But how does it know that foo was already expanded? Let's try something a bit more complicated:
#define foo bar a baz b
#define bar foo 1
#define baz bar 2
foo
And then let's see how foo is expanded, step by step:
#define foo foo a bar b baz c
#define bar foo 1
#define baz bar 2
foo
First the rule "foo -> foo a bar b baz c" will be applied and the results rescanned: let's call this scope 1. We'll end up with:
foo a bar b baz c
Now the results of this expansion will be scanned, in a new scope. Let's call it scope 2. The first token the preporcessor will see is "foo", which was already expanded on scope 1: it will be ignored and it will continue to the next expandable token, "bar", and it will expand it like this:
foo a foo 1 b bar 2 c
On the scope that baz's expansion creates (scope 4), the parent's scope expansion rules are "inherited", so for scope 4 "foo" was already expanded but "bar" was not, because bar's expansion happened on scope 3 and scope 3 is not scope's 4 parent. Not following me? Try following this diagram:
foo -> foo a bar b baz c
foo -> already expanded, ignore
a -> not a macro, ignore
bar -> expand to "foo 1"
foo -> expanded at parent scope, ignore
1 -> not a macro, ignore
b -> not a macro, ignore
baz -> expand to "bar 2"
bar -> expand to "foo 1"
foo -> already expanded at parent scope, ignore
1 -> not a macro, ignore
2 -> not a macro, ignore
c -> not a macro, ignore
Hopefully the preprocessor expansion rules should be a bit more clear now: each expansion creates a scope, each scope inherits from parent's scopes whether a rule was applied or not and if it was then said rule is ignored in the current scope.
Of course these rules get more complicated when dealing with token pasting and stringifying operators, because each phase (stringifying, token pasting, rescanning and expansion) will happen in a specific order. Things get even more complicated when you realize (by reading the standard) that said order is not the same when you deal with argument replacement.
Then again, it's probably a good idea if your macros don't rely on the recursive expansion rules of the preprocessor.
Thursday, 19 September 2013
Vim tip: Jump to a tag definition
Just add this magic spell to your .vimrc; next time you open a file in a project with a tags file generated just press ctrl-enter with your cursor over the definition you wish to find:
map <C-CR> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>
Tuesday, 17 September 2013
C preprocessor V: Conditionals
#if 0
# if 0
# else
# elif true
# endif
#endif
Clearly the inner if is wrong because the else clause comes before the elseif, however you might think it doesn't matter because it's surrounded by an #if 0. Surprise: it does matter, that's not valid preprocessor input. Even if the outer #if is not "taken", whatever preprocessing directives are inside it should still be valid (though anything that's not a preprocessing directive will indeed be ignored).
Even though at first it might seem weird for things inside an #if 0 to be important, it makes sense if you think that should an internal #if not respect the proper structure then the preprocessor wouldn't know when to end the first #if 0. Then again, if you find any real-world utility to this bit of preprocessor implementation trivia, you are doing something horribly wrong!
Thursday, 12 September 2013
Vim tip: open file under cursor
gf open in the same window ("goto file")
f open in a new window (Ctrl-w f)
gf open in a new tab (Ctrl-w gf)
Tuesday, 10 September 2013
C preprocessor IV: VA Args
#define DEBUG(fmt, ...) printf(fmt, __VA_ARGS__);
Combining this with stringify will provide you hours of fun. Combining this with token pasting... well, that's just evil.
Thursday, 5 September 2013
Stopping commits on git
Who hasn't commited debug code by mistake? It's only normal to forget to remove an #include we added only to test some stuff. Luckily it's easy to tell git that we don't want to commit any changes with a certain string.
On any (git) repo you'll find a .git/hooks folder; add this script in .git/hooks/pre-commit (and don't forget to chmod +x it):
#!/bin/sh
if [ 0 != `git diff | grep "STOPCOMMIT" | wc -l` ]; then
echo "Error: STOPCOMMIT found, remove it before commiting";
git diff
exit 1
fi
Now git will check your commits and stop them if they contain the STOPCOMMIT string. Now you can add all the debug changes you want, as long as you add a //STOPCOMMIT after them you'll never end up commiting them by mistake.
Monday, 2 September 2013
C preprocessor III: Token pasting
#define PASTE(x, y) x ## y
#define FOOBAR 42
int main() { return PASTE(FOO, BAR); }
The previous code would just return 42. So what's the usefulness of a paste operator? Other than obfuscating stuff, you can use it to create classes with similar interfaces but different method names (I'm not saying it's a good idea, I'm saying you can). For example:
#define MAKE_GET_SET(x, T) \
void set_ ## x (T o) { this->x = o; } \
T get_ ## x () { return this->x; }
class Foo {
MAKE_GET_SET(foo, int);
The token pasting operator doesn't have the limitation of being applicable only to a macro parameter, so code like "12 ## 34" is a perfectly valid operation which results in "1234". It does have a catch: if the resulting token is not valid the behavior is undefined. This means that, for example, pasting "12" and "foo" together produces "12foo", which is not a valid token. Being the operation undefined means that a compiler might reject this operation (I'm pretty sure gcc does) or that it might do a completely different thing (it could choose to ignore the token pasting operator and it would still be standard compliant).
Nasal demons FTW!
Thursday, 29 August 2013
Vrapper: a real text editor for Eclipse
Vrapper provides pretty decent text editing capabilities for Eclipse, I'd almost say it makes it usable. And, as a beneficial side effect, now your coworkers wont' be able to touch your Eclipse anymore!
Tuesday, 27 August 2013
C preprocessor II: stringify operator
#define f(x) to_str(x) == #x
f(123)
Would print
to_str(123) == "123"
A restriction applies to the stringify operator: it can only be applied to a macro param, not just any token. So this, for example, is an illegal macro:
#define f(x) #123 == #x
There's another operator, which is a bit more "esoteric". We'll talk about token pasting next time.
Thursday, 22 August 2013
Crazy git error
fatal: example.com/repo.git/info/refs not found: did you run git update-server-info on the server?
It can be very baffling, because it may happen even if you change absolutely nothing in your git's configuration. I've read most people attribute this to a typo, and that seems to be the most common case, but I found yet another thing that might trigger this error: if you have set a proxy server, for example for wget, using an environment variable like http_proxy, https_proxy or ftp_proxy then git might be tripping up on your proxy and producing this error message.
Tuesday, 20 August 2013
C preprocessor: Just a simple replacer?
During my time toying with the preprocessor I learned a few things about recursion, the different operators supported by it and some crazy things about the order of conditional evaluation. I'll summarize some of the things I learned in the next few posts: you might want to check 16.3 in the C++ standard, since the next few articles will be only explanations about different paragraphs on this section.
Disclaimer: if you find any real-world utility to these bits of preprocessor trivia, you are probably doing something horribly wrong or horribly evil!
Thursday, 15 August 2013
Avoid compile warnings from 3rd party libs with gcc
When including a third party library (like, for example, boost) you will almost never have the option to fix any of the diagnostics that your compiler helpfully provides you. If there's nothing you can do about them, there's no point in getting the warnings either. Disabling -Weffc++ is also not a good idea. If you already took the effort of cleaning your code to such a high standard, you shouldn't now relax it.
There's a third option: When compiling don't include those libs as "-I /path/to/lib", do it as "-isystem /path/to/lib". Gcc will now know those warnings are not your fault and it will stop nagging you.
Tuesday, 13 August 2013
Git tip: auto update your ctags
ctags -R -f .ctags .
Now every time you do a git pull your ctags file will automagically update. You might also want to copy or ln -s this script for the post-commit hook, if you want to run a ctags update on each git commit. Be aware that this will make your commits slower, if generating your tags file takes a long time.
Extra tip: "-f .ctags" will make ctags write into a hidden file, .ctags, which you can then add to .gitignore. Now ctags magically works in Vim and you won't even need to see your tags file (just don't forget to "set tags=./.ctags;/" on vim).
Thursday, 1 August 2013
Pictag: finally a simple geotagging tool for Linux
TL;DR: Link to a mostly working hacked version of Pictag, on my Github repo.
Since Google decided not to support Picasa for Linux anymore (yes, a long time ago) I've been looking for a decent photo management alternative. Lately I've settled with Digikam, it does everything Picasa used to do (and much better, I may add) except for providing a way to geotag your pictures on a map.
Most geotagging solutions involve having an already created waypoints map from a GPS device, which then gets processed and magically added to the images' exif data. That didn't cut it for me, I don't have, nor want, a GPS I can take on holidays, plus I really only want to drag and drop pictures on a map. That's where pictag comes in.
At the moment pictag seems to be a bit abandoned, as there are no more packages for Ubuntu 13.04. Luckily with some hacking it's possible to get it running.
First, since there's no package for Pictag you'll need to take care of the dependencies yourself. On a more or less vanilla 13.04 install, this should do the trick:
sudo apt-get install python-setuptools \
python-distutils-extra \
geoclue-ubuntu-geoip \
liblaunchpad-integration-common \
libchamplain-0.12-0 \
libchamplain-0.12-dev \
libchamplain-gtk-0.12-0 \
libchamplain-gtk-0.12-dev \
python-pyexiv2 \
libclutter-gtk-1.0-0 \
libclutter-gtk-1.0-dev
After you've taken care of that you can download the latest version from Launchpad (while writing this article that should be 12.07.17) and run ./bin/pictag, only to watch it fail miserably.
Pictag seems to be using GSettings, a very annoying Gnome settings manager which won't work unless you actually install whatever program you're trying to run. Luckily we can just hack it out of Pictag simply by commenting out all references to self.settings in PictagWindow.py and Window.py. Either that or get my hacked version of Pictag, on my Github repo.
With some luck, my hacked version of Pictag should run pretty much OK on Ubuntu 13.04 or newer. There seems to be a few issues with libchamplain (the mapping library) on earlier versions of Ubuntu that may cause the map to display only broken images. If you can't load any maps you'll have to get a newer Ubuntu. Or fork my repo and get hacking :)
Tuesday, 30 July 2013
Force a program to output to stdout
With this trick you could, for example, run "gcc -S foo.cpp -o /dev/stdout", to get the assembly listing for foo.cpp.
You probably shouldn't use this trick on anything other than CLI scripting stuff (keep in mind /dev/stdout might be closed or not accessible for some processes).
Thursday, 25 July 2013
C++ exceptions under the hood appendix III: RTTI and exceptions orthogonality
Exception handling on C++ requires a lot of reflexion. I don't mean the programmer should be reflecting on exception handling (though that's probably not a bad idea), I mean that a piece of C++ code should be able to understand things about itself. This looks a lot like run-time type information, RTTI. Are they the same? If they are, does exception handling work without RTTI?
We might be able to get a clue about the difference between RTTI and exception handling by using -fno-rtti on gcc when compiling our ABI project. Let's use the throw.cpp file:
g++ -fno-rtti -S throw.cpp -o throw.nortti.s
g++ -S throw.cpp -o throw.s
diff throw.s throw.nortti.s
If you try that yourself you should see there's no difference between the RTTI and the No-RTTI version. Can we conclude then that gcc's exception handling is done with a mechanism different to RTTI? Not yet, let's see what happens if we try to use RTTI ourselves:
void raise() {
Exception ex;
typeid(ex);
throw Exception();
}
If you try and compile that, gcc will complain: you can't use typeid with -fno-rtti specified. Which makes sense. Let's see what typeid does with a simple test:
#include <typeinfo>
class Bar {};
const std::type_info& foo()
{
Bar bar;
return typeid(bar);
}
If we compile this with "g++ -O0 -S", you will see foo compiled into something like this:
_Z3foov:
.LFB19:
# Prologue stuff...
subl $16, %esp
# Bar bar
movl $_ZTI3Bar, %eax
# typeid(bar)
leave
# Epilogue stuff...
_ZTS3Bar:
# Definition for _ZTS3Bar...
_ZTI3Bar:
.long _ZTVN10__cxxabiv117__class_type_infoE+8
.long _ZTS3Bar
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
Does that look familiar? If it doesn't, then try changing the sample code to this one:
class Bar {};
void foo() { throw Bar(); }
Compile it like "g++ -O0 -fno-rtti -S test.cpp" and see the resulting file. You should see something like this now:
_Z3foov:
# Prologue stuff...
# Initialize exception
subl $24, %esp
movl $1, (%esp)
call __cxa_allocate_exception
movl $0, 8(%esp)
# Specify Bar as exception thrown
movl $_ZTI3Bar, 4(%esp)
movl %eax, (%esp)
# Handle exception
call __cxa_throw
# Epilogue stuff...
_ZTS3Bar:
# Definition for _ZTS3Bar...
_ZTI3Bar:
.long _ZTVN10__cxxabiv117__class_type_infoE+8
.long _ZTS3Bar
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",@progbits
That should indeed look familiar: the class being thrown is exactly the same as the class that was used for typeid!
We can now conclude what's going on: the implementation for exception throwing type information, which needs reflexion and relies on RTTI info for it, is exactly the same as the underlying implementation for typeid and other RTTI friends. Specifying -fno-rtti on g++ only disables the "frontend" functions for RTTI: that means you won't be able to use typeid, and no RTTI classes will be generated... unless an exception is thrown, in which case the needed RTTI classes will be generated regardless of -fno-rtti being present (you still won't be able to access the RTTI information of this class via typeid, though).