Managing multiple network profiles using upstart

One of the purposes of buying the Jetway mini-top HBJC600C99-352-BW was using it as wireless router. I installed Ubuntu 11.04 on it. As NetworkManager does not handle wireless interfaces in access point (AP) mode, I decided to design my own network management. The idea is simple: use the required daemons/application and create upstart jobs to handle the activation logic. These are the network profiles I want to support:

  • WIFI: The htpc will connect to any known AP available.
  • ADSL: The htpc will connect to Internet via ADSL and act as a wireless router.
  • 3G: The htpc will connect to the Internet via 3G and act as a wireless router.

List of applications I need to use:

  • upstart;
  • wpa_supplicant;
  • dhclient;
  • brctl;
  • ifconfig;
  • hostapd;
  • dhcpd;
  • pppd;
  • iptables;
  • dnsmasq.

To install the needed packages, type the application name in the terminal. Ubuntu will help you with package’s name.

There are thousand ways to do that using upstart, so let me list some constraints I kept in mind when designing the system:

  • Customized solution. I believe that generic solutions must be used only when you really need them. Every time you make something more generic you end up adding more logic, creating more corner cases and spending more time with use cases that you will NEVER face. Example of assumptions: my built-in ethernet port is eth0, my wireless interface wlan0 is NOT hotplug.
  • Always have a maintenance channel available. Shit happens, all the time. So independent of the network profile I choose I want some way to get a secure shell connection without connect a keyboard (that I don’t have) to the htpc.
  • One upstart job per long lived process. Among the applications listed above, some have short lifetime, i.e. they set some configuration and/or perform some action and finish. Others keep running until some orderly finish action. I decided that the formers don’t need to be a job, they can be run as pre or post scripts of other jobs.

1st step: Get rid of Ubuntu networking jobs.

I will manage my network stuff using only upstart jobs, so I don’t need network-manager and ifupdown utilities. So lets disable them:

root$ echo manual >> /etc/init/networking.conf
root$ echo manual >> /etc/init/network-interfaces.conf
root$ echo manual >> /etc/init/network-manager.conf
root$ echo manual >> /etc/init/networking.conf
root$ echo manual >> /etc/init/bridge-network-interface.conf

Now, we need a job to raise the loopback interface. The following job is completely based on the Ubuntu’s network-interface job:


start on net-device-added INTERFACE=lo
stop on net-device-removed INTERFACE=lo

pre-start script
    mkdir -p /var/run/network
    ifconfig lo up
    initctl emit -n net-device-up IFACE=lo LOGICAL=lo
                                  ADDRFAM=inet METHOD=loopback
end script

post-stop exec initctl emit -n net-device-down IFACE=lo LOGICAL=lo
                                               ADDRFAM=inet METHOD=loopback

As upstart will run and take care of all daemons listed above, we must disable the sysinit scripts that start/stop them (that ones in /etc/init.d).

root$ update-rc.d -f hostapd remove
root$ update-rc.d -f isc-dhcp-server remove
root$ update-rc.d -f dnsmasq remove

2nd step: create mutually exclusive jobs to set the network profile.


stop on (starting net-profile-adsl
         or starting net-profile-wifi)
# the 'start on' below means "i'm the default profile"
start on (local-filesystems
          and net-device-added INTERFACE=wlan0
	  and net-device-added INTERFACE=eth0)


stop on (starting net-profile-3g
         or starting net-profile-wifi)


stop on (starting net-profile-3g
         or starting net-profile-adsl)

The main ideia of this arrangement is to change the profile using a single command. For instance, if somehow my adsl connection become unavailable I just need to connect my cell phone to the htpc and run the following command:

root$ start net-profile-3g

To reach this goal, all the following jobs will depend on this set of “fake” jobs as you can see in the next steps.

3rd step: set-up the bridge

