<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Weird rocketry &#187; sysadmin</title>
	<atom:link href="http://webapp.org.ua/category/sysadmin/feed" rel="self" type="application/rss+xml" />
	<link>https://webapp.org.ua</link>
	<description>Flights to outer code</description>
	<lastBuildDate>Sat, 16 Jul 2016 11:12:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>OpenWRT Chaos Calmer 15.05 on Dlink DIR-320 with CDMA modem</title>
		<link>https://webapp.org.ua/dev/openwrt-chaos-calmer-15-05-on-dlink-dir-320-with-cdma-modem/</link>
		<comments>https://webapp.org.ua/dev/openwrt-chaos-calmer-15-05-on-dlink-dir-320-with-cdma-modem/#comments</comments>
		<pubDate>Thu, 07 Apr 2016 11:53:19 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[dev]]></category>
		<category><![CDATA[hardware]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[3.18]]></category>
		<category><![CDATA[AirCard 250U]]></category>
		<category><![CDATA[brcm47xx]]></category>
		<category><![CDATA[cdma]]></category>
		<category><![CDATA[dir-320]]></category>
		<category><![CDATA[dlink]]></category>
		<category><![CDATA[extroot]]></category>
		<category><![CDATA[image builder]]></category>
		<category><![CDATA[linux kernel]]></category>
		<category><![CDATA[openwrt]]></category>
		<category><![CDATA[opkg]]></category>
		<category><![CDATA[PL2303TA]]></category>
		<category><![CDATA[serial]]></category>
		<category><![CDATA[sierra]]></category>
		<category><![CDATA[usb-ttl]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=492</guid>
		<description><![CDATA[The goal of this article is to install latest OpenWRT firmware on a very popular DIR-320 Wi-Fi router (BRCM47XX based). The reason why you might do this is to be able to connect modern hardware(modems) to this pretty old legacy device. Official firmware 3G modem support list is pretty limited and uses old kernel. On [...]]]></description>
			<content:encoded><![CDATA[<div class="markdown-content">
<p><a href="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_logo_dir-320.jpg"><img src="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_logo_dir-320.jpg" alt="" title="openwrt_logo_dir-320" width="474" height="353" class="alignleft size-full wp-image-505"/></a></p>
<p>The goal of this article is to install latest OpenWRT firmware on a very popular DIR-320 Wi-Fi router (BRCM47XX based). The reason why you might do this is to be able to connect modern hardware(modems) to this pretty old legacy device.</p>
<p><a href="http://ftp.dlink.ru/pub/Router/DIR-320/Data_sh/RevA/Supported%203G%20modems.pdf">Official firmware 3G modem support list</a> is pretty limited and uses old kernel. On the other hand, there is an alternative <a href="http://www.dd-wrt.com/site/index">DD-WRT</a> firwmare with linux kernel 2.6.x which is pretty old also. Therefore, the only viable option is installing OpenWRT which ships the latest linux kernels 3.18.xx.</p>
<p>As a bonus sub-topic we&#8217;ll consider setting up an external CDMA(EVDO) modem and using it to access internet.</p>
</div>
<p><span id="more-492"></span></p>
<div class="markdown-content">
<p><br style="clear:left;"/><br />
In order to proceed and experiment by yourself the following is necessary:</p>
<ul>
<li><a href="https://wikidevi.com/wiki/D-Link_DIR-320_rev_A1">Dlink DIR-320 router</a> (<em>rev. A1/A2 only!</em>, be careful as there are B1/B2/NRU versions which are completely different hardware!)</li>
<li>RJ45 CAT5 Patch cable</li>
<li>USB to Serial adapter (I&#8217;ve been able to successfully use cheap <a href="http://www.ebay.com/sch/i.html?_nkw=Module+Converter+Serial+Adapter+Cable+For+Win+8+PL2303TA+USB+TTL+to+RS232">PL2303TA based USB TTL to RS232</a>)</li>
<li>USB flash card or hard drive</li>
<li>USB 3G modem (in my case it&#8217;s <a href="http://www.pcmag.com/article2/0,2817,2367921,00.asp">Sierra AirCard 250U</a>)</li>
<li>USB Hub (external power source is highly recommended)</li>
<li>x86_64 Linux host system (i&#8217;m using Ubuntu 15.10 x86_64)</li>
<li>a lot of patience :)</li>
</ul>
<h2>Install OpenWRT using Image builder for brcm47xx/legacy</h2>
<p>On your host linux system, download and unpack <a href="https://wiki.openwrt.org/doc/howto/obtain.firmware.generate">OpenWRT image builder</a> packages:</p>
<pre><code class="bash" title="">bananos@ubby:$ wget "https://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/OpenWrt-ImageBuilder-15.05.1-brcm47xx-legacy.Linux-x86_64.tar.bz2"
bananos@ubby:$ tar -xvvf "OpenWrt-ImageBuilder-15.05.1-brcm47xx-legacy.Linux-x86_64.tar.bz2"
</code></pre>
<p>After that, we&#8217;re going to assemble our custom firmware out of pre-built packages. Image builder was created specifically to overcome the slowness and complexity of compiling OpenWRT from sources.</p>
<pre><code class="bash" title="">bananos@ubby:$ sudo apt-get install -y subversion build-essential libncurses5-dev zlib1g-dev gawk git ccache gettext libssl-dev xsltproc
bananos@ubby:$ cd "OpenWrt-ImageBuilder-15.05.1-brcm47xx-legacy.Linux-x86_64"
bananos@ubby:$ make image PROFILE="Broadcom-b43" PACKAGES="base-files libc libgcc busybox kmod-usb2 kmod-usb-ohci kmod-usb-uhci kmod-usb-storage kmod-fs-ext4 block-mount kmod-scsi-core -dropbear mtd uci -opkg netifd fstools swconfig wpad-mini nvram -otrx kmod-leds-gpio kmod-gpio-button-hotplug kmod-ledtrig-default-on kmod-ledtrig-timer kmod-ledtrig-netdev dnsmasq iptables -ip6tables ppp ppp-mod-pppoe kmod-nf-nathelper firewall odhcpd odhcp6c"

make[1]: Entering directory '/home/bananos/Projects/openwrt_dir320/image_builder/OpenWrt-ImageBuilder-15.05.1-brcm47xx-legacy.Linux-x86_64'
echo 'Building images for brcm47xx - Broadcom SoC, all Ethernet, BCM43xx WiFi (b43, default)'
Building images for brcm47xx - Broadcom SoC, all Ethernet, BCM43xx WiFi (b43, default)
echo 'Packages: base-files block-mount busybox dnsmasq firewall fstools iptables kernel kmod-b43 kmod-b43legacy kmod-fs-ext4 kmod-gpio-button-hotplug kmod-leds-gpio kmod-ledtrig-default-on kmod-ledtrig-netdev kmod-ledtrig-timer kmod-nf-nathelper kmod-scsi-core kmod-usb-ohci kmod-usb-storage kmod-usb-uhci kmod-usb2 libc libgcc mtd netifd nvram odhcp6c odhcpd ppp ppp-mod-pppoe swconfig uci wpad-mini'
Packages: base-files block-mount busybox dnsmasq firewall fstools iptables kernel kmod-b43 kmod-b43legacy kmod-fs-ext4 kmod-gpio-button-hotplug kmod-leds-gpio kmod-ledtrig-default-on kmod-ledtrig-netdev kmod-ledtrig-timer kmod-nf-nathelper kmod-scsi-core kmod-usb-ohci kmod-usb-storage kmod-usb-uhci kmod-usb2 libc libgcc mtd netifd nvram odhcp6c odhcpd ppp ppp-mod-pppoe swconfig uci wpad-mini
echo

rm -rf /home/bananos/Projects/openwrt_dir320/image_builder/OpenWrt-ImageBuilder-15.05.1-brcm47xx-legacy.Linux-x86_64/build_dir/target-mipsel_mips32_uClibc-0.9.33.2/root-brcm47xx
.....

</code></pre>
<p>Note the <code>-</code> symbol before some of the packages, this means that those must be excluded from resulting build. As a result our target image will have almost nothing except external usb support and bare linux kernel. This is due to really tiny capacity of the internal router storage(4Mb). In order to increase it we&#8217;ll be using external USB storage(extroot) which is covered in detail in the next sections of this article.</p>
<p>Make sure you have active connection to internet as Image Builder will download some packages from the online repository. At the end of the build, you should be able to find a bunch of prepackaged firmwares in <code>bin/</code> directory:</p>
<pre><code class="bash" title="">bananos@ubby:$ ls bin/brcm47xx/ | grep "asus"

openwrt-15.05.1-brcm47xx-legacy-asus-wl-300g-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-320gp-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-330ge-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v1-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v2-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-500w-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-520gu-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-550ge-squashfs.trx
openwrt-15.05.1-brcm47xx-legacy-asus-wl-hdd25-squashfs.trx
</code></pre>
<p>Our file of interest is <code>openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v2-squashfs.trx</code> since Asus WL500gp-V2 uses the same hardware as Dlink DIR-320 Rev A.</p>
<h2>Firmware Flashing</h2>
<p>There are a lot of firmware flashing instructions on the net, but we&#8217;ll be using the <a href="https://wiki.openwrt.org/doc/howto/generic.flashing.tftp">most generic and reliable via TFTP</a>. Create the following bash file named <code>flash.sh</code>:</p>
<pre><code class="bash" title="">#!/bin/bash
echo "=================================================================="
echo "This script will upload dd-wrt firmware (firmware.bin)"
echo "in the current directory to 192.168.0.1 "
echo "during the router's bootup. "
echo ""
echo "* Set your ethernet card's settings to: "
echo "     IP:      192.168.0.10 "
echo "     Mask:    255.255.255.0 "
echo "     Gateway: 192.168.0.1 "
echo "* Unplug the router's power cable. "
echo ""
echo "Press Ctrl+C to abort or any other key to continue... "

read

echo ""
echo "* Re-plug the router's power cable. "
echo ""
echo "=================================================================="
echo "Waiting for the router... Press Ctrl+C to abort. "
echo ""

try(){
ping -c 1 -w 1 192.168.0.1
}
try

while [ "$?" != "0" ] ;
do
try
done
echo "*** Start Flashing **** "
atftp --no-source-port-checking -p -l firmware.bin 192.168.0.1
echo "Firmware successfully loaded!"
</code></pre>
<p>The script&#8217;s usage instructions are pretty self-explanatory, but before using it we must do a few more things:</p>
<pre><code class="bash" title="">bananos@ubby:$ chmod +x flash.sh
bananos@ubby:$ cp bin/brcm47xx/openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v2-squashfs.trx firmware.bin
bananos@ubby:$ sudo apt-get install -y atftp atftpd
</code></pre>
<p>Assuming that your USB-to-Serial adapter was detected as <code>/dev/ttyUSB0</code>, let&#8217;s open serial terminal to be able to observe what is happening on the router in real time:</p>
<pre><code class="bash" title="">bananos@ubby:$ sudo bash -c "screen /dev/ttyUSB0 115200"
</code></pre>
<p>Now, prepare your ethernet network card settings and</p>
<ul>
<li>plug port #1 of your router to linux machine</li>
<li>run <code>./flash.sh</code> and press any key to see a lot of <code>connect: Network is unreachable</code> messages</li>
<li>plug router power cable and wait for the flashing process to finish</li>
</ul>
<p>In the serial console you&#8217;ll notice something similar to this:</p>
<pre><code class="" title="">Decompressing...........done

CFE version 1.0.37 for BCM947XX (32bit,SP,LE)
Build Date: Thu Jul 19 10:53:24 CST 2007 (root@redhat9)
Copyright (C) 2000,2001,2002,2003 Broadcom Corporation.

Initializing Arena
Initializing Devices.
Boot partition size = 262144(0x40000)
et0: Broadcom BCM47xx 10/100 Mbps Ethernet Controller 4.150.3.0
CPU type 0x29029: 240MHz
Total memory: 32768 KBytes

Total memory used by CFE:  0x80300000 - 0x803C0720 (788256)
Initialized Data:          0x80337730 - 0x8033AE50 (14112)
BSS Area:                  0x8033AE50 - 0x8033C720 (6352)
Local Heap:                0x8033C720 - 0x803A0720 (409600)
Stack Area:                0x803A0720 - 0x803C0720 (131072)
Text (code) segment:       0x80300000 - 0x80337730 (227120)
Boot area (physical):      0x003C1000 - 0x00401000
Relocation Factor:         I:00000000 - D:00000000

alpha bootcode ver 0.1.2
cmd = ifconfig eth0 -addr=192.168.0.1 -mask=255.255.255.0
We disable the arp for self.
We disable the arp for self.
Device eth0:  hwaddr 00-90-4C-C0-00-01, ipaddr 192.168.0.1, mask 255.255.255.0
        gateway not set, nameserver not set
cmd = go;
cmd = load -raw -addr=0x803c0720 -max=0x3a0000 :
Loader:raw Filesys:tftp Dev:eth0 File:: Options:(null)
Loading: entry point=803C0720
........... 3674112 bytes read
Entry at 0x803c0720
cmd = flash -noheader -mem -size=0x381000 0x803c0720 flash1.trx
Reading from 0x803c0720: Programming...done. 3674112 bytes written
Dest=80001000, source =803c0720, filename=flash1.trx
cmd = boot -raw -z -addr=0x80001000 -max=0x3a0000 flash0.os:
Loader:raw Filesys:raw Dev:flash0.os File: Options:(null)
Loading: entry point=80001000
.. 3712 bytes read
Entry at 0x80001000
Closing network.
Starting program at 0x80001000
[    0.000000] Linux version 3.18.23 (buildbot@builder1) (gcc version 4.8.3 (OpenWrt/Linaro GCC 4.8-2014.04 r48532) ) #1 Tue Mar 1 09:18:44 CET 2016
[    0.000000] CPU0 revision is: 00029029 (Broadcom BMIPS3300)
[    0.000000] bcm47xx: Using ssb bus
[    0.000000] ssb: Found chip with id 0x5354, rev 0x03 and package 0x00
[    0.000000] can not parse nvram name (null)boardnum(null) with value  got -22
[    0.000000] can not parse nvram name (null)rxpo2g(null) with value 0xfff8 got -34
[    0.000000] ssb: Sonics Silicon Backplane found at address 0x18000000
[    0.000000] Determined physical RAM map:
[    0.000000]  memory: 02000000 @ 00000000 (usable)
[    0.000000] Initrd not found or empty - disabling initrd
[    0.000000] Zone ranges:
[    0.000000]   Normal   [mem 0x00000000-0x01ffffff]
[    0.000000] Movable zone start for each node
[    0.000000] Early memory node ranges
[    0.000000]   node   0: [mem 0x00000000-0x01ffffff]
[    0.000000] Initmem setup node 0 [mem 0x00000000-0x01ffffff]
[    0.000000] Primary instruction cache 16kB, VIPT, 4-way, linesize 16 bytes.
[    0.000000] Primary data cache 16kB, 2-way, VIPT, cache aliases, linesize 16 bytes
[    0.000000] Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 8128
[    0.000000] Kernel command line:  noinitrd console=ttyS0,115200
[    0.000000] PID hash table entries: 128 (order: -3, 512 bytes)
[    0.000000] Dentry cache hash table entries: 4096 (order: 2, 16384 bytes)
[    0.000000] Inode-cache hash table entries: 2048 (order: 1, 8192 bytes)
[    0.000000] Memory: 28956K/32768K available (2605K kernel code, 103K rwdata, 316K rodata, 164K init, 267K bss, 3812K reserved)
[    0.000000] NR_IRQS:128
[    0.000000] MIPS: machine is Unknown Board
[    0.060000] Calibrating delay loop... 239.61 BogoMIPS (lpj=1198080)
[    0.070000] pid_max: default: 32768 minimum: 301
[    0.070000] Mount-cache hash table entries: 1024 (order: 0, 4096 bytes)
[    0.070000] Mountpoint-cache hash table entries: 1024 (order: 0, 4096 bytes)
[    0.080000] NET: Registered protocol family 16
[    0.100000] Switched to clocksource MIPS
[    0.110000] NET: Registered protocol family 2
[    0.110000] TCP established hash table entries: 1024 (order: 0, 4096 bytes)
[    0.110000] TCP bind hash table entries: 1024 (order: 0, 4096 bytes)
[    0.110000] TCP: Hash tables configured (established 1024 bind 1024)
[    0.110000] TCP: reno registered
[    0.110000] UDP hash table entries: 256 (order: 0, 4096 bytes)
[    0.110000] UDP-Lite hash table entries: 256 (order: 0, 4096 bytes)
[    0.110000] NET: Registered protocol family 1
[    0.110000] futex hash table entries: 256 (order: -1, 3072 bytes)
[    0.120000] squashfs: version 4.0 (2009/01/31) Phillip Lougher
[    0.120000] jffs2: version 2.2 (NAND) (SUMMARY) (LZMA) (RTIME) (CMODE_PRIORITY) (c) 2001-2006 Red Hat, Inc.
[    0.120000] msgmni has been set to 56
[    0.120000] io scheduler noop registered
[    0.120000] io scheduler deadline registered (default)
[    0.120000] Serial: 8250/16550 driver, 16 ports, IRQ sharing enabled
[    0.130000] console [ttyS0] disabled
[    0.150000] serial8250.0: ttyS0 at MMIO 0xb8000300 (irq = 3, base_baud = 1562500) is a U6_16550A
[    0.450000] console [ttyS0] enabled
[    0.470000] serial8250.0: ttyS1 at MMIO 0xb8000400 (irq = 3, base_baud = 1562500) is a U6_16550A
[    0.490000] physmap platform flash device: 02000001 at 1c000000
[    0.490000] physmap-flash.0: Found 1 x16 devices at 0x0 in 8-bit bank. Manufacturer ID 0x000001 Chip ID 0x0000f6
[    0.500000] Amd/Fujitsu Extended Query Table at 0x0040
[    0.510000]   Amd/Fujitsu Extended Query version 1.1.
[    0.510000] physmap-flash.0: Swapping erase regions for top-boot CFI table.
[    0.520000] number of CFI chips: 1
[    0.530000] 6 bcm47xxpart partitions found on MTD device physmap-flash.0
[    0.540000] Creating 6 MTD partitions on "physmap-flash.0":
[    0.540000] 0x000000000000-0x000000040000 : "boot"
[    0.550000] 0x000000040000-0x0000003f0000 : "firmware"
[    0.560000] 0x00000004001c-0x00000004090c : "loader"
[    0.570000] 0x00000004090c-0x000000146000 : "linux"
[    0.580000] 0x000000146000-0x0000003f0000 : "rootfs"
[    0.580000] mtd: device 4 (rootfs) set to be root filesystem
[    0.590000] 1 squashfs-split partitions found on MTD device rootfs
[    0.600000] 0x000000380000-0x0000003f0000 : "rootfs_data"
[    0.600000] 0x0000003f0000-0x000000400000 : "nvram"
[    0.710000] libphy: Fixed MDIO Bus: probed
[    0.710000] b44: Broadcom 44xx/47xx 10/100 PCI ethernet driver version 2.0
[    0.730000] libphy: b44_eth_mii: probed
[    0.850000] b53_common: found switch: BCM5325, rev 0
[    0.860000] b44 ssb0:0: attached PHY driver [Broadcom B53 (1)] (mii_bus:phy_addr=1:1e)
[    0.870000] b44 ssb0:0 eth0: Broadcom 44xx/47xx 10/100 PCI ethernet driver 00:90:4c:c0:00:01
[    0.880000] bcm47xx-wdt bcm47xx-wdt.0: BCM47xx Watchdog Timer enabled (30 seconds, Software Timer)
[    0.890000] GPIO_WDT: failed to register misc device
[    0.890000] TCP: cubic registered
[    0.890000] NET: Registered protocol family 17
[    0.900000] bridge: automatic filtering via arp/ip/ip6tables has been deprecated. Update your scripts to load br_netfilter if you need this.
[    0.910000] Bridge firewalling registered
[    0.920000] 8021q: 802.1Q VLAN Support v1.8
[    0.940000] VFS: Mounted root (squashfs filesystem) readonly on device 31:4.
[    0.950000] Freeing unused kernel memory: 164K (802f7000 - 80320000)
[    2.620000] init: Console is alive
[    2.630000] init: - watchdog -
[    5.430000] usbcore: registered new interface driver usbfs
[    5.430000] usbcore: registered new interface driver hub
[    5.440000] usbcore: registered new device driver usb
[    5.640000] SCSI subsystem initialized
[    5.670000] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver
[    5.680000] ehci-platform: EHCI generic platform driver
[    5.680000] ehci-platform ehci-platform.0: EHCI Host Controller
[    5.690000] ehci-platform ehci-platform.0: new USB bus registered, assigned bus number 1
[    5.700000] ehci-platform ehci-platform.0: irq 6, io mem 0x18003800
[    5.730000] ehci-platform ehci-platform.0: USB 2.0 started, EHCI 1.00
[    5.730000] hub 1-0:1.0: USB hub found
[    5.740000] hub 1-0:1.0: 2 ports detected
[    5.750000] ohci_hcd: USB 1.1 'Open' Host Controller (OHCI) Driver
[    5.760000] ohci-platform: OHCI generic platform driver
[    5.770000] ohci-platform ohci-platform.0: Generic Platform OHCI controller
[    5.780000] ohci-platform ohci-platform.0: new USB bus registered, assigned bus number 2
[    5.790000] ohci-platform ohci-platform.0: irq 6, io mem 0x18003000
[    5.850000] hub 2-0:1.0: USB hub found
[    5.860000] hub 2-0:1.0: 2 ports detected
[    5.870000] uhci_hcd: USB Universal Host Controller Interface driver
[    5.890000] usbcore: registered new interface driver usb-storage
[    6.680000] init: - preinit -
[    7.170000] b44 ssb0:0 eth0: Link is up at 100 Mbps, half duplex
[    7.180000] b44 ssb0:0 eth0: Flow control is off for TX and off for RX
[    7.460000] random: mktemp urandom read with 11 bits of entropy available
Press the [f] key and hit [enter] to enter failsafe mode
Press the [1], [2], [3] or [4] key and hit [enter] to select the debug level
[    8.980000] b44 ssb0:0 eth0: Link is Up - 100Mbps/Full - flow control off
[   11.010000] mount_root: loading kmods from internal overlay
[   11.380000] block: attempting to load /etc/config/fstab
[   11.390000] block: unable to load configuration (fstab: Entry not found)
[   11.400000] block: no usable configuration
[   11.400000] mount_root: jffs2 not ready yet, using temporary tmpfs overlay
[   11.460000] b44 ssb0:0 eth0: powering down PHY
[   11.490000] procd: - early -
[   11.500000] procd: - watchdog -
[   12.000000] b44 ssb0:0 eth0: Link is Down
[   12.410000] procd: - ubus -
[   13.430000] procd: - init -
Please press Enter to activate this console.
[   17.510000] NET: Registered protocol family 10
[   17.530000] Loading modules backported from Linux version master-2015-03-09-0-g141f155
[   17.540000] Backport generated by backports.git backports-20150129-0-gdd4a670
[   17.560000] nf_conntrack version 0.5.0 (455 buckets, 1820 max)
[   17.670000] xt_time: kernel timezone is -0000
[   17.730000] cfg80211: Calling CRDA to update world regulatory domain
[   17.740000] ip_tables: (C) 2000-2006 Netfilter Core Team
[   17.770000] cfg80211: World regulatory domain updated:
[   17.770000] cfg80211:  DFS Master region: unset
[   17.780000] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)
[   17.790000] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)
[   17.800000] cfg80211:   (2457000 KHz - 2482000 KHz @ 20000 KHz, 92000 KHz AUTO), (N/A, 2000 mBm), (N/A)
[   17.810000] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (N/A, 2000 mBm), (N/A)
[   17.820000] cfg80211:   (5170000 KHz - 5250000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (N/A)
[   17.830000] cfg80211:   (5250000 KHz - 5330000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (0 s)
[   17.840000] cfg80211:   (5490000 KHz - 5730000 KHz @ 160000 KHz), (N/A, 2000 mBm), (0 s)
[   17.840000] cfg80211:   (5735000 KHz - 5835000 KHz @ 80000 KHz), (N/A, 2000 mBm), (N/A)
[   17.850000] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[   18.230000] PPP generic driver version 2.4.2
[   18.240000] NET: Registered protocol family 24
[   18.410000] b43-phy0: Broadcom 5354 WLAN found (core revision 13)
[   18.440000] b43-phy0: Found PHY: Analog 6, Type 5 (LP), Revision 0
[   18.450000] b43-phy0: Found Radio: Manuf 0x17F, ID 0x2062, Revision 1, Version 0
[   18.470000] Broadcom 43xx driver loaded [ Features: PNL ]
[   18.550000] Broadcom 43xx-legacy driver loaded [ Features: PLD ]
[   26.610000] b44 ssb0:0 eth0: Link is up at 100 Mbps, full duplex
[   26.610000] b44 ssb0:0 eth0: Flow control is off for TX and off for RX
[   28.030000] b44 ssb0:0 eth0: Link is Up - 100Mbps/Full - flow control off
[   31.430000] jffs2_scan_eraseblock(): End of filesystem marker found at 0x0
[   31.450000] jffs2_build_filesystem(): unlocking the mtd device... done.
[   31.450000] jffs2_build_filesystem(): erasing all blocks after the end marker... ^[[A^[[A
[   34.450000] b44 ssb0:0 eth0: powering down PHY
[   34.530000] b44 ssb0:0 eth0: Link is up at 100 Mbps, full duplex
[   34.540000] b44 ssb0:0 eth0: Flow control is off for TX and off for RX
[   34.580000] device eth0.1 entered promiscuous mode
[   34.580000] device eth0 entered promiscuous mode
[   34.600000] br-lan: port 1(eth0.1) entered forwarding state
[   34.610000] br-lan: port 1(eth0.1) entered forwarding state
[   35.830000] done.
[   35.830000] jffs2: notice: (845) jffs2_build_xattr_subsystem: complete building xattr subsystem, 0 of xdatum (0 unchecked, 0 orphan) and 0 of xref (0 dead, 0 orphan) found.
[   36.610000] br-lan: port 1(eth0.1) entered forwarding state
[   80.480000] random: nonblocking pool is initialized

BusyBox v1.23.2 (2016-03-01 08:53:11 CET) built-in shell (ash)

  _______                     ________        __
 |       |.-----.-----.-----.|  |  |  |.----.|  |_
 |   -   ||  _  |  -__|     ||  |  |  ||   _||   _|
 |_______||   __|_____|__|__||________||__|  |____|
          |__| W I R E L E S S   F R E E D O M
 -----------------------------------------------------
 CHAOS CALMER (15.05.1, r48532)
 -----------------------------------------------------
  * 1 1/2 oz Gin            Shake with a glassful
  * 1/4 oz Triple Sec       of broken ice and pour
  * 3/4 oz Lime Juice       unstrained into a goblet.
  * 1 1/2 oz Orange Juice
  * 1 tsp. Grenadine Syrup
 -----------------------------------------------------
root@OpenWrt:/#

</code></pre>
<p>After successful flash procedure, reboot your router by powering it off and setting your ethernet network card back to DHCP (that&#8217;s necessary because the default router DHCP server assigns addresses in <code>192.168.1.XXX</code> subnet, which is different from <code>192.168.0.XXX</code> which we used for flashing purposes)</p>
<p>Turn on the device once again and wait until wired connection with your host system establishes. After that, you may happily telnet into the router:</p>
<pre><code class="bash" title="">bananos@ubby:$ telnet 192.168.1.1
Trying 192.168.1.1...
Connected to 192.168.1.1.
Escape character is '^]'.
 === IMPORTANT ============================
  Use 'passwd' to set your login password
  this will disable telnet and enable SSH
 ------------------------------------------

BusyBox v1.23.2 (2016-03-01 08:53:11 CET) built-in shell (ash)

.....
</code></pre>
<p>Congrats! The first, most important step is completed. In the next section we&#8217;ll configure <a href="https://wiki.openwrt.org/doc/howto/extroot">extroot</a> to be able to install additional OpenWrt packages such as LuCI and various kernel modules.</p>
<h2>Setting up extroot</h2>
<p>Connect your USB drive to linux host system. The first thing we&#8217;re going to do is partitioning. Assuming that your newly inserted disk is <code>/dev/sdb</code> I would suggest somewhat similar to this:</p>
<pre><code class="bash" title="">bananos@ubby:$ sudo fdisk -l /dev/sdb
Disk /dev/sdb: 28 GiB, 30005821440 bytes, 58605120 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xa58948b4

Device     Boot   Start      End  Sectors   Size Id Type
/dev/sdb1            63  2008124  2008062 980.5M 82 Linux swap / Solaris
/dev/sdb2       2008125  6024374  4016250   1.9G 83 Linux
/dev/sdb3       6024375 58605119 52580745  25.1G 83 Linux
</code></pre>
<p>In my case, I&#8217;m using 1.8 inch TOSHIBA MK3008GAL hard drive. To make partitioning table similar to above mentioned you may use GUI tool called <code>GParted</code> or use plain <code>fdisk</code>. Primary partition usage is as follows:</p>
<ul>
<li><code>/dev/sdb1</code> is for swapping purposes due to a low (32Mb) amount of RAM</li>
<li><code>/dev/sdb2</code> is for root filesystem (rootfs <code>/</code>)</li>
<li><code>/dev/sdb3</code> is for home directory (<code>/home</code>)</li>
</ul>
<p>After partitioning, format <code>rootfs</code> and <code>/home</code> into ext4 filesystems:</p>
<pre><code class="" title="">bananos@ubby:$ sudo umount /dev/sdb2
bananos@ubby:$ sudo mkfs.ext4 /dev/sdb2
mke2fs 1.42.12 (29-Aug-2014)
Creating filesystem with 502031 4k blocks and 125696 inodes
Filesystem UUID: 69b17872-9486-4113-8d9f-59a5e4221027
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912

Allocating group tables: done
Writing inode tables: done
Creating journal (8192 blocks): done
Writing superblocks and filesystem accounting information: done

bananos@ubby:$ sudo umount /dev/sdb3
bananos@ubby:$ sudo mkfs.ext4 /dev/sdb3

....

bananos@ubby:$ sudo mkswap /dev/sdb1
Setting up swapspace version 1, size = 980.5 MiB (1028120576 bytes)
no label, UUID=457a57b6-aae0-410a-8832-4e182e15e04b

</code></pre>
<p>Now, connect USB drive to your router, turn it on, and telnet once again:</p>
<pre><code class="bash" title="">root@OpenWrt:/# logread | grep "sda"
Tue Mar  1 08:15:13 2016 kern.notice kernel: [    7.290000] sd 0:0:0:0: [sda] 58605120 512-byte logical blocks: (30.0 GB/27.9 GiB)
Tue Mar  1 08:15:13 2016 kern.notice kernel: [    7.320000] sd 0:0:0:0: [sda] Write Protect is off
Tue Mar  1 08:15:13 2016 kern.debug kernel: [    7.320000] sd 0:0:0:0: [sda] Mode Sense: 03 00 00 00
Tue Mar  1 08:15:13 2016 kern.err kernel: [    7.330000] sd 0:0:0:0: [sda] No Caching mode page found
Tue Mar  1 08:15:13 2016 kern.err kernel: [    7.330000] sd 0:0:0:0: [sda] Assuming drive cache: write through
Tue Mar  1 08:15:13 2016 kern.info kernel: [    7.400000]  sda: sda1 sda2 sda3
Tue Mar  1 08:15:13 2016 kern.notice kernel: [    7.440000] sd 0:0:0:0: [sda] Attached SCSI disk
</code></pre>
<p>We&#8217;ve just used <code>logread</code> to make sure that hard drive was successfully detected by kernel. Now, let&#8217;s proceed to creating external rootfs:</p>
<pre><code class="bash" title="">root@OpenWrt:/# ls -l /dev/sda
brw-r--r--    1 root     root        8,   0 Jan  1  1970 /dev/sda
root@OpenWrt:/# block detect
config 'global'
        option  anon_swap       '0'
        option  anon_mount      '0'
        option  auto_swap       '1'
        option  auto_mount      '1'
        option  delay_root      '5'
        option  check_fs        '0'

config 'swap'
        option  uuid    '457a57b6-aae0-410a-8832-4e182e15e04b'
        option  enabled '0'

config 'mount'
        option  target  '/mnt/sda2'
        option  uuid    '69b17872-9486-4113-8d9f-59a5e4221027'
        option  enabled '0'

config 'mount'
        option  target  '/mnt/sda3'
        option  uuid    '37582519-c560-45d3-9a4e-9a95d255b33a'
        option  enabled '0'
</code></pre>
<p>We&#8217;ve just seen that usb hard drive is present at <code>/dev/sda</code> and has 3 partitions. Next, we&#8217;ll create a so-called <a href="https://wiki.openwrt.org/doc/howto/extroot/extroot.theory">pivot-overlay</a>:</p>
<pre><code class="bash" title="">root@OpenWrt:/# mount /dev/sda2 /mnt ; tar -C /overlay -cvf - . | tar -C /mnt -xf - ; umount /mnt
./
./.fs_state
./work/
./work/work/
./upper/
./upper/etc/
./upper/etc/uci-defaults/
./upper/etc/uci-defaults/11_migrate-sysctl
./upper/etc/uci-defaults/03_network_migration
./upper/etc/uci-defaults/odhcpd.defaults
./upper/etc/uci-defaults/10_migrate-shadow
./upper/etc/uci-defaults/10-fstab
./upper/etc/uci-defaults/12_network-generate-ula
./upper/etc/uci-defaults/09_fix_crc
./upper/etc/config/
./upper/etc/config/dhcp
./upper/etc/config/fstab
./upper/etc/config/firewall
./upper/etc/config/network
./upper/etc/config/system
./upper/etc/config/wireless
./upper/etc/ethers
./upper/etc/dnsmasq.time
</code></pre>
<p>The above mentioned command will mount <code>/dev/sda2</code> as <code>/mnt</code>, then will copy everything from <code>/overlay</code> to <code>/mnt</code> and unmount partition. Now, create <code>fstab</code> template:</p>
<pre><code class="bash" title="">root@OpenWrt:/# block detect &gt; /etc/config/fstab ; vi /etc/config/fstab
</code></pre>
<p>After editing your <code>fstab</code> file it should look like following:</p>
<pre><code class="" title="">config 'global'
        option  anon_swap       '0'
        option  anon_mount      '0'
        option  auto_swap       '1'
        option  auto_mount      '1'
        option  delay_root      '5'
        option  check_fs        '1'

config 'swap'
        option  enabled '1'
        option  device '/dev/sda1'

config 'mount'
        option  target  '/overlay'
        option  enabled '1'
        option  device  '/dev/sda2'
        option  fstype  'ext4'
        option  options 'rw,relatime,data=ordered,async,errors=remount-ro'
        option  enabled_fsck '1'

config 'mount'
        option  target  '/home'
        option  enabled '1'
        option  device '/dev/sda3'
        option  fstype  'ext4'
        option  options 'rw,relatime,data=ordered,async,errors=remount-ro'
        option  enabled_fsck '1'
</code></pre>
<p>Don&#8217;t forget to create <code>/home</code> directory by entering <code>mkdir -p /home</code>! Now, reboot your router and check that everything was mounted correctly:</p>
<pre><code class="bash" title="">root@OpenWrt:/# df -h
Filesystem                Size      Used Available Use% Mounted on
rootfs                    1.9G      2.9M      1.7G   0% /
/dev/root                 2.3M      2.3M         0 100% /rom
tmpfs                    14.2M     44.0K     14.2M   0% /tmp
/dev/sda2                 1.9G      2.9M      1.7G   0% /overlay
overlayfs:/overlay        1.9G      2.9M      1.7G   0% /
tmpfs                   512.0K         0    512.0K   0% /dev
/dev/sda3                24.6G     43.9M     23.2G   0% /home

root@OpenWrt:/# swapon -s
Filename                                Type            Size    Used    Priority
/dev/sda1                               partition       1004024 0       -1
</code></pre>
<p>We can see here, that rootfs(<code>/</code>) partition now has 1.7G of free space, and there&#8217;s almost 998M of swap. That&#8217;s it! External root filesystem is ready to use. In the next step, we&#8217;ll install <code>opkg</code> package manager, to be able to do something useful with our fresh linux system.</p>
<h2>Installation of package manager (opkg)</h2>
<p>A bare linux system is of no use if we&#8217;re not able to install additional software. That&#8217;s what we&#8217;ll accomplish in this section. Since we don&#8217;t have access to internet(yet) from the router itself, we&#8217;ll download <code>opkg</code> binary package manually and install it on the working system.</p>
<p>As an additional option you may consider downloading all of the OpenWRT binary packages to newly prepared usb drive if you have plenty of free space. That&#8217;s very useful if there will be no access to internet from the router itself during spontaneous connection failures or maintenance periods.</p>
<p>Re-attach hard drive to linux host system and assuming that<br />
<code>/media/bananos/69b17872-9486-4113-8d9f-59a5e4221027</code> is your <code>/home</code> directory mentioned above, download all packages:</p>
<pre><code class="bash" title="">root@ubby:$ cd `/media/bananos/69b17872-9486-4113-8d9f-59a5e4221027` &amp;&amp; mkdir repo &amp;&amp; cd repo
root@ubby:$ wget -r --no-parent --reject "index.html*" "https://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/"
......

FINISHED --2016-03-31 16:48:54--
Total wall clock time: 7m 23s
Downloaded: 4508 files, 307M in 2m 9s (2.39 MB/s)
</code></pre>
<p>This will download all packages from <code>https://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/</code> preserving directory structure. Let&#8217;s make it more clean:</p>
<pre><code class="bash" title="">root@ubby:$ mv downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/* .
root@ubby:$ rm -rf downloads.openwrt.org/
root@ubby:# ls
base luci  management  packages  routing  telephony
</code></pre>
<p>Now, let&#8217;s install <a href="https://wiki.openwrt.org/doc/techref/opkg">opkg</a> manager by copying corresponding package to rootfs:</p>
<pre><code class="bash" title="">root@ubby:$ cp base/opkg_9c97d5ecd795709c8584e972bfdf3aee3a5b846d-9_brcm47xx.ipk /media/bananos/37582519-c560-45d3-9a4e-9a95d255b33a/opkg.ipk
root@ubby:$ cd /media/bananos/37582519-c560-45d3-9a4e-9a95d255b33a/

root@ubby:$ 7z x opkg.ipk

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,2 CPUs)

Processing archive: opkg.ipk
Extracting  opkg
Everything is Ok
Size:       71680
Compressed: 64546

root@ubby:$ tar -xvf opkg
./debian-binary
./data.tar.gz
./control.tar.gz

root@ubby:$ rm control.tar.gz opkg.ipg debian-binary rm opkg
</code></pre>
<p>Unplug USB-hdd from host system and replug it back to router, run <code>telnet</code> and check that <code>data.tar.gz</code> is at <code>/overlay</code>:</p>
<pre><code class="bash" title="">root@OpenWrt:/# ls /overlay/
data.tar.gz  etc          lost+found   upper        work
root@OpenWrt:/# mv /overlay/data.tar.gz /
root@OpenWrt:/# tar -xzvf data.tar.gz
./
./lib/
./lib/upgrade/
./lib/upgrade/keep.d/
./lib/upgrade/keep.d/opkg
./bin/
./bin/opkg
./usr/
./usr/lib/
./usr/lib/opkg/
./usr/sbin/
./usr/sbin/opkg-key
./etc/
./etc/uci-defaults/
./etc/uci-defaults/20_migrate-feeds
./etc/opkg/
./etc/opkg/customfeeds.conf
./etc/opkg/distfeeds.conf
./etc/opkg.conf
</code></pre>
<p>If everything was correct and you extracted tar package directly to <code>/</code> then it is possible to run <code>opkg</code> itself:</p>
<pre><code class="bash" title="">root@OpenWrt:/# opkg --version
opkg version 0.1.8
</code></pre>
<p>Now, if you have working internet connection it is possible to install additional OpenWRT packages like LuCI, but we&#8217;re going to leverage our offline repo we&#8217;ve created above. Open <code>/etc/opkg/distfeeds.conf</code> and create following file contents:</p>
<pre><code class="" title="">#src/gz chaos_calmer_base http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/base
#src/gz chaos_calmer_luci http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/luci
#src/gz chaos_calmer_packages http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/packages
#src/gz chaos_calmer_routing http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/routing
#src/gz chaos_calmer_telephony http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/telephony
#src/gz chaos_calmer_management http://downloads.openwrt.org/chaos_calmer/15.05.1/brcm47xx/legacy/packages/management

src/gz chaos_calmer_base file:///home/repo/base
src/gz chaos_calmer_luci file:///home/repo/luci
src/gz chaos_calmer_packages file:///home/repo/packages
src/gz chaos_calmer_routing file:///home/repo/routing
src/gz chaos_calmer_telephony file:///home/repo/telephony
src/gz chaos_calmer_management file:///home/repo/management
</code></pre>
<p>run update procedure:</p>
<pre><code class="bash" title="">root@OpenWrt:/# opkg update
Downloading file:///home/repo/base/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_base.
Downloading file:///home/repo/base/Packages.sig.
Signature check passed.
Downloading file:///home/repo/luci/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_luci.
Downloading file:///home/repo/luci/Packages.sig.
Signature check passed.
Downloading file:///home/repo/packages/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_packages.
Downloading file:///home/repo/packages/Packages.sig.
Signature check passed.
Downloading file:///home/repo/routing/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_routing.
Downloading file:///home/repo/routing/Packages.sig.
Signature check passed.
Downloading file:///home/repo/telephony/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_telephony.
Downloading file:///home/repo/telephony/Packages.sig.
Signature check passed.
Downloading file:///home/repo/management/Packages.gz.
Updated list of available packages in /var/opkg-lists/chaos_calmer_management.
Downloading file:///home/repo/management/Packages.sig.
Signature check passed.
</code></pre>
<p>Now, it is possible to install any additional software we like. For example, let&#8217;s install <code>nano</code> text editor:</p>
<pre><code class="bash" title="">root@OpenWrt:/# opkg install nano
Installing nano (2.4.1-1) to root...
Downloading file:///home/repo/packages/nano_2.4.1-1_brcm47xx.ipk.
Installing libncurses (5.9-2) to root...
Downloading file:///home/repo/base/libncurses_5.9-2_brcm47xx.ipk.
Installing terminfo (5.9-2) to root...
Downloading file:///home/repo/base/terminfo_5.9-2_brcm47xx.ipk.
Configuring terminfo.
Configuring libncurses.
Configuring nano.
</code></pre>
<h2>Make sure internet works</h2>
<p>If you have access to an internet via LAN cable (i.e. you do have another router running DHCP in your network with internet access), plug your DIR-320 WAN port into your network. Make sure, it gets dynamic IP:</p>
<pre><code class="bash" title="">root@OpenWrt:/# ifconfig

br-lan    Link encap:Ethernet  HWaddr 00:90:4C:C0:00:01
          inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fd47:5a3c:26b2::1/60 Scope:Global
          inet6 addr: fe80::290:4cff:fec0:1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:37 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:3926 (3.8 KiB)

eth0.2    Link encap:Ethernet  HWaddr 00:90:4C:C0:00:01
          inet addr:192.168.0.194  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::290:4cff:fec0:1/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:223 errors:0 dropped:0 overruns:0 frame:0
          TX packets:104 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:50169 (48.9 KiB)  TX bytes:9778 (9.5 KiB)
</code></pre>
<p>Make sure that your existing network uses different subnet. By default, OpenWRT is configured to use <code>192.168.1.X</code> subnet, so you should use something like <code>192.168.0.X</code> or <code>192.168.2.X</code>. Verify that you&#8217;re able to download content from the internet:</p>
<pre><code class="bash" title="">root@OpenWrt:/# wget http://httpbin.org/ip -O /dev/null
Connecting to httpbin.org (54.175.219.8:80)
null                 100% |*******************************|    32   0:00:00 ETA
</code></pre>
<p>If you&#8217;re not able to get any content outside your network, it is most likely a problem with firewall. One of the symptoms of this problem is that when you issue <code>ping</code> command, there will be following output <code>ping: sendmsg: Operation not permitted</code>.</p>
<p>To allow all traffic in any direction(don&#8217;t do this in production environment!), do the following:</p>
<pre><code class="bash" title="">root@OpenWrt:/# echo "iptables -P INPUT ACCEPT" &gt;&gt; /etc/firewall.user
root@OpenWrt:/# echo "iptables -P OUTPUT ACCEPT" &gt;&gt; /etc/firewall.user
root@OpenWrt:/# echo "iptables -P FORWARD ACCEPT" &gt;&gt; /etc/firewall.user
root@OpenWrt:/# /etc/init.d/firewall restart
</code></pre>
<h2>LuCI installation</h2>
<p><a href="https://wiki.openwrt.org/doc/techref/luci">LuCI</a> is a web-based GUI for managing OpenWRT. A lot of essential configuration which is pretty cumbersome to do via command-line could be easily made through LuCI.</p>
<p>Before installing LuCI packages I would strongly suggest setting up <code>kmod-zram</code> and <code>zram-swap</code> packages if you&#8217;re not using external HDD swap, but instead rely on slow, error-prone flash memory. <a href="https://en.wikipedia.org/wiki/Zram">Zram</a> is a special linux kernel module which makes part of your RAM compressed and behave like swap.</p>
<p>Now, let&#8217;s proceed:</p>
<pre><code class="bash" title="">root@OpenWrt:/# opkg update &amp;&amp; opkg install --force-overwrite wget ca-certificates coreutils dropbear
root@OpenWrt:/# opkg install ip fdisk usbutils screen htop
root@OpenWrt:/# opkg install luci luci-proto-3g luci-proto-ipv6 luci-proto-openconnect luci-proto-ppp luci-proto-relay
</code></pre>
<p>After successfull installation of the above mentioned packages, reboot and plug your linux host into one of the 4 LAN ports of the router. Since LuCI is not yet configured, it is not possible to access it via WAN, therefore we&#8217;re going to setup it from the internal router network. Open up your favorite browser and go to <code>http://192.168.1.1/cgi-bin/luci</code></p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_luci_login_page.png"><img src="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_luci_login_page.png" alt="" title="openwrt_luci_login_page" width="703" height="547" class="aligncenter size-full wp-image-510" /></a></p>
<p>From now on, you may fully configure your router by setting up root password, enabling Wi-Fi, etc.</p>
<h2>3g/CDMA modem configuration</h2>
<p>Now, the most interesting part &#8212; how do we connect external CDMA modem to the router and make sure it will function as a WAN interface for LAN clients? At the time of this writing, I had in my hands a used <a href="http://www.amazon.com/Sierra-Wireless-Aircard-250U4G-Silver/dp/B009ZY10GK">Sierra AirCard 250U</a>:</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_sierra_wireless_250u.jpg"><img src="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_sierra_wireless_250u.jpg" alt="" title="openwrt_sierra_wireless_250u" width="457" height="329" class="aligncenter size-full wp-image-512" /></a></p>
<p>In this part of the article, we&#8217;re going to setup it to act as an external WAN interface. First off, disconnect ethernet cable from router&#8217;s WAN port and connect modem. Make sure you&#8217;re using USB-hub with external power supply, since 3G modems may drain a lot of current from single USB port and you might experience a lot of weird issues.</p>
<p>Open up terminal console using <code>ssh</code> (telnet should be already disabled if you&#8217;ve configured router&#8217;s root password):</p>
<pre><code class="bash" title="">bananos@ubby:$ ssh  root@192.168.1.1
Warning: Permanently added '192.168.1.1' (RSA) to the list of known hosts.
root@192.168.1.1's password:
</code></pre>
<p>When CDMA modem is powered on, it is possible to see it in the list of connected usb devices:</p>
<pre><code class="bash" title="">root@OpenWrt:~# lsusb
Bus 001 Device 007: ID 1199:0301 Sierra Wireless, Inc.
Bus 001 Device 008: ID 198f:0220 Beceem Communications Inc. BCSM250 WiMAX Adapter
Bus 001 Device 004: ID 0424:2512 Standard Microsystems Corp. USB 2.0 Hub
Bus 001 Device 003: ID 05ac:0221 Apple, Inc. Aluminum Keyboard (ISO)
Bus 001 Device 005: ID 067b:2506 Prolific Technology, Inc. Kaser 8gB micro hard drive
Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 001 Device 002: ID 05ac:1006 Apple, Inc. Hub in Aluminum Keyboard
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
</code></pre>
<p>In this example I&#8217;m using Apple Keyboard as USB hub :)  Aricard 250U may actually work in CDMA/WiMax mode, and is detected as two separate devices <code>Sierra Wireless, Inc.</code> and <code>Beceem Communications Inc. BCSM250 WiMAX Adapter</code>. Now, let&#8217;s search for Sierra support in software packages:</p>
<pre><code class="bash" title="">root@OpenWrt:~# opkg update
root@OpenWrt:~# opkg list | grep sierra
kmod-usb-net-sierrawireless - 3.18.23-1 - Kernel support for Sierra Wireless devices
kmod-usb-serial-sierrawireless - 3.18.23-1 - Kernel support for Sierra Wireless devices
</code></pre>
<p>Luckily, there is kernel support for Sierra devices and we&#8217;re going to leverage that! This is exactly the case where modern linux kernel shines in all its beauty. On top of this kernel modules we need to install some other generic stuff:</p>
<pre><code class="bash" title="">root@OpenWrt:~# opkg install kmod-usb-serial kmod-usb-serial-option kmod-usb-serial-wwan kmod-usb-serial-ipw
root@OpenWrt:~# opkg install comgt usb-modeswitch coreutils-stty
root@OpenWrt:~# opkg install kmod-usb-net-sierrawireless kmod-usb-serial-sierrawireless
root@OpenWrt:~# reboot
</code></pre>
<p>Make sure that sierra kernel support is functioning:</p>
<pre><code class="bash" title="">root@OpenWrt:~# lsmod | grep sierra
sierra                  6048  0
sierra_net              5600  0
usbnet                 15872  1 sierra_net
</code></pre>
<p>As this point, we have a serial interface to CDMA modem at <code>/dev/ttyUSB0</code>. Verify that modem responds to AT commands:</p>
<pre><code class="" title="">root@OpenWrt:~# gcom info -d /dev/ttyUSB0
##### Wireless WAN Modem Configuration #####
Product text:
====

Manufacturer: Sierra Wireless, Inc.
Model: AC250U Rev 2.0 (3)
Revision: p3012901,8815 [May 28 2010 14:42:39]
QCOM: SWI6085_FP.01.28
BOOT: SWI6085_PP.01.29.01 2010/05/28 18:13:46
APPL: SWI6085_PP.01.29.01 2010/05/28 18:13:46
USB VID: 0x1199 PID: 0x0301
ESN: 09612160827
0x60B98F3B
+GCAP: +CIS707-A, CIS-856, CIS-856-A, +MS, +ES, +DS, +FCLASS
SKU: 0x132BD1
OK
====
Manufacturer:           ERROR
IMEI and Serial Number: 09612160827
Manufacturer's Revision:
p3012901,8815 [May 28 2010 14:42:3
Hardware Revision:

Network Locked:

Customisation:

Band settings:          (
)
APN:

##### END #####
</code></pre>
<p>Now, switch to LuCI and go to <code>Network-&gt;Interfaces</code>. Stop <code>WAN6</code> unless you're going to use IPv6 and edit <code>WAN</code> interface.</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_add_new_3g_wan.png"><img src="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_add_new_3g_wan.png" alt="" title="openwrt_add_new_3g_wan"  width="900" class="aligncenter size-full wp-image-514" /></a></p>
<p>When editing existing <code>WAN</code> interface, change <code>Protocol</code> to <code>UMTS/GPRS/EV-DO</code>, click <code>Switch protocol</code> button and wait for additional parameters to appear:</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_cdma_connection_params.png"><img src="http://webapp.org.ua/wp-content/uploads/2016/04/openwrt_cdma_connection_params.png" alt="" title="openwrt_cdma_connection_params" width="649" height="711" class="aligncenter size-full wp-image-513" /></a></p>
<p>On this screen you should enter provider specific info (take a look at your contract/prepaid plan details). Since my modem is connected to <a href="http://intertelecom.ua">Ukraine's CDMA Intertelecom</a> my connection parameters are:</p>
<ul>
<li><code>Protocol</code>: UMTS/GPRS/EV-DO</li>
<li><code>Modem device</code>: /dev/ttyUSB0 (we've tested above that it actually responds to AT commands)</li>
<li><code>Service type</code>: CDMA/EV-DO</li>
<li><code>APN</code>: empty</li>
<li><code>PIN</code>: empty</li>
<li><code>PAP/CHAP username</code>: IT</li>
<li><code>PAP/CHAP password</code>: IT</li>
<li><code>Dial number</code>: #777</li>
</ul>
<p>Note, that your interface will now be named <code>3g-wan</code> and since there is a flag called <code>Bring up on boot</code> in the <code>Advanced tab</code> your CDMA connection will be established automatically on power up. To make sure that everything works, open up terminal once again:</p>
<pre><code class="bash" title="">root@OpenWrt:~# logread | grep -E "chat|ppp"
Tue Apr  5 19:38:31 2016 daemon.notice pppd[6810]: pppd 2.4.7 started by root, uid 0
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (BUSY)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (NO CARRIER)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (ERROR)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (NO DIAL TONE)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (NO ANSWER)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: abort on (DELAYED)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: report (CONNECT)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: timeout set to 10 seconds
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: send (AT^M)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: expect (OK)
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: AT^M^M
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: OK
Tue Apr  5 19:38:32 2016 local2.info chat[6821]:  -- got it
Tue Apr  5 19:38:32 2016 local2.info chat[6821]: send (ATZ^M)
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: timeout set to 30 seconds
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: expect (OK)
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: ^M
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: ATZ^M^M
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: OK
Tue Apr  5 19:38:33 2016 local2.info chat[6821]:  -- got it
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: send (ATDT#777^M)
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: expect (CONNECT)
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: ^M
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: ATDT#777^M^M
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: CONNECT
Tue Apr  5 19:38:33 2016 local2.info chat[6821]:  -- got it
Tue Apr  5 19:38:33 2016 local2.info chat[6821]: send (^M)
Tue Apr  5 19:38:33 2016 daemon.info pppd[6810]: Serial connection established.
Tue Apr  5 19:38:33 2016 daemon.info pppd[6810]: Using interface 3g-wan
Tue Apr  5 19:38:33 2016 kern.info kernel: [ 8554.840000] 3g-wan: renamed from ppp0
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: Connect: 3g-wan &lt; --&gt; /dev/ttyUSB0
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: PAP authentication succeeded
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: local  IP address 10.227.181.163
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: remote IP address 172.17.4.100
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: primary   DNS address 192.168.4.3
Tue Apr  5 19:38:33 2016 daemon.notice pppd[6810]: secondary DNS address 192.168.4.7
Tue Apr  5 20:08:32 2016 daemon.info pppd[6810]: LCP terminated by peer
Tue Apr  5 20:08:32 2016 daemon.info pppd[6810]: Connect time 30.0 minutes.
Tue Apr  5 20:08:32 2016 daemon.info pppd[6810]: Sent 826328 bytes, received 547992 bytes.
Tue Apr  5 20:08:33 2016 daemon.info pppd[6810]: Terminating on signal 15
Tue Apr  5 20:08:35 2016 daemon.notice pppd[6810]: Connection terminated.
Tue Apr  5 20:08:36 2016 daemon.notice pppd[6810]: Modem hangup
Tue Apr  5 20:08:36 2016 daemon.info pppd[6810]: Exit.
Tue Apr  5 20:08:37 2016 daemon.notice pppd[7884]: pppd 2.4.7 started by root, uid 0
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (BUSY)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (NO CARRIER)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (ERROR)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (NO DIAL TONE)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (NO ANSWER)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: abort on (DELAYED)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: report (CONNECT)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: timeout set to 10 seconds
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: send (AT^M)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: expect (OK)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: AT^M^M
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: OK
Tue Apr  5 20:08:38 2016 local2.info chat[7896]:  -- got it
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: send (ATZ^M)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: timeout set to 30 seconds
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: expect (OK)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: ^M
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: ATZ^M^M
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: OK
Tue Apr  5 20:08:38 2016 local2.info chat[7896]:  -- got it
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: send (ATDT#777^M)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: expect (CONNECT)
Tue Apr  5 20:08:38 2016 local2.info chat[7896]: ^M
Tue Apr  5 20:08:39 2016 local2.info chat[7896]: ATDT#777^M^M
Tue Apr  5 20:08:39 2016 local2.info chat[7896]: CONNECT
Tue Apr  5 20:08:39 2016 local2.info chat[7896]:  -- got it
Tue Apr  5 20:08:39 2016 local2.info chat[7896]: send (^M)
Tue Apr  5 20:08:39 2016 daemon.info pppd[7884]: Serial connection established.
</code></pre>
<p>These are the logs from <code>pppd</code> daemon and CHAT script, responsible for sending AT commands to modem. As you can see there may be random hangups, but the connection is automatically re-established which is very nice.</p>
<p>And when you enter <code>ifconfig</code> command you should see <code>3g-wan</code> interface too:</p>
<pre><code class="" title="">root@OpenWrt:~# ifconfig
3g-wan    Link encap:Point-to-Point Protocol
          inet addr:10.227.196.50  P-t-P:172.17.4.100  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:977 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2117 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:3
          RX bytes:529666 (517.2 KiB)  TX bytes:324250 (316.6 KiB)
</code></pre>
<p>In case you&#8217;re interested in diving deeper into how things work, I&#8217;d recommend looking at these files:</p>
<ul>
<li><code>/etc/config/network</code> contains network configuration</li>
<li><code>/lib/netifd/proto/3g.sh</code> shell logic responsible for running <code>pppd</code> daemon</li>
</ul>
<h2>Measuring signal strength</h2>
<p>The last problem you&#8217;ll probably stumble upon &#8212; is how to measure signal strength, especially if you&#8217;re setting up standalone solution at a remote location with a modem connected to an external antenna. This is usually accomplished by sending special <code>AT</code> command to modem. Note, however, that most software and examples over internet are targeted towards more popular GRPS/UMTS modems, and they will probably won&#8217;t work.</p>
<p>Before using serial protocol to communicate with modem, we must shutdown existing <code>3g-wan</code> connection, because otherwise we&#8217;ll get <code>cat: read error: Resource temporarily unavailable</code>:</p>
<pre><code class="bash" title="">root@OpenWrt:~# ifdown wan
</code></pre>
<p>Note, that <code>ifdown</code> won&#8217;t accept <code>3g-wan</code> as interface, but oddly enough the above command works. For now, let&#8217;s focus on how to send <code>AT</code> commands to modem:</p>
<ul>
<li>run <code>screen</code></li>
<li>open 2 consoles</li>
</ul>
<p>In the first console run <code>cat /dev/ttyUSB0</code> (this is a place to look for modem replies) and in the second run <code>echo -ne "at!status?\r\n" &gt; /dev/ttyUSB0</code>. Switch back consoles and you should see something like this:</p>
<pre><code class="bash" title="">root@OpenWrt:~# cat /dev/ttyUSB0
at!rssi?
-83

OK
</code></pre>
<p>A range from -60 dbm to -90 dBm is considered adequate. Using this special AT command you may now run it in a loop with small delay, observe signal strength in the second console and properly adjust external antenna. Also, there seems to be an unofficial OpenWRT package specifically for signal monitoring called <a href="http://dl.eko.one.pl/chaos_calmer/ar71xx/packages/3ginfo_20160223_all.ipk">3ginfo</a>, but I&#8217;ve not tried it and not sure if it works for CDMA/EVDO modems.</p>
<h2>TL;DR;</h2>
<p>Seriously, If you want to avoid all the hassle of setting up CDMA modem and OpenWRT, just buy yourself a device which combines WiFi router and 3g modem &#8212; <a href="https://en.wikipedia.org/wiki/MiFi">MiFi</a> will do just fine :)</p>
<p>Download <a href="/wp-content/uploads/2016/04/openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v2-squashfs.trx">openwrt-15.05.1-brcm47xx-legacy-asus-wl-500gp-v2-squashfs.trx</a>  (MD5: <strong>420e24e9a042c01585d818c14afa11d3</strong>)</p>
<h2>Links</h2>
<ul>
<li><a href="https://wiki.openwrt.org/doc/recipes/3gdongle">OpenWRT 3g dongle howto</a></li>
<li><a href="http://ubuntuguide.org/wiki/Ubuntu:Gutsy#Using_USB_EVDO_Internet_modem">Using USB EVDO Internet_modem</a></li>
<li><a href="http://wiki.villagetelco.org/Using_a_3G_USB_Modem">Using a 3G USB Modem</a></li>
<li><a href="http://www.daveconroy.com/verified-raspberry-pi-and-3g-sierra-wireless-250u-aircard-from-sprint/">Raspberry pi and 3g sierra wireless 250u</a></li>
<li><a href="http://kb.netgear.com/app/answers/detail/a_id/22827/~/can-i-use-my-netgear-aircard-modem-on-a-linux-operating-system-(v.1.7.40)%3F#CDMA_AT_Commands">CDMA AT Commands</a></li>
<li><a href="http://www.panticz.de/node/670">OpenWrt connect to UMTS with Huawei E620 3G USB Modem</a></li>
<li><a href="https://wiki.ubuntu.com/SierraMC8775">Sierra Wireless model MC8775 PCI Express</a></li>
<li><a href="http://askubuntu.com/questions/323352/how-do-i-log-usb-modem-at-command-output">How do i log usb modem AT command output</a></li>
<li><a href="http://manpages.ubuntu.com/manpages/gutsy/man1/gcom.1.html">gcom datacard control tool</a></li>
<li><a href="http://eko.one.pl/?p=openwrt-3ginfo">OpenWRT 3ginfo</a></li>
<li><a href="http://unix.stackexchange.com/questions/220657/sending-serial-commands-with-echo-vs-screen-session">Sending serial commands with echo vs screen session</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/dev/openwrt-chaos-calmer-15-05-on-dlink-dir-320-with-cdma-modem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CloudWatch custom metrics</title>
		<link>https://webapp.org.ua/dev/cloudwatch-custom-metrics/</link>
		<comments>https://webapp.org.ua/dev/cloudwatch-custom-metrics/#comments</comments>
		<pubDate>Wed, 16 Dec 2015 15:40:08 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[dev]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[cloudwatch]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[time series]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=397</guid>
		<description><![CDATA[In this post we&#8217;re going to investigate how to create custom metrics for the AWS CloudWatch service. In some cases it&#8217;s not enough to have default set of AWS metrics which are already defined for you in dashboard. Let&#8217;s say you want to monitor the number of active customers on your website, or you would [...]]]></description>
			<content:encoded><![CDATA[<div class="markdown-content">
<p><img class="size-full wp-image-417 alignleft" title="cloudwatch_logo" src="http://webapp.org.ua/wp-content/uploads/2015/12/cloudwatch_logo.png" alt="" width="225" height="225" /></p>
<p>In this post we&#8217;re going to investigate how to create custom metrics for the AWS CloudWatch service. In some cases it&#8217;s not enough to have default set of AWS metrics which are already defined for you in dashboard. Let&#8217;s say you want to monitor the number of active customers on your website, or you would like to know the number of failed requests to your API backend.</p>
<p>Whatever it is, CloudWatch will allow you to record any time-based data using AWS APIs.</p>
<p><br style="clear: both;" /></p>
</div>
<p><span id="more-397"></span></p>
<div class="markdown-content">
<h2>Install AWS CLI</h2>
<p>First off, in order to post data to CloudWatch you need to install and setup <a href="https://pypi.python.org/pypi/awscli/">command-line tools to work with AWS APIs</a>:</p>
<pre><code class="bash" title="">$ pip install awscli
</code></pre>
<p>If you don&#8217;t know what <code>pip</code> is, head over <a href="https://pip.pypa.io/en/latest/installing.html">pip installation manual</a>.<br />
Once AWS CLI is installed the <code>aws</code> command should be available via your command shell:</p>
<pre><code class="bash" title="">$ aws
usage: aws [options]   [ ...] [parameters]
To see help text, you can run:

aws help
aws: error: too few arguments
</code></pre>
<p>Before issuing real commands to AWS service you need to configure cli tools:</p>
<pre><code class="bash" title="">$ aws configure
AWS Access Key ID [****************KCEQ]:
AWS Secret Access Key [****************x++s]:
Default region name [us-west-2]:
Default output format [json]:
</code></pre>
<p>After successfull configuration you should be able to use command-line interface for AWS, for example, let&#8217;s list all available EC2 instances:</p>
<pre><code class="" title="">$ aws ec2 describe-instances | grep "PublicDnsName" | awk '{$1=$1};1' | uniq
"PublicDnsName": "ec2-44-148-96-212.us-west-2.compute.amazonaws.com",
"PublicDnsName": "ec2-42-25-174-143.us-west-2.compute.amazonaws.com",
"PublicDnsName": "ec2-44-68-194-93.us-west-2.compute.amazonaws.com",
"PublicDnsName": "ec2-44-69-229-202.us-west-2.compute.amazonaws.com",
</code></pre>
<h2>Choose a metric</h2>
<p>Let&#8217;s say that we want to monitor application API status by periodically requesting specific endpoint and checking HTTP response code. In our example we&#8217;ll use <code>http://httpbin.org/status/200</code> URL to demo.</p>
<p>We will consider HTTP 200 response code as a <code>service alive</code> event and treat it as <code>1</code>, and any other response code(including timeout) as a <code>service failure</code> event or <code>0</code>.</p>
<p>The following bash code(<code>service_mon.sh</code>) will output HTTP response code:</p>
<pre><code class="bash" title="">#!/bin/bash
CODE=`curl -k -s -o /dev/null -w "%{http_code}" http://httpbin.org/status/200`
echo $CODE
</code></pre>
<p>Run it and verify that script outputs <code>200</code>:</p>
<pre><code class="" title="">$ ./service_mon.sh
200
</code></pre>
<h2>Choose metric name</h2>
<p>We&#8217;re going to name our metric <code>ServiceStatus</code> and will report it to CloudWatch using <code>cloudwatch</code> subcommand. Modify above mentioned <code>service_mon.sh</code> script to be the following:</p>
<pre><code class="bash" title="">#!/bin/bash

# get response code
CODE=`curl -k -s -o /dev/null -w "%{http_code}" http://httpbin.org/status/200`
if [ "$CODE" -eq 200 ] ; then
aws cloudwatch put-metric-data --metric-name ServiceStatus --namespace CL_AGENTS --value 1 --unit "Count"
else
aws cloudwatch put-metric-data --metric-name ServiceStatus --namespace CL_AGENTS --value 0 --unit "Count"
fi
</code></pre>
<p>Note <code>CL_AGENTS</code> in cmd parameters, this is a convenient group name for all your metrics, typically you&#8217;d want to put your application name in there. In this example we&#8217;re specifying a type for our data called <code>Count</code>, this is not the only possible option. Here&#8217;s a list of other units:</p>
<pre><code class="" title="">[ Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits,
Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second,
Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None ]
</code></pre>
<p><a href="http://webapp.org.ua/wp-content/uploads/2015/12/aws_metric_namespace.png"><img class="aligncenter size-full wp-image-415" title="aws_metric_namespace" src="http://webapp.org.ua/wp-content/uploads/2015/12/aws_metric_namespace.png" alt="" width="688" height="578" /></a></p>
<p>&nbsp;</p>
<h2>Periodic script execution</h2>
<p>Put the script we&#8217;ve written into crontab:</p>
<pre><code class="" title=""># m h  dom mon dow   command
*/5 * * * * /mnt/service_mon.sh

</code></pre>
<p><span style="text-align: center;">This will post service status to CloudWatch every 5 minutes.  Here&#8217;s how it might look like in web based AWS console:</span></p>
<p style="text-align: center;"><a href="http://webapp.org.ua/wp-content/uploads/2015/12/cloudwatch_metric.png"><img class="aligncenter size-full wp-image-418" title="cloudwatch_metric" src="http://webapp.org.ua/wp-content/uploads/2015/12/cloudwatch_metric.png" alt="" width="824" height="439" /></a></p>
<p>You may also report multiple values at the same time using JSON file:</p>
<pre><code class="json" title="">[
{
"MetricName": "ServiceStatus",
"Timestamp": "Wednesday, June 12, 2013 8:28:20 PM",
"Value": 1,
"Unit": "Count"
},
{
"MetricName": "ServiceStatus",
"Timestamp": "Wednesday, June 12, 2013 8:30:20 PM",
"Value": 0,
"Unit": "Count"
}
]

</code></pre>
<p>To do bulk reporting use this format:</p>
<pre><code class="" title="">$ aws cloudwatch put-metric-data --namespace "CL_AGENTS" --metric-data file://metric.json
</code></pre>
<h2>Setup alarms</h2>
<p>Up until now our metric is almost useless, except that we may see nice graphs in the CloudWatch. To do it more usable, let&#8217;s add alarm if our API is down:</p>
<ul>
<li>Select <code>ServiceName</code> metric in the <code>CL_AGENTS</code> namespace we&#8217;ve just created</li>
<li>Click <code>Create Alarm</code> button on the right side of the graph</li>
<li>In the subsequent popup, select alarm details:</li>
</ul>
<p style="text-align: center;"><a href="http://webapp.org.ua/wp-content/uploads/2015/12/cloudwatch_create_alarm.png"><img class="aligncenter size-full wp-image-416" title="cloudwatch_create_alarm" src="http://webapp.org.ua/wp-content/uploads/2015/12/cloudwatch_create_alarm.png" alt="" width="836" height="587" /></a></p>
<h2>Gotchas</h2>
<ul>
<li>Keep in mind that CloudWatch will store your time-series data only for <strong>2 weeks (14 days)</strong>, therefore if you want more history and insights for your data you&#8217;re probably will be better off using custom database like <a href="https://github.com/influxdb/influxdb">InfluxDB</a> for example</li>
<li>Make sure to setup aws cli under the same user which your crontab is using, otherwise AWS configuration won&#8217;t be accessible for cron and your monitoring script will not work</li>
</ul>
<h2>Links</h2>
<ul>
<li><a href="https://aws.amazon.com/cloudwatch/">Amazon Cloudwatch service</a></li>
<li><a href="http://docs.aws.amazon.com/cli/latest/reference/cloudwatch/put-metric-data.html">Detailed documentation for put-metric-data command</a></li>
<li><a href="https://en.wikipedia.org/wiki/Time_series_database">Time series database</a></li>
</ul>
</div>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/dev/cloudwatch-custom-metrics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing optware on Dune HD-TV 102</title>
		<link>https://webapp.org.ua/hardware/installing-optware-on-dune-hd-tv-102/</link>
		<comments>https://webapp.org.ua/hardware/installing-optware-on-dune-hd-tv-102/#comments</comments>
		<pubDate>Sun, 03 Nov 2013 22:36:18 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[hardware]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[102w]]></category>
		<category><![CDATA[dune]]></category>
		<category><![CDATA[entware]]></category>
		<category><![CDATA[hacking dune]]></category>
		<category><![CDATA[hd-tv 102]]></category>
		<category><![CDATA[optware]]></category>
		<category><![CDATA[root access]]></category>
		<category><![CDATA[transmission]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=362</guid>
		<description><![CDATA[Dune company has given us a miryad of excellent media players, especially by producing high quality software. In this article I&#8217;ll give you step-by-step instructions on how to convert your media player into full-fledged NAS with ability to download torrents and perform any task a generic linux box could do. Root access First off, you [...]]]></description>
			<content:encoded><![CDATA[<div class="markdown-content">
<p><img src="http://webapp.org.ua/wp-content/uploads/2013/11/TV_102w.png" alt="" title="Dune HD TV-102w" width="486" height="259" class="alignleft size-full wp-image-380" /></p>
<p>Dune company has given us a miryad of excellent media players, especially by producing high quality software. In this article I&#8217;ll give you step-by-step instructions on how to convert your media player into  full-fledged NAS with ability to download torrents and perform any task a generic linux box could do.</p>
</div>
<p><br style="clear:both"/><br />
<span id="more-362"></span></p>
<div class="markdown-content">
<h2>Root access</h2>
<p>First off, you need to obtain a retail model Dune HD-TV 102w (with &#8216;w&#8217; postfix), this is the only model which  has appropriate firmware for getting root access.</p>
<p>Download <a href="http://files.dune-hd.com/partners/sdk/dune_service_telnetd.dsf">dune_service_telnetd.dsf</a>, copy it to usb-flash drive and insert into Dune. Power on device, go to <code>Sources</code>, find that file and press <code>OK</code> to execute it. Once this is done, <code>telnetd</code> service will be available until next reboot. To make it permanent, run the following:</p>
<pre><code class="bash" title="">telnet root@dune_ip
login: root
password: &lt;empty&gt;

tangox[~] touch /config/telnetd
tangox[~] sync

</code></pre>
<h2>HDD Partition</h2>
<p>Connect USB-HDD disk drive to Dune to be able to install Optware and store torrents media. We&#8217;re going to re-format the disk and create 3 partitions. Here&#8217;s a sample list:</p>
<pre><code class="bash" title="">tangox[~] fdisk -l /dev/sda

Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

   Device Boot      Start         End      Blocks  Id System
/dev/sda1               1         499     4008186  83 Linux
/dev/sda2             500         624     1004062+ 82 Linux swap
/dev/sda3             625       19457   151276072+ 83 Linux

</code></pre>
<p>As you can see we&#8217;re going to use <code>sda1</code> to store Optware, <code>sda2</code> for swap and <code>sda3</code> for video content.<br />
To do that you may use <code>fdisk</code>, <code>mkfs.ext3</code> and <code>mkswap</code> commands like this:</p>
<pre><code class="bash" title=""># after fdisk partitioning
tangox[~] mkswap /dev/sda2
tangox[~] mkfs.ext3 /dev/sda1
tangox[~] mkfs.ext3 /dev/sda3
</code></pre>
<h3 id="post-362-md-4">Initialize swap</h3>
<p>Dune a has special mechanism to autostart some services during initial boot. We&#8217;re going to put some preliminary startup work there.<br />
Create file <code>/mnt/config/boot/bootstrap.sh</code> and put following contents inside:</p>
<pre><code class="bash" title="">#!/bin/sh
# Turn on swap partition
swapon /dev/sda2
</code></pre>
<p>Then, make sure that file is executable:</p>
<pre><code class="bash" title="">tangox[~] chmod +x /mnt/config/boot/bootstrap.sh
</code></pre>
<h3 id="post-362-md-5">Give nice names to HDD partitions</h3>
<p>In order for HDD partitions to look nice in Dune GUI (sources menu section), will do some more tuning.<br />
First off, issue <code>df</code> command:</p>
<pre><code class="bash" title="">tangox[~] df
Filesystem                Size      Used Available Use% Mounted on
tmpfs                    92.7M      3.1M     89.6M   3% /tmp
/dev/sda3               142.0G     57.8G     77.0G  43% /D
/dev/mtdblock4          105.2M     75.6M     29.5M  72% /app
/dev/loop0              262.3M    262.3M         0 100% /tango3
/dev/mtdblock5          100.0M      8.1M     91.9M   8% /mnt
/dev/sda1                 3.8G    132.3M      3.4G   4% /tmp/mnt/storage/34611c58-ba35-4256-b546-8038078575ab
/dev/sda3               142.0G     57.8G     77.0G  43% /tmp/mnt/storage/566c9eb8-8239-4af5-9ea5-609ddc035e6f

</code></pre>
<p>You&#8217;ll see those ugly long directory names, which we want to change. Go to <code>/tmp/mnt/storage/34611c58-ba35-4256-b546-8038078575ab</code> and create the file <code>dune_folder.txt</code> with the following contents:</p>
<pre><code class="bash" title="">storage_name=opt
system_files=*
</code></pre>
<p>Because this is a system partition for our Optware we&#8217;re going to hide every file from being visible by end-user. Go to next directory and create similar file:</p>
<pre><code class="bash" title="">tangox[~] cd /tmp/mnt/storage/566c9eb8-8239-4af5-9ea5-609ddc035e6f
tangox[~] echo "storage_name=media" &gt;&gt; dune_folder.txt
tangox[~] echo "system_files=*.part" &gt;&gt; dune_folder.txt
</code></pre>
<p>This set of folder settings will make uncompleted torrent files hidden from Dune menus. Once you&#8217;re done, reboot, telnet again and run <code>df</code> command one more time:</p>
<pre><code class="bash" title="">tangox[~] df
Filesystem                Size      Used Available Use% Mounted on
tmpfs                    92.7M      3.1M     89.6M   3% /tmp
/dev/sda3               142.0G     57.8G     77.0G  43% /D
/dev/mtdblock4          105.2M     75.6M     29.5M  72% /app
/dev/loop0              262.3M    262.3M         0 100% /tango3
/dev/mtdblock5          100.0M      8.1M     91.9M   8% /mnt
/dev/sda1                 3.8G    132.3M      3.4G   4% /tmp/mnt/storage/opt
/dev/sda3               142.0G     57.8G     77.0G  43% /tmp/mnt/storage/media
</code></pre>
<p>Things will look more nicer! Now, let&#8217;s make aliases for <code>opt</code> and <code>media</code> folders by symlinking them to root.  Make sure your system don&#8217;t have any important data at <code>/opt</code> as we&#8217;re going to delete it. Now, open <code>/mnt/config/boot/bootstrap.sh</code> file and modify it to look as following:</p>
<pre><code class="bash" title="">#!/bin/sh
# Turn on swap partition
swapon /dev/sda2

# symlink optware and media folders
rm -rf /opt
ln -s /tmp/mnt/storage/opt /opt
ln -s /tmp/mnt/storage/media /media

</code></pre>
<p>Now reboot, and ensure that there are valid <code>/opt</code> and <code>/media</code> symlinks at root path.</p>
<h2>Optware installation</h2>
<p>Finally we&#8217;re ready to install additional software. Create optware installation script at <code>/opt/install.sh</code>:</p>
<pre><code class="bash" title="">#!/bin/sh
# Source code: http://www.nslu2-linux.org/wiki/Optware/HomePage
feed=http://ipkg.nslu2-linux.org/feeds/optware/oleg/cross/unstable/
# install ipkg
ipk_name=`wget -qO- $feed/Packages | awk '/^Filename: ipkg-opt/ {print $2}'`
/usr/bin/wget "$feed/$ipk_name"
/bin/tar -xOvzf $ipk_name ./data.tar.gz | tar -C / -xzvf -
mkdir -p /opt/etc/ipkg
echo "src cross $feed" &gt; /opt/etc/ipkg/feeds.conf

# install uc-libC
ipk_name=`wget -qO- $feed/Packages | awk '/^Filename: uclibc-opt/ {print $2}'`
/usr/bin/wget "$feed/$ipk_name"
/bin/tar -xOvzf $ipk_name ./data.tar.gz | tar -C / -xzvf -

</code></pre>
<p>To do that you may should use <code>vi</code> editor which is available by default. Ensure that the file is executable and run it:</p>
<pre><code class="bash" title="">tangox[~] chmod +x /opt/install.sh
# run it
tangox[opt] ./install.sh

Connecting to ipkg.nslu2-linux.org (140.211.169.161:80)
ipkg-opt_0.99.163-10 100% |*************************************************************************************************************| 75831  00:00:00 ETA
./
./opt/
./opt/bin/
./opt/bin/ipkg
./opt/bin/ipkg-opt
./opt/bin/update-alternatives
./opt/etc/
./opt/etc/ipkg.conf

.....................................

Connecting to ipkg.nslu2-linux.org (140.211.169.161:80)
uclibc-opt_0.9.28-13 100% |*************************************************************************************************************|   832k 00:00:00 ETA
./
./opt/
./opt/etc/
./opt/lib/
./opt/lib/ld-uClibc-0.9.28.so
./opt/lib/ld-uClibc.so.0
./opt/lib/libc.so

......................................................

</code></pre>
<p>If you&#8217;ve been observing messages above chances are high that you now have a working skeleton of optware system.<br />
Let&#8217;s check this by typing:</p>
<pre><code class="bash" title="">tangox[opt] /opt/bin/ipkg --version
ipkg version 0.99.163

</code></pre>
<p>This means that package management system has been installed and works fine. From this time on you have the ability to install tons of additional linux software precompiled for MIPS architecture!  You may get the list of available software by typing <code>ipkg --list</code>, and we&#8217;ll continue our tuning process.</p>
<h3 id="post-362-md-6">Fix PATH variable</h3>
<p>Let&#8217;s make using optware more convenient, open <code>/mnt/config/boot/bootstrap.sh</code> and add following lines:</p>
<pre><code class="bash" title=""># fix PATH for new packages
echo "export PATH=/opt/bin:/opt/sbin:/bin:/sbin:/usr/bin:/usr/bin/X11:/usr/local/bin" &gt;&gt; /root/.bashrc
echo "export PATH=/opt/bin:/opt/sbin:/bin:/sbin:/usr/bin:/usr/bin/X11:/usr/local/bin" &gt;&gt; /etc/profile
</code></pre>
<h2>Optware autostart hack</h2>
<p>In order to autostart all neccessary services we&#8217;re going to do some additional hacking. At first, it seems that adding call of autostart script to <code>/mnt/config/boot/bootstrap.sh</code> will do the trick, but after numeruos attempts  to do just that things didn&#8217;t work. My guess is that at <code>/mnt/config/boot/</code> stage external storage is not mounted yet, so everything under <code>/opt</code> is not available.</p>
<p>To overcome that, I&#8217;ve managed to create a bit ugly, but working solution, i.e. to autostart services using crond,  which is available by default on device. The idea is simple: start optware only once, and if it is started already just do nothing. Let&#8217;s write some scripts to achieve that.</p>
<p>Create <code>/opt/etc/rc.optware</code> file with following contents:</p>
<pre><code class="bash" title="">#!/bin/sh
# Start all init scripts in /opt/etc/init.d
# executing them in numerical order.
for i in /opt/etc/init.d/* ;do

    # Ignore dangling symlinks (if any).
    [ ! -f "$i" ] &amp;&amp; continue

    case "$i" in
       *.sh)
        # Source shell script for speed.
        (
            trap - INT QUIT TSTP
            set start
            . $i
        )
        ;;
       *)
        # No sh extension, so fork subprocess.
        $i start
        ;;
    esac
done
</code></pre>
<p>Create <code>/opt/etc/optware-cron.sh</code> with following contents:</p>
<pre><code class="bash" title="">#!/bin/sh
# After reboot this file will be absent!
FLAG_FILE=/var/run/optware.started

# if file not found, run optware
if [ ! -f $FLAG_FILE ]; then
 touch $FLAG_FILE
 /opt/etc/rc.optware
fi
</code></pre>
<p>Make sure both files are executable:</p>
<pre><code class="bash" title="">tangox[opt] chmod +x optware-cron.sh rc.optware
</code></pre>
<p>Open our <code>/mnt/config/boot/bootstrap.sh</code> file and add following lines:</p>
<pre><code class="bash" title="">killall crond
echo "*/1 * * * * /opt/etc/optware-cron.sh" &gt;&gt; /tmp/cron/crontabs/root
/usr/sbin/crond
</code></pre>
<p>This will modify crond config during startup and will make sure that <code>optware-cron.sh</code> file will be launched once per every minute.</p>
<p>Reboot your dune and ensure that everything works fine. Next, we&#8217;re going to add some useful software like transmission!</p>
<h2>Install transmission</h2>
<p><img src="http://webapp.org.ua/wp-content/uploads/2013/11/transmission-bittorrent1.png" alt="" title="transmission-bittorrent" width="300" height="300" class="aligncenter size-full wp-image-383" /></p>
<pre><code class="bash" title="">tangox[opt] ipkg install transmission
</code></pre>
<p>Let&#8217;s create startup script for Transmission daemon, open <code>/opt/etc/init.d/S60transmission</code> and type in:</p>
<pre><code class="bash" title="">#!/bin/sh
# Exit if the package is not installed
test -f /opt/bin/transmission-daemon || exit 0

function start_daemon() {
    /sbin/start-stop-daemon --start --quiet --exec /opt/bin/transmission-daemon  --auth --config-dir=/opt/etc/transmission/ --username="your_username" --password="your_password" --download-dir=/media/ --allowed=* --logfile=/opt/var/log/transmissiond.log
}

case "$1" in
  start)
    echo  "Starting transmission-daemon"
    start_daemon
    ;;
  stop)
    echo  "Stopping transmission-daemon"
    /sbin/start-stop-daemon --stop --quiet --exec /opt/bin/transmission-daemon
    ;;
  restart)
    echo -n "Stopping transmission-daemon"
    /sbin/start-stop-daemon --stop --quiet --exec /opt/bin/transmission-daemon
    for i in 1 2 3 ;
    do
        sleep 1
        echo -n "."
    done
    echo  "Restarting transmission-daemon"
    start_daemon
    ;;
  *)
    echo "Usage: /opt/etc/init.d/S60transmission {start|stop|restart}"
    exit 1
esac

exit 0

</code></pre>
<p>Don&#8217;t forget to make this script executable and make sure you provide valid <code>your_username</code> and <code>your_password</code>. Verify that transmission daemon works by typing in the terminal:</p>
<pre><code class="bash" title="">tangox[opt] /opt/etc/init.d/S60transmission start
tangox[opt] ps -Af | grep trans
 1500 root       0:04 /opt/bin/transmission-daemon --auth --config-dir=/opt/etc/transmission/ --username="your_username" --password="your_password" --download-dir=/media/ --allowed=* --logfile=/opt/var/log/transmissiond.log 

</code></pre>
<p>If everything went fine the last command should output transmission process running in the background, you might also observe it by running <code>top</code> command.</p>
<p>Reboot your dune once again, open your favorite web browser and point it to <code>http://dune_ip:9091</code> you should see basic auth dialog from your Transmission web interface. From this point you&#8217;re free to download any torrent media which will be instantly accessible for playback once completed.</p>
<h2>Some useful tips</h2>
<p>1) I would highly recommend desktop client for transmission called <a href="https://code.google.com/p/transmisson-remote-gui/">Transmission Remote GUI</a> it has more control and features than default web interface.</p>
<p>2) Find out <code>power management</code> section in main dune menu and set <code>sleep mode</code> to <code>never</code>. You need your device to be online 7&#215;24 don&#8217;t you?</p>
<p>3) Install <code>openssh</code> tools, setup <a href="http://www.cyberciti.biz/tips/ssh-public-key-based-authentication-how-to.html">public key based authentication</a> and turn off passwordless telnet to increase security</p>
<h2>Links</h2>
<ul>
<li><a href="http://files.dune-hd.com/partners/sdk/dune_devel_info.txt">http://files.dune-hd.com/partners/sdk/dune_devel_info.txt</a></li>
<li><a href="http://files.dune-hd.com/partners/sdk/dune_service_telnetd.dsf">http://files.dune-hd.com/partners/sdk/dune_service_telnetd.dsf</a></li>
<li><a href="http://dune-hd.com/support/misc/dune_folder_howto.txt">http://dune-hd.com/support/misc/dune_folder_howto.txt</a></li>
<li><a href="http://files.dune-hd.com/partners/sdk/dune_boot_process.txt">http://files.dune-hd.com/partners/sdk/dune_boot_process.txt</a></li>
<li><a href="https://code.google.com/p/transmisson-remote-gui/">https://code.google.com/p/transmisson-remote-gui/</a></li>
<li><a href="http://www.cyberciti.biz/tips/ssh-public-key-based-authentication-how-to.html">http://www.cyberciti.biz/tips/ssh-public-key-based-authentication-how-to.html</a></li>
</ul>
</div>
<p></empty></p>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/hardware/installing-optware-on-dune-hd-tv-102/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to setup TimeMachine on a network drive with disk quota</title>
		<link>https://webapp.org.ua/hardware/how-to-setup-timemachine-on-a-network-drive-with-disk-quota/</link>
		<comments>https://webapp.org.ua/hardware/how-to-setup-timemachine-on-a-network-drive-with-disk-quota/#comments</comments>
		<pubDate>Wed, 17 Oct 2012 21:45:37 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[hardware]]></category>
		<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[access rights]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[Buffalo]]></category>
		<category><![CDATA[disk quota]]></category>
		<category><![CDATA[LS-WXL]]></category>
		<category><![CDATA[NAS]]></category>
		<category><![CDATA[Network drive]]></category>
		<category><![CDATA[Time Machine]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=283</guid>
		<description><![CDATA[Well, once you bought your NAS or configured a dedicated PC with network drive you&#8217;ll obviously want to setup Time Machine. The problem is, once configured to backup to a networked drive your TimeMachine will eat all available space. For those lucky ones, who shared a dedicated disk partition on their drive — there&#8217;s no problem [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://webapp.org.ua/wp-content/uploads/2012/10/tm-logo.png"><img class="alignleft size-medium wp-image-285" title="tm-logo" src="http://webapp.org.ua/wp-content/uploads/2012/10/tm-logo-300x300.png" alt="" width="300" height="300" /></a>Well, once you bought your <a href="http://en.wikipedia.org/wiki/Network-attached_storage">NAS</a> or configured a dedicated PC with network drive you&#8217;ll obviously want to setup Time Machine.  The problem is, once configured to backup to a networked drive your TimeMachine will eat all available space.</p>
<p>For those lucky ones, who shared a dedicated disk partition on their drive — there&#8217;s no problem at all. But I was not one of them. Recently, I&#8217;ve purchased a used <a href="http://www.buffalo-technology.com/en/ls-wxl-linkstation-duo.html">Buffalo LS-WXL Linkstation duo</a> inserted two new 1TB drives and configured it as a RAID0 array. As a result, almost whole 2Tb partition became available for sharing — despite how hard I tried to figure out <a href="http://en.wikipedia.org/wiki/XFS">xfs</a> quotas on target partition, no success.</p>
<p>Well, there are bad and good news.</p>
<ul>
<li>The good news is that you may limit your Time Machine disk quota by using something called <a href="http://en.wikipedia.org/wiki/Sparse_image">sparse disk bundles</a>.</li>
<li>The bad news is that you&#8217;ll need <a href="http://buffalo.nas-central.org/wiki/Category:LS-WXL#Gain_SSH_Access">root access to your NAS</a> in order to apply permissions hack to make it work with latest versions of Time Machine</li>
</ul>
<p><br style="clear: both;" /><br />
<span id="more-283"></span></p>
<p>Let&#8217;s proceed!</p>
<h2>Create sparse bundle on your mac</h2>
<p>Open terminal, and create 1024g sparse disk:</p>
<pre><code class="bash">
# Get the MACADDR of network port
$ MAC=$(ifconfig en0 | perl -ne 's/.*ether (\w+:\w+:\w+:\w+:\w+:\w+).*/$1/ &amp;&amp; s/://g &amp;&amp; print;')
$ echo $MAC
001122334455

# Create name of sparsebundle
$ SBNAME=$(hostname)_$MAC.sparsebundle
$ echo $SBNAME
amber_001122334455.sparsebundle

# Create sparse image
# You should modify 1024g to the size of your maximum Time Machine backup size.
$ hdiutil create -fs HFS+J -size 1024g -type SPARSEBUNDLE -volname "Time Machine" $SBNAME
$ ls $SBNAME
Info.bckup    Info.plist    bands        token
</code></pre>
<p>Once this is done, copy sparse bundle directory into your network volume:</p>
<pre><code class="bash">
# mine network disk is called /Volume/tm
$ cp -R $SBNAME /Volumes/tm
</code></pre>
<h2>Create a separate user for TimeMachine</h2>
<p>It is a good practice to create a special user specifically for network drives that will be used for TimeMachine backup.</p>
<p>I called mine <em>tm</em>:</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2012/10/create_™_user.png"></a><a href="http://webapp.org.ua/wp-content/uploads/2012/10/2012-10-18_0039.png"><img class="aligncenter size-full wp-image-290" title="buffalo_create_user" src="http://webapp.org.ua/wp-content/uploads/2012/10/2012-10-18_0039.png" alt="" width="794" height="492" /></a></p>
<h2>Apply hack with access rights</h2>
<p>On MacOS X versions prior to 10.6.3, this step would be not necessary, but on latest versions TimeMachine automatically resizes your sparse bundle to occupy the whole space. We&#8217;ll deny it using access rights hack.</p>
<p>To be able to continue, you should access your NAS using <a href="http://buffalo.nas-central.org/wiki/Category:LS-WXL">root credentials</a>.</p>
<pre><code class="bash">
# login to your NAS via ssh
$ ssh -i ~/.ssh/my.key root@nas
Warning: Permanently added 'nas,192.168.1.227' (RSA) to the list of known hosts.
Last login: Wed Oct 17 19:35:37 2012 from amber

# go to the destination of your shared network volume
root@NAS:~$ cd /mnt/array1/tm/

# check out that sparse bundle has been successfully copied
root@NAS:/mnt/array1/tm$ ls -l
drwxrwsrwx    4 tm       hdusers      4096 Oct 17 19:08 amber_001122334455.sparsebundle/
</code></pre>
<p>The main idea behind access right hack is pretty simple: deny TimeMachine user from write access to specific files:</p>
<pre><code class="bash">
# Give read-only access for tm user
root@NAS:/mnt/array1/tm$ cd amber_001122334455.sparsebundle
root@NAS:/mnt/array1/tm/amber.sparsebundle$  chown root:root Info.*
root@NAS:/mnt/array1/tm/amber.sparsebundle$  chmod a+r-w Info.*

# Check access rights:

root@NAS:/mnt/array1/tm/amber.sparsebundle# ls -l
-r--r--r--    1 root     root          500 Oct  9 20:36 Info.bckup
-r--r--r--    1 root     root          500 Oct  9 20:36 Info.plist
drwxrwsrwx    3 tm       hdusers   1155072 Oct 17 19:08 bands/
</code></pre>
<h2>Configure TimeMachine</h2>
<p>The last step is to configure TimeMachine to backup to network disk. It&#8217;s the same process as with usual hdd.</p>
<p>Once TimeMachine is configured, let&#8217;s verify that it is backing up normally and will not occupy the whole disk space.</p>
<p>Open <code>Spotlight</code> and type <code>Console</code> — a special program to see your software logs. Matching string for TimeMachine will be <code>backupd</code></p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2012/10/console_log_for_tm.png"><img class="aligncenter size-full wp-image-287" title="console log for TimeMachine" src="http://webapp.org.ua/wp-content/uploads/2012/10/console_log_for_tm.png" alt="" width="872" height="327" /></a></p>
<p>At the console logs you should see something like this:</p>
<pre><code>
10/9/12 8:39:36.012 PM com.apple.backupd: Starting standard backup
10/9/12 8:39:36.026 PM com.apple.backupd: Attempting to mount network destination URL: afp://tm@NAS._afpovertcp._tcp.local/tm
10/9/12 8:39:36.480 PM com.apple.backupd: Mounted network destination at mountpoint: /Volumes/tm-1 using URL: afp://tm@NAS._afpovertcp._tcp.local/tm
<strong>10/9/12 8:39:53.925 PM com.apple.backupd: Resizing backup disk image from 1024.0 GB to 1834.2 GB</strong>
<strong>10/9/12 8:39:53.938 PM com.apple.backupd: Could not resize backup disk image (DIHLResizeImage returned 35)</strong>
10/9/12 8:39:53.939 PM com.apple.backupd: Renaming /Volumes/tm-1/amber_c82a141a607c.sparsebundle to /Volumes/tm-1/amber.sparsebundle
10/9/12 8:39:53.971 PM com.apple.backupd: Running backup verification
10/9/12 8:39:55.349 PM com.apple.backupd: QUICKCHECK ONLY; FILESYSTEM CLEAN
10/9/12 8:40:57.454 PM com.apple.backupd: Backup verification passed!
10/9/12 8:40:58.953 PM com.apple.backupd: QUICKCHECK ONLY; FILESYSTEM CLEAN
10/9/12 8:41:01.105 PM com.apple.backupd: Disk image /Volumes/tm-1/amber.sparsebundle mounted at: /Volumes/Time Machine
10/9/12 8:41:01.113 PM com.apple.backupd: Backing up to: /Volumes/Time Machine/Backups.backupdb
10/9/12 8:41:01.117 PM com.apple.backupd: Ownership is disabled on the backup destination volume.  Enabling.
10/9/12 8:41:12.304 PM com.apple.backupd: Backup content size: 95.2 GB excluded items size: 18.1 GB for volume sys
10/9/12 8:42:20.556 PM com.apple.backupd: Backup content size: 668.6 GB excluded items size: 248.4 GB for volume storage
10/9/12 8:42:20.564 PM com.apple.backupd: 596.84 GB required (including padding), 1023.05 GB available
10/9/12 8:42:20.616 PM com.apple.backupd: Waiting for index to be ready (101)
</code></pre>
<p>The message we&#8217;re most interested in is <code>com.apple.backupd: Could not resize backup disk image (DIHLResizeImage returned 35)</code>, which means that our access rights hack worked and TimeMachine will be limited by 1024GB.</p>
<p>However, reporting will show you the whole disk size as available — don&#8217;t be confused by this:</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2012/10/main_scr_tm.png"><img class="aligncenter size-full wp-image-288" title="Time Machine reporting invalid disk quota" src="http://webapp.org.ua/wp-content/uploads/2012/10/main_scr_tm.png" alt="" width="668" height="445" /></a></p>
<h2>Related info</h2>
<ul>
<li><a href="http://forums.buffalotech.com/t5/Storage/Time-Machine-Setup-How-to-prevent-disk-image-from-resizing/td-p/73624">Time Machine Setup: How to prevent disk image from resizing</a></li>
<li><a href="http://code.stephenmorley.org/articles/time-machine-on-a-network-drive/">Time machine on a network drive</a></li>
<li><a href="http://hintsforums.macworld.com/showthread.php?t=110709">TimeMachine doesn&#8217;t play well with custom sparsebundles</a></li>
<li><a href="http://buffalo.nas-central.org/wiki/Category:LS-WXL">Root access on Buffalo LS-WXL</a></li>
<li><a href="http://www.buffalo-technology.com/en/ls-wxl-linkstation-duo.html">Buffalo LS-WXL linkstation duo</a></li>
<li><a href="http://en.wikipedia.org/wiki/Network-attached_storage"> Network attached storage </a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/hardware/how-to-setup-timemachine-on-a-network-drive-with-disk-quota/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing OpenVZ on Amazon EC2</title>
		<link>https://webapp.org.ua/sysadmin/installing-openvz-on-amazon-ec2/</link>
		<comments>https://webapp.org.ua/sysadmin/installing-openvz-on-amazon-ec2/#comments</comments>
		<pubDate>Thu, 01 Dec 2011 13:49:27 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[openvz]]></category>
		<category><![CDATA[pv-grub]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=172</guid>
		<description><![CDATA[Imagine, that your system is pretty complicated and consists of a number of components, each deployed into separate machine.  For development &#38; testing needs it&#8217;s always too costly to keep up &#38; running all these machines.  It&#8217;s not that as easy to make modification into your system structure, i.e. adding new machines with different roles, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://webapp.org.ua/wp-content/uploads/2011/12/aws_logo.jpg"><img class="size-medium wp-image-177 alignleft" title="aws_logo" src="http://webapp.org.ua/wp-content/uploads/2011/12/aws_logo-300x109.jpg" alt="" width="300" height="109" /></a>Imagine, that your system is pretty complicated and consists of a number of components, each deployed into separate machine.  For development &amp; testing needs it&#8217;s always too costly to keep up &amp; running all these machines.  It&#8217;s not that as easy to make modification into your system structure, i.e. adding new machines with different roles, etc.</p>
<p>One solution is to virtualize all your stuff &amp; isolate environment of each component.  An easy way would be to buy a hardware &amp; setup hardware virtualization such as <a href="http://xen.org">XEN</a> for instance, but there is more popular approach &#8212; using <a href="http://aws.amazon.com/ec2/">Amazon EC2</a> cloud services.</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2011/12/OpenVZ-logo.png"><img class="size-medium wp-image-178 alignright" title="OpenVZ-logo" src="http://webapp.org.ua/wp-content/uploads/2011/12/OpenVZ-logo-300x76.png" alt="" width="300" height="76" /></a>In this post I&#8217;m going to show you how to setup OpenVZ virtualization on Amazon EC2 node (which, actually itself is virtualized XEN node)</p>
<p>We&#8217;re going to use as a base a CentOS 5.6 Amazon image with <a href="http://wiki.xen.org/xenwiki/PvGrub">pv-grub</a> enabled (this is required to be able to boot into custom kernel)</p>
<p><span id="more-172"></span></p>
<p>Ok, from the AWS console start CentOS 5.6/x64  (centos-5.6-64bit-ebs-pvgrub / ami-a14f1ce4), obtain public DNS name &amp; make sure that default ssh 22 port is enabled:</p>
<pre><code class="bash">
ssh -i ~/aws_ssh.key root@ec2-50-18-60-65.us-west-1.compute.amazonaws.com
</code></pre>
<h2>Install OpenVZ &amp; some dependencies</h2>
<pre><code class="bash">
yum -y install gcc.x86_64 gcc-c++.x86_64 java-1.6.0-openjdk iptables openssl-devel zlib-devel pkgconfig glib2-devel

#Open VZ, Install XEN-compatible kernel!
wget -O /etc/yum.repos.d/openvz.repo http://download.openvz.org/openvz.repo
rpm --import http://download.openvz.org/RPM-GPG-Key-OpenVZ
yum --enablerepo=openvz-kernel-rhel5 -y install ovzkernel-xen.x86_64 ovzkernel-xen-devel.x86_64 vzctl.x86_64 vzquota.x86_64
</code></pre>
<h2>Override some kernel parameters</h2>
<pre><code class="bash">
echo "net.ipv4.ip_forward = 1
net.ipv4.conf.default.proxy_arp = 0
net.ipv4.conf.all.rp_filter = 1
kernel.sysrq = 1
net.ipv4.conf.default.send_redirects = 1
net.ipv4.conf.all.send_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.conf.default.forwarding=1
net.ipv4.conf.default.accept_source_route = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296" &gt; /etc/sysctl.conf
# reload from disk
sysctl -p

#Substitute default kernel by OpenVZ
sed -i 's/kernel/ovzkernel/' /etc/sysconfig/kernel
</code></pre>
<h2>Install ntpd</h2>
<p>This will help to sync time between all virtual machines.</p>
<pre><code class="bash">yum install -y ntp.x86_64
/usr/sbin/ntpdate 0.rhel.pool.ntp.org europe.pool.ntp.org
# start on next boot
chkconfig ntpd on
</code></pre>
<h2>Enable rpmforge repo</h2>
<p>Chances are pretty high that you&#8217;ll want something from this repo (latest git for example), so you&#8217;d better install it now.</p>
<pre><code class="bash">rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
wget -O /tmp/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
rpm -Uvh /tmp/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
yum -y install --enablerepo=rpmforge git.x86_64

</code></pre>
<h2>Setup firewall</h2>
<pre><code class="bash">#Setup firewall
echo "*filter" &gt; /etc/sysconfig/iptables
echo "COMMIT" &gt;&gt; /etc/sysconfig/iptables
</code></pre>
<h2>Install OpenVZ kernel to boot by default</h2>
<p>For some reason, yum install process does not add OpenVZ kernel into grub bootlist, therefore we&#8217;re doing it manually:</p>
<div class="gfm-content">WP_GFM HttpError: server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none</div>
<p>Check your <code>/boot/grub/menu.lst</code>, it should look like following:</p>
<pre><code class="bash">default=1
title centos5.6
  root (hd0)
  kernel /boot/vmlinuz-2.6.18-238.5.1.el5xen root=/dev/sda1
  initrd /boot/initrd-2.6.18-238.5.1.el5xen.img

title CentOS-openvz-xen
  root (hd0)
  kernel /boot/vmlinuz-2.6.18-274.3.1.el5.028stab094.3xen root=/dev/sda1
  initrd /boot/initrd-2.6.18-274.3.1.el5.028stab094.3xen.img

</code></pre>
<p>Reboot and then login again to check that you&#8217;re on OpenVZ kernel:</p>
<pre><code class="bash">
ssh -i ~/aws_ssh.key root@ec2-204-236-152-176.us-west-1.compute.amazonaws.com
Last login: Tue Nov 29 05:34:50 2011 from 94.45.135.130
[root@ip-10-176-46-67 ~]# uname -a
Linux ip-10-176-46-67 2.6.18-274.7.1.el5.028<strong>stab</strong>095.1xen #1 SMP Mon Oct 24 21:00:35 MSD 2011 x86_64 x86_64 x86_64 GNU/Linux
</code></pre>
<h2>Download &amp; install OpenVZ CentOS5 template:</h2>
<pre><code class="bash">wget http://download.openvz.org/template/precreated/centos-5-x86_64.tar.gz

#Symlink OpenVZ CentOS template
[ -d /vz/template/cache ] || mkdir -p /vz/template/cache
ln -s /root/centos-5-x86_64.tar.gz /vz/template/cache
</code></pre>
<h2>Create your first OpenVZ container(VM)</h2>
<pre><code class="bash">vzctl create 101 --ostemplate centos-5-x86_64 &gt; /dev/null
vzctl set 101 --ipadd 10.0.102.101 --save &gt; /dev/null
vzctl set 101 --nameserver 8.8.8.8 --save &gt; /dev/null
vzctl set 101 --name "APP1" --save &gt; /dev/null
vzctl set 101 --onboot yes --save &gt; /dev/null
</code></pre>
<p>Try to login into APP1 shell:</p>
<pre><code class="bash">vzctl enter 101
</code></pre>
<p>At this point, if you was able to create APP1 container, you can setup other components of your system &#8212; Database, Cache server, whatever you want.</p>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/sysadmin/installing-openvz-on-amazon-ec2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Setting up NGINX SSL reverse proxy for Tomcat</title>
		<link>https://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/</link>
		<comments>https://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 13:39:27 +0000</pubDate>
		<dc:creator>bananos</dc:creator>
				<category><![CDATA[sysadmin]]></category>
		<category><![CDATA[nginx]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[ssl reverse proxy]]></category>
		<category><![CDATA[tomcat]]></category>
		<category><![CDATA[tomcat reverse proxy]]></category>

		<guid isPermaLink="false">http://webapp.org.ua/?p=150</guid>
		<description><![CDATA[Setting up Tomcat in some cases can be pain in the ass, especially when your application is pretty complex, in terms of large number of upstream servers which you all want to proxy via SSL. In my case, I was playing around with Shindig &#8212; an OpenSocial container, which itself is a Java servlet delivered via Apache [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://webapp.org.ua/wp-content/uploads/2011/11/apache-tomcat-install.jpg"><img class="size-full wp-image-193 alignleft" title="apache-tomcat-install" src="http://webapp.org.ua/wp-content/uploads/2011/11/apache-tomcat-install.jpg" alt="" width="268" height="129" /></a>Setting up Tomcat in some cases can be pain in the ass, especially when your application is pretty complex, in terms of large number of upstream servers which you all want to proxy via SSL.</p>
<p>In my case, I was playing around with <a href="http://shindig.apache.org/" target="_blank">Shindig</a> &#8212; an OpenSocial container, which itself is a Java servlet delivered via <a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat</a> server.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><a href="http://webapp.org.ua/wp-content/uploads/2011/12/Nginx-logo-620x350.png"><img class="alignright size-medium wp-image-196" title="Nginx-logo" src="http://webapp.org.ua/wp-content/uploads/2011/12/Nginx-logo-620x350-300x81.png" alt="" width="300" height="81" /></a></p>
<p>The goal was to reverse proxy Shindig through SSL, i.e. it should be able to access it via</p>
<pre><code class="bash">https://localhost/gadgets/</code></pre>
<p>with localhost being served by <a href="http://nginx.org/" target="_blank">Nginx</a>.</p>
<p><span id="more-150"></span></p>
<h2>Initial schema</h2>
<h2><a href="http://webapp.org.ua/wp-content/uploads/2011/11/tt.png"><img class="aligncenter size-full wp-image-151" title="nginx-tomcat-reverse-proxy" src="http://webapp.org.ua/wp-content/uploads/2011/11/tt.png" alt="nginx tomcat reverse proxy schema" width="396" height="473" /></a>Initial nginx config</h2>
<pre><code class="nginx">
daemon off;

worker_processes  2;
error_log /var/log/nginx_error.log info;
user bananos staff;

events {
    worker_connections  1024;
}

http {
    include /opt/nginx/conf/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $bytes_sent "$http_referer" "$http_user_agent" "$gzip_ratio"';
    ignore_invalid_headers on;
    index index.html;
    client_header_timeout 240;
    client_body_timeout 240;
    send_timeout 240;
    client_max_body_size 100m;
    proxy_buffer_size 128k;
    proxy_buffers 8 128k;

    upstream tomcat_server {
	# Tomcat is listening on default 8080 port
        server 127.0.0.1:8080 fail_timeout=0;
    }

    server {
        server_name localhost;
        listen 443;

        ssl on;
        ssl_session_timeout 5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        #make sure you already have this certificate pair!
	ssl_certificate /var/certs/server.crt;
        ssl_certificate_key /var/certs/server.key;
        ssl_session_cache shared:SSL:10m;

	# www-root, we're serving static files from here, accessible via https://localhost/
        location / {
            root  /var/www;
            index index.html index.htm;
        }

	# Our endpoint for tomcat reverse-proxy, assuming your endpoint java-servlet knows
	# how to handle http://localhost/gadgets  requests
        location /gadgets {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
	    proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
            proxy_connect_timeout      240;
            proxy_send_timeout         240;
            proxy_read_timeout         240;
            # note, there is not SSL here! plain HTTP is used
	   proxy_pass http://tomcat_server;
        }
     }
}

</code></pre>
<h2>Tomcat config</h2>
<p>And here the magic begins, the main point to not miss here is</p>
<blockquote><p>Tomcat needs to be explicitly told that it&#8217;s being proxied through 443(SSL) port!</p></blockquote>
<p>Here is a sample Tomcat config which is usually found at</p>
<pre><code class="bash">
{$CATALINA_HOME}/conf/server.xml
</code></pre>
<pre><code class="xml">

&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--&gt;
&lt;!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 --&gt;
&lt;Server port="8005" shutdown="SHUTDOWN"&gt;
  &lt;!-- Security listener. Documentation at /docs/config/listeners.html
  &lt;Listener className="org.apache.catalina.security.SecurityListener" /&gt;
  --&gt;
  &lt;!--APR library loader. Documentation at /docs/apr.html --&gt;
  &lt;Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" /&gt;
  &lt;!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html --&gt;
  &lt;Listener className="org.apache.catalina.core.JasperListener" /&gt;
  &lt;!-- Prevent memory leaks due to use of particular java/javax APIs--&gt;
  &lt;Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /&gt;
  &lt;Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /&gt;
  &lt;Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" /&gt;

  &lt;!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  --&gt;

&lt;!--  &lt;GlobalNamingResources&gt;--&gt;
    &lt;!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    --&gt;
&lt;!--
    &lt;Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" /&gt;
  &lt;/GlobalNamingResources&gt; --&gt;

  &lt;!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   --&gt;
  &lt;Service name="Catalina"&gt;

    &lt;!--The connectors can use a shared executor, you can define one or more named thread pools--&gt;
    &lt;!--
    &lt;Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/&gt;
    --&gt;

    &lt;!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking &amp; non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    --&gt;
    &lt;Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
	       proxyName="localhost"
               <span style="font-size: 200%;">proxyPort="443"</span>
               <span style="font-size: 200%;">scheme="https"</span>
                /&gt;
    &lt;!-- A "Connector" using the shared thread pool--&gt;
    &lt;!--
    &lt;Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" /&gt;
    --&gt;
    &lt;!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation --&gt;
    &lt;!--
    &lt;Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" /&gt;
    --&gt;

    &lt;!-- Define an AJP 1.3 Connector on port 8009 --&gt;
  &lt;!--  &lt;Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /&gt;--&gt;

    &lt;!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html --&gt;

    &lt;!-- You should set jvmRoute to support load-balancing via AJP ie :
    &lt;Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"&gt;
    --&gt;
    &lt;Engine name="Catalina" defaultHost="localhost"&gt;

      &lt;!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) --&gt;
      &lt;!--
      &lt;Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/&gt;
      --&gt;        

      &lt;!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack --&gt;
&lt;!--      &lt;Realm className="org.apache.catalina.realm.LockOutRealm"&gt; --&gt;
        &lt;!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  --&gt;
&lt;!--        &lt;Realm className="org.apache.catalina.realm.UserDatabaseRealm"    resourceName="UserDatabase"/&gt;--&gt;
&lt;!--      &lt;/Realm&gt;--&gt;

      &lt;Host name="localhost"  appBase="webapps"   unpackWARs="true" autoDeploy="true"&gt;

        &lt;!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html --&gt;
        &lt;!--
        &lt;Valve className="org.apache.catalina.authenticator.SingleSignOn" /&gt;
        --&gt;

        &lt;!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" --&gt;

        &lt;Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/&gt;

      &lt;/Host&gt;
    &lt;/Engine&gt;
  &lt;/Service&gt;
&lt;/Server&gt;

</code></pre>
<p>As it turned out proxyPort property was the key to proxying  Tomcat via Nginx.</p>
]]></content:encoded>
			<wfw:commentRss>https://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
