date over HTTP

I always manage to get myself into weird issues… I have this (pretty old) wrt54g router that works well with dd-wrt v3.0-r34311 vpn release. This router is installed in an apartment intended for rental where I happen to crash every now and then. It connects to an OpenVPN hub of mine so I can monit it and be sure guests renting the apartment have working Internet access.

The apartment is located on a small mountain and electricity is not exactly stable, from times to times power goes down and comes back up. And I noticed the openvpn link sometimes fails to reconnect.

After some debugging, I finally noticed that for some reason, the enabled NTP feature sometimes do not fetch the current time, and so the router’s date is stuck to epoch.

In order to be sure the access point gets the right time, I took a different approach, when booting, it will fetch current time online and setup date accordingly.
I was surprised not to find any online website providing some kind of strftime REST API, so I finally decided to put something up by myself.
nginx ssi’s module has interesting variables for this particular use, namely date_local and date_gmt. Here’s related nginx configuration:

location /time {
	ssi on;
	alias /home/imil/www/time;
	index index.html;
}

index.html contains the following:

<!--# config timefmt="%Y-%m-%d %H:%M:%S" -->
<!--# echo var="date_gmt" -->

This particular time format was chosen because this is busybox supported date set format, and as a matter of fact, dd-wrt uses busybox for most of its shell commands.

On the router side, in AdministrationCommands, the following oneliner will be in charge of verifying the current year and call our special URL if we’re still stuck in the 70’s:

[ "$(date +%Y)" = "1970" ] && date -s "$(wget -q -O- http://62.210.38.67/time/|grep '^2')"

Yeah, this is my real server IP, use it if you want to but do not assume it will work forever ;)

And that’s it, click on Save Startup in order to save your command to the router’s nvram so it is called at next restart.