First, the question. Why do I need a bridge? It’s because I have a printer connected to the htpc via ethernet. As I only have one built-in ethernet port I bought a usb-ethernet adapter (eth1). So, every time the htpc is running the 3g or adsl profile, I want wlan0 and eth1 in a bridge to route the connection to them. I can even say that everytime I plug-in the usb-ethernet adapter, I want dhcpd sending valid IP addresses to it (do you remember that I want a ssh access anytime?). The solution that I chose:

  1. The bridge (br0) will be set up at startup time and dhcpd will be configured to manage this interface
  2. Whenever the usb-ethernet is plugged in, its interface will be added to the bridge
  3. Every time ADSL or 3G profiles are chosen, wlan0 will also be added to the bridge


start on started loopback
stop on stopping loopback

pre-start script
    brctl addbr br0
    ifconfig br0 netmask broadcast
end script

post-stop script
    ifconfig br0 down
    brctl delbr br0
end script


start on net-device-added INTERFACE=eth1
stop on net-device-removed INTERFACE=eth1

pre-start script
    ifconfig eth1 up
    brctl addif br0 eth1
end script
post-stop exec brctl delif br0 eth1


start on started bridge
stop on stopping bridge

exec dhcpd -f

Note that the configurations above do not show when the wlan0 interface is added to the bridge. It will be covered in the next steps. Do not forget to change /etc/default/isc-dhcp-server in order to make dhcpd manage the br0 interface. Also, you need a valid configuration in the /etc/dhcp/dhcpd.conf. I will show my config below:

ddns-update-style none;

option domain-name-servers;

default-lease-time 600;
max-lease-time 7200;


log-facility local7;

subnet netmask {
  option routers;

4th step: managing wlan0 when the WIFI profile is chosen

Basically I need wpa_supplicant and dhclient running on wlan0 interface. Also, I need to keep wlan0 out of the bridge. Dumping the config:


start on started net-profile-wifi
stop on stopping net-profile-wifi

exec wpa_supplicant -iwlan0 -Dnl80211 -c/etc/wpa_supplicant.conf


start on started wpa_supplicant
stop on stopping wpa_supplicant

exec dhclient -d wlan0

emits net-device-up
emits net-device-down

post-start exec initctl emit -n net-device-up IFACE=wlan0 LOGICAL=wlan0
                                              ADDRFAM=inet METHOD=dhcp
pre-stop script
    ifconfig wlan0
    initctl emit -n net-device-down IFACE=wlan0 LOGICAL=wlan0
                                    ADDRFAM=inet METHOD=dhcp
end script

Note that you need a valid /etc/wpa_supplicant.conf file in order to be able to connect to a known AP. I don’t think I need to paste my config here. If you have any doubts run ‘man wpa_supplicant.conf’.

5th step: managing wlan0 when either 3G or ADSL profiles are chosen

I only need to launch hostpad and to add wlan0 to the bridge (br0). The job configuration:


start on (started net-profile-3g
          or started net-profile-adsl)
stop on (stopping net-profile-3g
         or stopping net-profile-adsl)

exec hostapd /etc/hostapd.conf

post-start script
    while [ "`iw wlan0 info | grep type | cut -d ' ' -f 2`" != "AP" ]; do
        sleep 0.5
    brctl addif br0 wlan0
end script
pre-stop exec brctl delif br0 wlan0

Note how wlan0 is added to the bridge. The current solution is a ugly hack that I’m planning to improve further… The problem is that a wireless interface in ‘managed mode’ cannot be added to a bridge. So when I move from WIFI profile (the wlan0 is in managed mode) to 3G or ADSL profile (wlan0 is in master mode), the brctl addif command fails. The reason is that hostapd daemon does not have enough time to set the master mode before its own post-start script runs.

Lets remind you again about valid configuration files… My wireless device uses ath9k kernel driver and below I’m pasting my hostapd.conf






6th step: managing ppp0 interface when either ADSL or 3G profiles are chosen

I only need to call pppd with the desired profile and create a NAT using iptables. There are bare differences between 3g and adsl pppd jobs as you can notice below:


start on started net-profile-adsl
stop on stopping net-profile-adsl

emits net-device-up
emits net-device-down

pre-start exec ifconfig eth0 up

exec pppd call gvt

post-start script
    iptables -t nat -A POSTROUTING -s -o ppp0 -j MASQUERADE
    iptables -A FORWARD -s -o ppp0 -j ACCEPT
    iptables -A FORWARD -d -m conntrack
                --cstate ESTABLISHED,RELATED -i ppp0 -j ACCEPT
    initctl emit -n net-device-up IFACE=ppp0 LOGICAL=ppp0
                                  ADDRFAM=inet METHOD=ppp
end script

pre-stop script
    iptables -F
    initctl emit -n net-device-down IFACE=ppp0 LOGICAL=ppp0
                                    ADDRFAM=inet METHOD=ppp
end script

pre-start exec ifconfig eth0 down


start on started net-profile-3g
stop on stopping net-profile-3g

emits net-device-up
emits net-device-down

exec pppd call vivo3g

post-start script
    iptables -t nat -A POSTROUTING -s -o ppp0 -j MASQUERADE
    iptables -A FORWARD -s -o ppp0 -j ACCEPT
    iptables -A FORWARD -d -m conntrack
                --cstate ESTABLISHED,RELATED -i ppp0 -j ACCEPT
    initctl emit -n net-device-up IFACE=ppp0 LOGICAL=ppp0
                                  ADDRFAM=inet METHOD=ppp
end script

pre-stop script
    iptables -F
    initctl emit -n net-device-down IFACE=ppp0 LOGICAL=ppp0
                                    ADDRFAM=inet METHOD=ppp
end script

Important notes:

  • My adsl modem is in bridge mode and connected to eth0 port.
  • GVT is my adsl provider name and Vivo3G is my 3G operator name :)

Configs to adsl connection:


user "turbonet@turbonet"
plugin eth0
remotename gvt
ipparam gvt

Add the following line to /etc/ppp/pap-secrets

"turbonet@turbonet" gvt "gvt25"

Configs to 3G connection:


connect "/usr/sbin/chat -v -f /etc/chatscripts/vivo3g"
user "vivo"
remotename vivo3g
ipparam vivo3g


'' ATZ
OK "ATDT*99#"

Add the following line to /etc/ppp/pap-secrets

"vivo" vivo3g "vivo"

7th (and last) step: Setup local dns server

To configure the htpc to run as a name server, I’m using dnsmasq:


start on started loopback
stop on stopping loopback

exec dnsmasq -k -u dnsmasq -7 /etc/dnsmasq.d,.dpkg-dist,.dpkg-old,.dpkg-new



If you want to use dnsmasq locally, add this line to your /etc/dhcp/dhclient.conf

prepend domain-name-servers;

That’s all. This setup is not fully tested (stressed). If you read/applied this and have some suggestions, please reply here :)


New gadget!

I was looking for a computer with following features:

  • Act as a wireless router
  • Act as a multimedia center (1080p)
  • Quiet
  • Low power consumption

After some research, I chose the Jetway Mini-Top HBJC600C99-352W-BW.

Software solution: Ubuntu 11.04 + XBMC. The installation has worked out of the box, no main issues. XBMC standalone is launched by default. Nice job xmbc team!!! The software is awesome.

In the following posts I will show how I customized Ubuntu to make it fit my requirements :)

Comments (7)

Linux Collaboration Summit – MeeGo Workgroup

Hey all,

It was a great time in San Francisco last week when I attended the Linux Collaboration Summit.

Presentations from key people of big companies (there were also summit sponsors) fulfill the first day agenda.

I highlight Intel and Nokia presentations, both showing what they want with Meego and both emphasizing the collaborative and open source aspects of the project. Of course the “paradox” of being open and possibly include closed components were source of some questions that the speakers tried to answer, but somehow I feel that some people didn’t get satisfied. The answer is simple in my point of view: products may need more code then Meego provides. Meego could avoid vendors to add closed code to Meego based products by a pedantic licensing scheme but it may be harmful to a project that is just launching and that has a competitor that allows proprietary code to be added. Meego already sees that open source is the way to best quality products, this is very good. Now the vendors that must follow the same way…

In the second day the Meego workgroup!

Firstly, the obvious that everybody says after a conference: very nice to assign faces to nicknames, very nice to have opportunity to answer the questions you have directly to the right person and very nice to do networking.

There were no news in the presentations but the talks were very productive in a way that lot of questions were raised and answered by the speakers like that the Qt will be more than a UI toolkit to become the application toolkit, acting as an interface to access the device resources. There was the nice talk from Marcel also about the connectivity part followed by the technical panel with architects from Nokia and Intel.

I could not forget to say that San Francisco is a very nice city, lot of places to visit, nice weather.. impossible to refuse to take some hours to visit touristic places there!

Well, I just want to say that was very nice to be part of this event! Looking forward next year ;)

Comments (1)

Frases soltas sobre a Finlândia

Estou em Tampere desde o dia 02/11. Após mais de 20 dias acho que já tenho algumas frases pra deixar aqui…


  • Oito horas de (sol) claridade por dia quando eu cheguei, agora já está das 9:10am até 3:20am.
  • Mais uma vez tive a felicidade de ver neve e de ver nevar. É muito massa botar a lingua pra fora pra pegar os flocos.
  • Todos os moradores aqui reclamam muito dessa época do ano pois não tem neve! Sim, como está muito escuro por boa parte do dia, a neve ajuda a deixar a cidade mais clara, já que ela reflete bastante a luz (nem que seja a dos refletores).

Eu: “Caramba… tá ZERO graus hoje!!”
R: “É… tá quente até, ainda bem né? Você não chegou no inverno forte.”
Eu: “Err… e frio é quanto?”
R: “Ah! Chega a -20″


  • Sauna é como futebol no Brasil. O primeiro apartamento que fiquei tinha 34m2 e acreditem, tinha uma sauna. Mas depois de um tempo percebi que, na verdade, ter sauna em casa não é algo que se encontre em casas mais simples.
  • Brincar de frio-quente. Eles adoram. Por exemplo algo bem comum aqui é ficar de 10 a 15 minutos numa sauna de 80 oC e depois pular num lago abaixo de 4 oC, daí eles nadam um pouco e voltam pra sauna. Quer tentar?


  • O primeiro choque: durante o almoço, percebi que 80% das pessoas tomam leite junto com o prato de comida. Sim, como se fosse suco. Explicação: eles precisam de cálcio dado que o sol não é um cara que costuma aparecer muito por aqui.
  • Suco natural: não achei.
  • Batata, batata, batata e mais batata. O cúmulo foi um prato que comi que tinha batata assada e batata frita de guarnição.
  • Carnes diferentes: já comi ovelha num restaurante estilo Viking e rena (sim, a do papai Noel) aqui do lado de casa.
  • Comi caviar :) Bléééééééé :(
  • A comida é um bocado gordurosa.


  • Kiitos‘ é obrigado, ‘hei‘ é oi, ‘hei hei‘ é tchau informal e ‘katu‘ é rua. Pronto, você sabe tanto finlandês quanto eu.
  • Todo nome de rua possui katu no fim. Eu já fiquei num apartamento na Mustalahdenkatu e agora estou num apartamento na Yliopistonkatu. Tenta falar aí…
  • As vogais tem o som muito parecido com o português. Isso ajuda na hora de falar nomes das lojas e ruas. Se bem que tem algumas vogais a mais aqui, e pra pronunciar… é difícil.
  • Em Tampere o inglês é mais comum entre os jovens. É razoavelmente fácil achar um idoso que não fala nada ou quase nada de inglês.


  • Eu nunca me considerei um cara alto. Mas aqui algumas vezes tenho a impressão de ser baxinho.. realmente estranho.
  • A carga horária diária na Finalândia, na média, é de 8h. Dentro desse tempo eles tem 30min de almoço.
  • O pessoal aqui curte beber. É muito comum achar pessoas cambaleando pelas ruas de madrugada. Além disso, as ruas principais da cidade ficam imundas durante o “período das baladas”. E acreditem, no dia seguinte as ruas estão completamente limpas. Algum milagre acontece no fim da madrugada…

Fotos em

Comments (2)

Ensuring SSD alignment with parted tool

I’ll show how to partition your SSD Vertex disk keeping the desired alignment to SSD erase block size. The following links were useful to point me that align partitions increase the SSD performance and how to complete the first part of the Journey to set up my Ubuntu+MacBook Pro+Vertex SSD.

You would ask me why don’t follow Ted’s post to make my partition table. Basically because I don’t want to use LVM. There is another important difference between our scenes: he has a Intel SSD with 128KB erase block size and I have a OCZ Vetex SSD with 512KB erase block size and of course it makes difference in the calculations.

Let’s start

$ sudo parted
(parted) unit b

The ‘unit’ command is very important because it makes the ‘print’ command show the start/end partition boundaries in bytes (and not in MB, GB or whatever).

This is my current partition table:

(parted) p
Model: ATA OCZ-VERTEX (scsi)
Disk /dev/sda: 128035676160B
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Number  Start         End            Size          File system  Name                  Flags
1      20480B        209735679B     209715200B    fat32        EFI System Partition  boot
2      209735680B    37656481791B   37446746112B  hfs+         Untitled
3      37656985600B  48393879551B   10736893952B  ext4         primary               boot
4      48393879552B  128035323903B  79641444352B  ext4         primary

Now, the very first question: How can I see that the partitions are aligned?

Good one. You just need to ensure that the boundaries can be divided by “erase block size” (EBS). In my case, the Vertex EBS is 512KB (= 512 * 1024B). Getting the 3rd partition as instance: 37656985600 / (512 * 1024) = 71825 (and no rest), so the begining of this partition is aligned.

How did I get this value?

  1. Get the end boundary of the second partition (37656481791)
  2. 37656481791 / (512 *1024) = 71824.04
  3. Get the non-decimal part +1 (71825)
  4. 71825 *512 * 1024 = 37656985600

So you have the aligned start address of your 3rd partition.

Note that to have a aligned end address, you need to choose a partition size that can be divided by 512KB as well, I’ve chosen 10736893952 (~10GB).

The end address in this case is  37656985600 + 10736893952 – 1 = 48393879551

Below you have the parted command to create the partition:

(parted) mkpart primary 37656985600 48393879551

In the same way I calculated the 4th partition boundaries (/home)

(parted) mkpart primary 48393879552 128035323903

Note that I lost some KB between the 2nd and 3rd partition and at the end of the disk. It’s normal as the second partition is not aligned (maybe MacOS is not prepared to SSD yet?).

I also marked the 3rd partition as bootable:

(parted) toogle 3 boot

And it’s done. The next post will show how to install Ubuntu Jaunty using a customised mkfs.ext4 command.

Comments (6)

Macbook Pro 5,1 + OCZ Vetex 120GB + Ubuntu

I’ve just finished.

After buy a SSD Vertex, I finally get my whole system working and now I can say: it’s not hard, it’s tricky. I’ll write some posts to let my efforts registered and maybe help someone to get the same success.

First of all, why did I buy a SSD?

I’m addicted to I/O performance. Actually this is the only reason. I could say that I want to improve the build time of Mamona, (and actually this is one nice reason), but in the truth, I just want to play with some of that toys ;)

Firmware upgrade and MacOS install

I’ve read some posts before get the SSD and I knew that a firmware upgrade was needed. The following link was enough to point me the instructions.

NOTE: The boring part was to find a desktop computer… I didn’t try the iso from OCZ in a Mac machine (and I can bet that it wouldn’t work).

The MacOS installation went flawlessly, no problems at all. I need to highlight the migration system. I just plugged my “old” disk in the USB port and bingo: users, configuration and files migrated to the new disk. Apple++.

Before the Linux installation, the finding…

… Ubuntu was not prepared to SSD disks. Well, it works without hacks. But if you want to get all the performance your disk has (remember my reason to buy it?) you need to make some adjustments to your Ubuntu Jaunty.

I won’t post everything together in the same post. The following posts (in HOWTO format) will show how I made these adjustments in my Ubuntu.

I can divide the whole process in four parts:

  1. Ensuring the partition alignment;
  2. Installing Ubuntu with a customized mkfs.ext4 command;
  3. Solving random freezes;
  4. Make Broadcom 4322 wireless work in the 2.6.30 kernel.

After these posts, I want to prepare one about the SSD performance compared to the original MacBook Pro 7200 rpm disk.

Comments (2)

Avoiding conflict with Scratchbox

We noticed that many people are giving up to try Mamona due to 2 reasons:

  1. We were requesting the user to install a qemu compatible version.  Of course this can bother people that use Scratchbox or another emulated system. Even Scratchbox has its own qemu you need to register the right interpreter on kernel through binfmt_misc and this registration is system-wide.
  2. There were many scritps to set/fetch/setup Mamona stuff and the help was distributed in many pages. All of this scripts were located (hidden) in tool.git repository and the documentation was a set of small pages with pointers between them asking for a “segmentation fault” :D

So we decided to make the things easier to the user creating mamona-installer.  It includes all Mamona scripts, our own qemu-arm static binary and do the dependency track. You just need to get the deb, rpm or tarball package and install Mamona.

The installer includes mamona-cputransp script to easily switch between qemu-arm interpreters in your system. Now you can have Mamona and Scratcbox in your machine and use them  one at a time.

The mamona-installer is included in our just released Mamona 0.2!!! Wooow!! See our Release Notes and enjoy our completely rewritten documentation :)

Suggestions and bugs, please report to us!


Mamona SDK pre-release!!!!

We’ve published the repositories of Mamona SDK 0.2Pre-release!!!!

Follow the instructions to install and use the SDK. If you have any doubts or bug reports:

  • mail list (mamona-devel <at> garage <dot> maemo <dot> org )
  • #mamona at freenode

The following machines are supported: Nokia770, Nokia800, Nokia810 and Omap3430sdp.

We divided the work in three parts:

  1. SDK itself: Our SDK was a little abandoned… The first thing we did was re-test it, fix the bugs and improve the script to install and enter into the chroot environment.
  2. SDK noemu: The no emulated packages are statically i386 binaries that improve the SDK performance, mainly the build time. After some tests bash, gcc and binutils were chosen to figure the noemu metapackage. We made a wiki page with instructions and some comparison tests.
  3. Xephyr: Finally we decided to add this functionality to Mamona. Now we can test GUI programs without flash the device.

Try it!

Comments (5)

Midori, Firefox 3, Beagleboard and Mamona

Lets welcome and  Eduardo Valentin! The new comers are working from INdT Manaus site and they already achieved GREAT results! Thanks guys!

The news:

Enjoy the links!

What’s next?? SDK and Network daemon. Mamona 0.2 is coming…

Comments (2)

Virtual Keyboard in Mamona

- I got Mamona 0.1 and it boots up!!! But… How can access the terminal?
- You can’t, there is no terminal..
- Bad.. but why?
- There is no virtual keyboard.
- And how can I play with Mamona?
- USB serial, USB net, …

Yeah, as you can see, we actually were providing a way to use Mamona on N(77|80|81)0 devices.But of course we weren’t happy with this… Mamona 0.2 couldn’t be released without this feature. And now it’s done.

A research work was made by Lauro and Salveti by testing some vkbds under Enlightenment and without WM (just X). The guys decided to create the mamona_im (git web) implemented by Salveti that “notice” that a text field has the cursor and request the vkbd to appear. The ecore and gtk plugins were created to this library to support text fields from these toolkits.

The virtual keyboard chosen is matchbox-keyboard (mkbd) because it’s simple and toolkit independent. We planned to place the keyboard at screen bottom (1/3 of screen height), horizontally maximized, without decorations  (border and title bar), and owning the desktop area that it is placed ( I mean other windows doesn’t use this area when maximized). Beyond this we needed to fix some bugs of mkbd (crazy resize, ‘shift’ bug – keys weren’t working with shift and placement just after launch).

I experienced some troubles with Enlightenment too. They have some different concepts of how a desktop should be and so they don’t follow some freedesktop standards. For instance the _NET_WORKAREA X hint (inform the current desktop area) is not set by e-wm because (1) it limits the workarea in a square shape and (2) e-wm manage vdesktops of different sizes. Thanks to E guys that helped me to understand this. :) In the end I added a patch to get the screen size from Xlib, it was enought.

Finally it’s  done!  It was tested on N770 tablet and we’re testing it on N800 and N810, actually it should work in all tablets. Take a look in the results in the demo recorded by Salveti (take a look in his feed about mamona vkbd too).