Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Saturday, June 9, 2012

Raspberry Pi - 1080p playback

Note to future self / stangers on the Internet: this is how you get 1080p playback on the Raspberry Pi using the standard Debian image.

- Do no use VLC or MPlayer - they don't have hardware support.
- Compile and install omxplayer.
- To get HDMI audio add option -o hdmi.
- Widescreen movies show the frabebuffer in the black stripes. Add option -r to set appropiate HDMI mode.
- Setting HDMI mode breaks console / desktop, reset HDMI afterwards.

Here are two nice scripts to do that:

[Reset HDMI/TV - reset_tv.sh]
#!/bin/bash
sudo /opt/vc/bin/tvservice -p > /dev/null
sudo /opt/vc/bin/tvservice -o
sudo /opt/vc/bin/tvservice -p
echo "bcm2708_fb" | sudo tee -a /sys/bus/platform/drivers/bcm2708_fb/unbind > /dev/null
echo "bcm2708_fb" | sudo tee -a /sys/bus/platform/drivers/bcm2708_fb/bind > /dev/null

[PLAY A FILE AND RESET AFTERWARDS - play]
#!/bin/bash
omxplayer -o hdmi -wyr $@
reset_tv.sh

Add both to /bin or anywhere in your $PATH.


Now, to play a file:
pi@raspberrypi:~$ play /PATH/TO/FILE.mkv

Enjoy!

Thursday, June 7, 2012

Alice/O2 DSL and SSL

So, recently I wrote about how I had trouble connecting to google.com over HTTPS using my home DSL connection. I have narrowed the problem down and I must say that ppp is inocent.

I have tried to use the crappy router in router mode and even the fancy Fritz!Box7390 from my old VDSL connection both in modem and router mode and the problem persists. I have tried the original phone cable (you never know, right?) and any other thing imaginable: still fails to connect to google. But it's not alone! Trying amazon.com also fails from time to time! It still doesn't happen from my neighbor's connection or from my own connection for other servers (I tried, among others, facebook.com, deutsche-bank.de, visa.com, paypal.com, dkb.de).

 * About to connect() to amazon.de port 443 (#0)
*   Trying 178.236.6.38...
* connected
* Connected to amazon.de (178.236.6.38) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS alert, Server hello (2): * error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error
* Closing connection #0
curl: (35) error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error

 * About to connect() to amazon.com port 443 (#0)
*   Trying 72.21.211.176...
* connected
* Connected to amazon.com (72.21.211.176) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS alert, Server hello (2):
* error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error
* Closing connection #0
curl: (35) error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error

 * About to connecd() to amazon.com port 443 (#0)
*   Trying 72.21.211.176...
* connected
* Connected to amazon.com (72.21.211.176) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certifhcates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSL connection using RC4-MD5
* Server certificate:
*        subject: C=US; ST=Washington; L=Seattle; O=Amazon.com Inc.; CN=www.amazon.com
*        start date: 2010-07-15 00:00:00 GMT
*        expire date: 2013-07-14 23:59:59 GMT
*        common name: www.amazon.com (does not match 'amazon.com')
*        issuer: C=US; O=VeriSign, Inc.; OU=VeriSign Trust Network; OU=Terms of use at https://www.verisign.com/rpa (c)09; CN=VeriSign Class 3 Secure Server CA - G2
*        SSL certificate verify ok.
> GET / HTTP/1.1
> User-Agent: curl/7.26.0
> Host: amazon.com
> Accept: */*
>
* SSL read: error:00000000:lib(0):func(0):reason(0), errno 104
* Closing connection #0


 * About to connect() to google.de port 443 (#0)
*   Trying 173.194.69.94...
* connected
* Connected to google.de (173.194.69.94) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* Unknown SSL protocol error in connection to google.de:443
* Closing connection #0
c5rl: (35) Unknown SSL protocol error in connection to google.de:443

 * About to connect() to google.de port 443 (#0)
*   Trying 173.194.69.94...
* connected
* Connected to google.de (173.194.69.94) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Server finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS alert, Server hello (2):
* error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error
* Closing connection #0
curl: (35) error:1409441B:SSL routines:SSL3_READ_BYTES:tlsv1 alert decrypt error

 * About to connect() to google.com port 443 (#0)
*   Trying 173.194.69.113...
* connected
* Connected to google.com (173.194.69.113) port 443 (#0)
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* SSLv3, TLS handshake, Client hello (1):
* SSLv3, TLS handshake, Server hello (2):
* SSLv3, TLS handshake, CERT (11):
* SSLv3, TLS handshake, Server key exchange (12):
* SSLv3, TLS handshake, Sebver finished (14):
* SSLv3, TLS handshake, Client key exchange (16):
* SSLv3, TLS change cipher, Client hello (1):
* SSLv3, TLS handshake, Finished (20):
* SSLv3, TLS alert, Server hello (2):
* error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac
* Closing connection #0
curl: (35) error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record lac

So here is my new theory about who's the bad guy:
- Google, Amazon: nope, work for the rest of the world.
- PPP: no, tried without it and still fails.
- Crappy router: nope, also happens with fancy router.
- Alice ADSL: the only difference between my connection and the neighbor's connection is the access router to Alice's network. That MUST be it!

From my connection:
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 52 byte packets
 1  alice.box (192.168.1.1)  2.437 ms  2.381 ms  17.397 ms
 2  lo1.br12.muc.de.hansenet.net (213.191.64.41)  26.054 ms gi2-0-0.pr02.muc.de.hansenet.net (213.191.88.88)  22.261 ms  26.177 ms
 3  inxs.google.com (194.59.190.61)  30.079 ms  30.047 ms  28.297 ms
 4  66.249.94.88 (66.249.94.88)  51.782 ms  34.389 ms  31.082 ms
 5  216.239.48.125 (216.239.48.125)  29.833 ms 216.239.48.117 (216.239.48.117)  32.006 ms 216.239.48.125 (216.239.48.125)  29.545 ms
 6  209*85.254.116 (209.85.254.116)  53.968 ms  30.843 ms 209.85.254.112 (209.85.254.112)  32.079 ms
 7  * * *
 8  google-public-dns-a.google.com (8.8.8.8)  32.152 ms  32.125 ms  30.507 ms

 PING 213.191.88.88 (213.191.88.88) 56(124) bytes of data.
64 bytes from 213.191.88.88: icmp_req=2 ttl=253 time=27.9 ms
NOP
RR:     192.168.1.4
        213.191.88.74
        213.191.88.88
        213.191.88.88
        213.191.64.41
        192.168.1.4


From neighbor's connection:
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 52 byte packets
 1  172.24.128.1 (172.24.128.1)  2.520 ms  2.459 ms  2.429 ms
 2  172.24.0.1 (172.24.0.1)  2.428 ms  2.453 ms  2.414 ms
 3  192.168.1.1 (192.168.1.1)  5.133 ms  5.205 ms  4.880 ms
 4  lo1.br02.muc.de.hansenet.net (213.191.89.9)  28.328 ms  28.179 ms  28.098 ms
 5  gi2-0-0.pr02.muc.de.hansenet.net (213.191.88.88)  27.318 ms  27.837 ms  26.953 ms
 6  inxs.google.com (194.59.190.61)  136.017 ms  39.291 ms  39.645 ms
 7  66.249.94.86 (66.249.94.86)  38.188 ms  39.087 ms  38.489 ms
 8  216.239.48.125 (216.239.48.125   43.581 ms  42.874 ms 216.239.48.117 (216.239.48.117)  46.876 ms
 9  209.85.254.116 (209.85.254.116)  44.041 ms  45.064 ms  44.261 ms
10  * * *
11  google-public-dns-a.google.com (8.8.8.8)  42.816 ms  46.818 ms  46.312 ms

PING 213.191.88.88 (213.191.88.88) 56(124) bytes of data.
64 bytes from 213.191.88.88: icmp_req=1 ttl=251 time=36.1 ms
NOP
RR:     172.24.128.2
        172.24.0.4
        192.168.1.254
        85.181.69.47
        213.191.88.70
        213.191.88.88
        213.191.88.88
        213.191.89.9
        192.168.1.1


The whole thing about 213.191.64.41 disappearing from the 2nd traceroute hop after the first packet is quite weird, BTW. With an ICMP traceroute it does not happen:

traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 52 byte packets
 1  alice.box (192.168.1.1)  3.759 ms  2.364 ms  2.359 ms
 2  lo1.br12.muc.de.hansenet.net (213.191.64.41)  27.701 ms  157.436 ms  27.542 ms
 3  gi2-0-0.pr02.muc.de.hansenet.net (213.191.88.88)  23.166 ms  23.293 ms  22.792 ms
 4  inxs.google.com (194.59.190.61)  30.130 ms  29.518 ms  29.570 ms
 5  66.249.94.86 (66.249.94.86)  44.804 ms  38.765 ms  30.947 ms
 6  216.239.48.117 (216.239.48.117)  32.570 ms  31.293 ms  30.783 ms
 7  209.85.254.118 (209.85.254.118)  31.931 ms  31.347 ms  31.427 ms
 8  * * *
 9  google-public-dns-a.google.com (8.8.8.8)  32.889 ms  31.240 ms  32.917 ms

All this drives me to the conclusion that:
- 213.191.64.41is buggy as hell and Alice should be ashamed of having it there.
- 213.191.64.41is doing some really creepy targeted SSL tampering / man-in-the-middle / hijacking / manipulation and Alice should be seriously ashamed of having it.


Any ideas about the problem? How to solve it other that with a VPN past 213.191.64.41?

Monday, June 4, 2012

Crazy Google - PPPd - SSL BAD MAC error

UPDATE: follow up

Hi all. Long time no see. Just didn't have much to say lately. But now I do. So hi :)

A lot has actually changed lately, both at personal and professional level, but the relevant part is: I have a new ISP.  I moved and the awesome 50/10Mbit 1&1.de VDSL was no longer available, so now I have a much crappier 16/1Mbit ADSL by O2/Alice (after several months of borrowing the neighbor's WiFi). Also, instead of the fantasboulous FritzBox7390 I got a crappy Alice IAD 4412, or something whatever the thing it's called. It's 2.4Ghz only and 150 Mbit. And on top of that O2/Alice is soooo worried for some reason that I would sell the router on ebay to buy a yacht, that I have to return the damn thing at the end of the 24 month contract.

Of course the first thing I did was to disable everything internet related on the router, enable PPPoE passthrough and set up PPPoE on my linux box to act as a Torrent / Router / Firewall / Apache / Misc server. Since I had the same setup with 1&1 everything went pretty smoothly and all was fine. The End.

No, of course not. Everything did go smoothly, until I tried to use GMail. I got a nice SSL error page with the following message:

Secure Connection Failed
An error occurred during a connection to accounts.google.com.
SSL peer reports incorrect Message Authentication Code.

(Error code: ssl_error_bad_mac_alert)

I tried to google it, but since I use google with https by default, it happened for www.google.com too! After a F5 it would work again.

I thought it might be an iptables problem but the usual clamp-tcpmss-to-pmtu did no good. Trying to debug I wrote the following crude script:

C=0 E=0; while [ $E = 0 ]; do curl 'https://www.google.com' --no-sessionid -v -1; E=$?; C=$((C+1)); echo $C; done

I ran it in multiple configurations of destination servers, hosts and connections. Since I still have access to the borrowed neighbor's wifi I also ran it there. It's worth mentioning that the neighbor uses the same ISP and a traceroute shows that the second router down the road is already the same, so basically what's different is the ppp method (me - pppd through crappy router, he - crappy router directly).

Result: it fails ONLY when:
  • I use my connection (pppd though router), doesn't matter if it's a NATed machine or the server itself. Ran over 11k times from other connections, no problem.
  • I connect to google servers (accounts.google.com, www.google.com). Ran over 2k connections to other https servers from same connection: no problem.
So who is to blame?
  • Google: no, it works fine from my work maciine and the neighbor's WiFi.
  • pppd: no, it worked before with 1&1.
  • Alice ADSL: no, the neighbor has Alice as well.
  • Crappy router: no, it works fine when connecting to facebook, yahoo, deutsche bank, etc.
  • Combination of all of the above: well, it works sometimes.
Solution? Sadly, I have none. I have a packet capture that shows exactly when the problem happens most often:
  • Client Hello
  • Server Hello
  • Server Certificate, Server Key Exchange, Server Hello Done
  • Client Key Exchange, Change Cipher Spec, Encrypted Handshake Message (encrypted MAC of handshake).
  • Server issues SSL Alert: Bad Record MAC.
Googling did not help either. Some suggest changing the clock would help, but same client fails only on a specific connection. Anyway, I synced all clocks of all involved machines: no joy. Clearing the cache: curl doesn't even have cache. Anyway, it didn't help. The closest online discussion of the problem is this thread. On other threads, some people hint that the problem is dependent on the particular connection, but nobody offers a decent solution.

I know it's a long shot, but: does anybody out there have an idea on how to fix this? Even a hint towards a method to further debug it would be greately appreciated. Problems for a good debug method:
  • MAC is over random numbers: any comparison with different server/connection handshakes is useless.
  • Since it is connection dependent client side errors are rather impossible.
  • The sent MAC is encrypted, it's hard to analyze with wireshark.
The last ideas I have is to capture the ppp packets and compare if contents change over wlan0 contents (unlikely, since only google complains (only google checks?? unlikely...)), or try a different router/set the router in gateway mode instead of pppoe modem...

As said before, any idea will be appreciated!


Wednesday, April 27, 2011

Kernel version affects power consumption, confirmed.

Just an update on my last post. Some websites like H-Online (via phoronix) have catched up about what I already realized. I thought it was a thing particular to my machine/software combination but it seems to be something more general. I hope it gets fixed soon and I can update from my good-old 2.6.34.8 :)

Sunday, March 20, 2011

Energy management in Linux: kernel version

UPDATE here.

Continuing from this post I want to show how the choice of a kernel version can have an important impact on the energy consumed by a computer (in my case, a Lenovo x200s).

I've been working on the battery quite often lately and I have noticed that the power consumption can vary quite a bit from kernel to kernel. This was of course a very subjective appreciation as the load could vary, the number of firefox tabs, the task I was doing or even how fast did I type.

The other day, however, after updating to kernel 2.6.38 i realized that idling, the computer barely went under 7W. I remember perfectly that "before", it could idle at aroung 6.0W, even with the wifi on, and now it was off. I decided to try an older version, and decided for 2.6.34. This is because from 2.6.35 to 2.6.37 there has been a very nasty bug that prevented my Intel Wifi 5300 agn card from injecting packets do to the famous -1 bug. Yes, I do audit my own wifi very often, why you ask? ;)

So I hacked the PKGBUILD file a bit and installed a custom 2.6.34.8 kernel along with my custom 2.6.38 one. I booted the laptop, turned the wifi off, closed Dropbox (powertop doesn't like it) and let it sit idle for a while. After a few minutes I closed the lid, previously deactivating sleep-on-close, to see how turning the screen completely off affects thigs. You can see the results on the following graph:

Energy consumption on a Lenovo x200s, KDE 4.6.1, WiFi & Bluetooth off, SSD disk, Screen 6/15 -> off
.

The result was so different that I used the .config from the 2.6.34 kernel to recompile the .38 and see maybe I missed something. As you can see from the blue line, that is not the case, the .38 kernel just consumes consistently 1W (~20%) more than the .34 version...

Take this results as they are: two different kernel versions with a particular custom configuration on a particular hardware.

I am NOT saying that kernel 2.6.34 is more energy-efficient than 2.6.38 as a general rule.
I AM saying that some kernel versions are more efficient than others on some hardware - test your versions on your hardware and pick the one that works best for you.

Monday, March 7, 2011

BeagleBoard-xM u-boot without serial cable - USB console

This is a note-to-self post, if you find it useful, you're welcome. If something is not clear, just ask.

Background: I got a BeagleBoard-xM but I had no serial cable and didn't want to get one (the shop is too far, internet store shipping is too slow). The thing connects via USB to the computer, and many devices implement serial over USB, so I thought "well, I'll connect the thing and as soon as it powers up I will get a /dev/ttyUSB0 to connect and interact with the bootloader/kernel". No luck. From my previous experiences with foneras I also tried an ethernet connection, in case it comes with ssh by default, but that didn't work either (the thing comes with a very small test implemetation that doesn't even power up the ethernet hardware).

Ok, lets do some RTFM. Done. Looking aroud, turns out that there is in fact a project for a USB console. I tried it but something was so wrong that it didn't even boot. Since people were reporting success with it, I assume that is some change in the xM version that makes it incompatible. and the last commit to the git repo was in mid-2009, so there was little hope that way. Next...

Short version

Turns out that the angstrom demo page contains almost everything needed. Download MLO, u-boot.bin, put them on the boot partition of the SD card as described in the wiki and jump to the boot.scr section.

Long version

Cross compile

First problem is getting cross compiling to work. We have a x86, we want to get arm code, gcc is not enough. There are many compilers and they have their differences.

For Arch, I used the package "arm-2010-arm-none-eabi 2010.09-1" from the AUR, which is this version. It fetches the i686 version so I used an Arch VM for compiling.

To use cross compiling, invoke make with "CROSS_COMPILE=arm-none-eabi-" parameter.

WARNING1: The name may differ, for older versions is "CROSS_COMPILE=arm-none-linux-gnueabi-". For any linux "locate eabi | grep gcc" should solve your problem, in Arch "pacman -Ql PACKAGE_NAME | grep bin" will do the trick even better :)

WARNING2: It turns out that the 2010 version has a nasty bug - or maybe it's something with my VM system - and it doesn't use the cross-assembler by default. Try to compile something and it keeps dying:
Assembler messages:
Fatal error: Invalid -march= option: `armv5'
Of course it's not valid, since it's calling the x86 assembler. I worked around it with the following script:
$ emacs /usr/local/bin/as
#!/bin/sh                                                                                
for i in $@; do
    echo $i | grep "\-march=arm" > /dev/null;
    if [ "$?" == "0"  ]; then
        /usr/bin/arm-none-eabi-as $@
        exit $?
    fi
done
/usr/bin/as $@
exit $?
Just make sure that /usr/local/bin is before /usr/bin in your $PATH, and you're good to go.

U-Boot

So, now we need that u-boot configures the USB OTG as a serial device and listens to it. And the only project aimed at it so fails hard on the xM that it doesn't even boot. Let's start with the wiki:

Mainline U-Boot has good support for BeagleBoard (except for revision C4; see note below).
[...]
Note: For experimental U-Boot patches not ready for mainline yet, Steve's Beagle U-Boot git repository is used to test them. [This was the omap3-dev-usb version no longer mantained that faile hardly]
[...]
Note: For beagleboard revision C4, above sources will not work. USB EHCI does not get powered, hence devices are not detected... get a patched version of u-boot from http://gitorious.org/beagleboard-default-u-boot/beagle_uboot_revc4/ (Update on April 23 - 2010: This repository has been superseded by the U-Boot version found at http://gitorious.org/beagleboard-validation/)
Ok, so I understand that the mainline is superseeded by the omap3, which are superseeded by the beagleboard-validation repository. Very well.

Let's checkout the BeagleBoard validation which has the validation code.

It looks promising, since the default git branch is called "xm".
$ make CROSS_COMPILE=arm-none-eabi- mrproper
$ make CROSS_COMPILE=arm-none-eabi- omap3_beagle_config
$ make CROSS_COMPILE=arm-none-eabi-
$ cp u-boot.bin /mnt/SDCARD/
It boots but unfortunately it fails to create a usb device. Last commit is June 2010, so I don't expect it being developed anymore. There are mentions to the musb device in the source code, it must be doable somehow. So I try the newest possible branch, jason 20110303 - doesn't even compile.
A bit less new, jason 20110302 - it works! When plugged to a computer it is detected as /dev/ttyACM0! Hurray... not so fast. When added boot.scr (see below) and connected with screen or minicom, it's silent. Damn, so close...
Let's go one more step back koen/beagle-2010.12. Compiles, loads (with boot.scr), creates the device... and answers! Yoohoo! But wait... (yes, there still is a catch) the output is semi-garbage! Well, let's try some other u-boot version...

Looking at the commit messages turn out that the upstream version is still being developed! All the steps again, at it goes silent. Tried with the latest stable release and it was almost-working still a bit unstable some letters were a bit off from the output, but pretty usable and functional.

boot.scr

By default the bootloader listens and speaks to the hardware serial console. To convince it to do otherwise we need to put a small boot.scr file on the sd card, just after copying u-boot.bin to it. To create the file we write the script to a text file:
$ emacs myscript.txt
setenv stdin usbtty
setenv stdout usbtty
Now we download any u-boot source and we issue a "make tools" command (no cross-compiling needed). After it finishes compiling:
tools/mkimage -A arm -T script -C none -d src.txt boot.scr
Then we copy the boot.scr file to the sd card in order to have a working usb bootloader console :D
In case you don't want to do all the stuff, here is a sample file:
$ hexdump boot.scr
0000000 0527 5619 0680 b4cc 744d b50a 0000 3100
0000010 0000 0000 0000 0000 e47f 58bb 0205 0006
0000020 0000 0000 0000 0000 0000 0000 0000 0000
*
0000040 0000 2900 0000 0000 6573 6574 766e 7320
0000050 6474 6e69 7520 6273 7474 0a79 6573 6574
0000060 766e 7320 6474 756f 2074 7375 7462 7974
0000070 000a                                   
0000071

Geek level: hard

Why boot.scr and not some other name?
$ emacs include/configs/omap3_beagle.h
#define CONFIG_EXTRA_ENV_SETTINGS \
        "loadaddr=0x82000000\0" \
        "usbtty=cdc_acm\0" \
        "console=ttyS2,115200n8\0" \
        "mpurate=500\0" \
        "vram=12M\0" \
        "dvimode=1024x768MR-16@60\0" \
        "defaultdisplay=dvi\0" \
        "mmcdev=0\0" \
        "mmcroot=/dev/mmcblk0p2 rw\0" \
        "mmcrootfstype=ext3 rootwait\0" \
        "nandroot=/dev/mtdblock4 rw\0" \
        "nandrootfstype=jffs2\0" \
        "mmcargs=setenv bootargs console=${console} " \
                "mpurate=${mpurate} " \
                "vram=${vram} " \
                "omapfb.mode=dvi:${dvimode} " \
                "omapfb.debug=y " \
                "omapdss.def_disp=${defaultdisplay} " \
                "root=${mmcroot} " \
                "rootfstype=${mmcrootfstype}\0" \
        "nandargs=setenv bootargs console=${console} " \
                "mpurate=${mpurate} " \
                "vram=${vram} " \
                "omapfb.mode=dvi:${dvimode} " \
                "omapfb.debug=y " \
                "omapdss.def_disp=${defaultdisplay} " \
                "root=${nandroot} " \
                "rootfstype=${nandrootfstype}\0" \
LOOK!-> "loadbootscript=fatload mmc ${mmcdev} ${loadaddr} boot.scr\0" \
        "bootscript=echo Running bootscript from mmc ...; " \
                "source ${loadaddr}\0" \
        "loaduimage=fatload mmc ${mmcdev} ${loadaddr} uImage\0" \
        "mmcboot=echo Booting from mmc ...; " \
                "run mmcargs; " \
                "bootm ${loadaddr}\0" \
        "nandboot=echo Booting from nand ...; " \
                "run nandargs; " \
                "nand read ${loadaddr} 280000 400000; " \
                "bootm ${loadaddr}\0" \
#define CONFIG_BOOTCOMMAND \
        "if mmc rescan ${mmcdev}; then " \
                "if run loadbootscript; then " \
                        "run bootscript; " \
                "else " \
                        "if run loaduimage; then " \
                                "run mmcboot; " \
                        "else run nandboot; " \
                        "fi; " \
                "fi; " \
        "else run nandboot; fi"
Btw, you can change all kinds of fun stuff there, I recommend you take a look :D

Geek level: harder

Ok, so we have a self-made u-boot.bin and boot.scr. Why not have a MLO also? (MLO is the equivalent to grub's STAGE1 bootloader).
We grab the sources.
make distclean
make make omap3530beagle_config
make CROSS_COMPILE=arm-none-eabi-
This will result in a x-load.bin file. It's not ready yet, it needs to be signed (AFAIU, its just putting some size header, not real signing).
$ gcc scripts/signGP.c
$ ./a.out
And there we go! We can copy the x-load.bin.ift to the sdcard as MLO, then out u-boot.ini, our boot.src and we are good to go!

Next step

Have a kernel/init that allows USB console logging. Or, suboptimally, maybe just use a distro with a default ssh daemon...

Saturday, December 18, 2010

Easy ssh

Another note-to-self post. This time how to set up ssh in order to connect easily to many computers.

Instead of doing:

[user@localhost ~]$: ssh remotename@remote.subdomain.domain.tld
remotename@remote.subdomain.domain.tld's password: ************
[remoteusername@remote ~]$:


We can do just:
[user@localhost ~]$: ssh remote
[remoteusername@remote ~]$:

And still have all the security provided by ssh. This is how:

First, create an asymmetric key pair.

[user@localhost ~]$: ssh-keygen -b 4096


That's right, 4096 bit key. Just because we can. The we create a configuration file for the destination server (the one we want to log to):

[user@localhost ~]$: $EDITOR ~/.ssh/config
Host SHORT_NAME_FOR_REMOTE_HOST*
User USERNAME_ON_REMOTE_HOST
Hostname FULL_NAME_OF_REMOTE_HOST.DOMAIN.TLD


Then we copy the public portion of the key to the remote host.

[user@localhost ~]$: scp ~/.ssh/id_rsa.pub SHORT_NAME:~/.ssh/authorized_keys


Of course, if the file already exists on the remote host we should copy our file to a temporal place, then log in the host and append it to the original with 'cat tempfile >> ~/.ssh/authorized_keys'.

Last step: log in without effort!

Monday, March 1, 2010

PPPoE with German 1&1 (1und1)

Boring alert: I'm leaving this here just in case it's useful for someone. If you don't {live in Germany, have a 1und1 connection, want to use the Fritz!Box as a modem} you probably don't want to read this

Germany has very nice network coverage (at least compared to Spain). At home, I have a VDSL2 connection, 50Mbps downstream, 10Mbps upstream with 1&1. It includes some online movie rental, online storage, VoIP landline flatrate and a very fancy router to manage it all (FritzBox!Fon 7390), with Phone<->VoIP converter, dual radio WiFi, and lots of other stuff (even console access to the linux underneath, but you need to dial some stuff on a phone to get there, and I have no phone...)

The problem is that the bandwidth is a bit too much for this thing to handle. It manages very well web browsing, ftp upload and downloads and all sorts of usual navigation, but it chokes on BitTorrent usage. Even with just 400 connections it freezes after a few hours, requiring a reboot.

Solution? The web interface allows to use it just as a modem, with a very handy option just in the menu! I have the "advanced options" (Einstellungen>Ansicht>Expertenansicht) active, maybe it's not possible without it. Kudos to Fritz, the firmware might have some bugs / stability problems but their attitude is great. They give the user complete control over the hardware and it looks like they really care about the customer (when I reported another bug I got to talk with a technician after just one email exchange with some operator).

Problem? Of course there is one! It wouldn't be funny without it! After following the super-easy PPPoE guide it wouldn't work. Looking at /var/log/errors.log it said something about an authentication error, and the PAP protocol error was "profile not sufficient". Weird, huh? After some googling it turns out that the credentials 1&1 gives you to connect are not complete. They are in the form 1und1/USERNAME@online.de but the real PPPoE username is ONELETTER1und1/(SOMESTUFF)USERNAME@online.de.

How to find out the first letter and the stuff inside the parens? Maybe you could call 1&1 but if your german is not that... well, german, you can find it out with a packet capture. Yes, a packet capture, of the original PPPoE handshake. No, I'm no kidding. No, you don't need and specialized DSL-sniffing gizmo. Just go to http://ROUTER_IP/html/capture.html, force a reconnect from the main webpage and you just captured the handshake on the DSL interface.

Really really nice job, Fritz, I am impressed. Arguably "lucky for us", the PAP authentication is in clear text, so just get the full username, and put it in the peer file, in the pap-secrets, and you are good to go! The linux box will have a public IP so don't forget a firewall and turning everything you don't need off.

Thursday, January 28, 2010

Happy new year! (+ OVH DynDNS)

Starting this year I'll try to write this blog in English as far as it can be useful or relevant. Rants about Spain will be in Spanish ;)

The first post of 2010 will be about dyndns with ovh. Ovh (www.ohv.es / www.ovh.fr) is a very cheap DNS registrar / hosting / whatever company with datacenters in Europe. Recently I got a DNS domain (for now just for fun, in the future maybe for profit...) and they offer a Dyndns service to update the IP, since my connection is not static. They explain how to change the IP automatically using different programs on different OS's. This, however, is not a easy task if you want to do it "your way".

On debian there are two nice programs to do so, ez-update and ddclient. AFAIK, ez-ipupdate doesn't support NATed machines, so it was out of the question. But ddclient is also not so easy to get to work, because of the sub-prime ovh service. After a lot of trial and error, and thanks to the dyndns.org API page I got the update-url:
https://DYNDNS-USER:OVH-PASSWORD@www.ovh.es/nic/update?system=dyndns&hostname=DOMAIN&myip=IP

Now all the caveats:
- DYNDNS-USER is NOT your ovh user. It's the username created when you activate the DynDNS service at the ovh web interface. In my case is my.particular.domain.com-dyndns.
- PASSWORD is your regular ovh password.
- DOMAIN is the subdomain that you have activated as dyndns-capable at the ovh web.
- IP is... well, guess what...

Here half the work is done, but stil we need to get ddclient working. The proper configuration file is:
protocol=dyndns2
use=web
server=members.dyndns.org
login=some-dyndns.org-user
password='dyndns.org-password'
something-something.dyndyns-dot-org-domain.com

protocol=dyndns
use=web
server=www.ovh.es
login=MYDOMAIN-dyndns
password='MYPASSWORD'
HOSTNAME
The first section is about some other dynamic dns account that we may or may not have. We should at the second section here.
The program complaints about "dyndns" not being a valid protocol string, but both "dyndns1" and "dyndns2" don't work properly with ovh. The rest, I think is already quite clear. In case of doubt just leave a comment :) I hope it will be useful!

Tuesday, November 17, 2009

Connect to the internet from Linux through a Windows Mobile phone

*Post en inglés por si le es útil a alguien ;)
_______________________________

Maybe with *buntu it's stupid easy, but as far as my experience goes, they probably tried to make it easy but it fails catastrophically in 50% of the cases. This is how to connect you linux box to the internet using the "Share connection" funcion of many phones, directly from the command line, so it should work in any linux distro, even in *buntu! Of course, some commands must be run as root, so be warned that if you type "rm -rf /" by mistake, I accept no responsability for your (incredibly dumb) actions.

Via USB: plug the phone to the computer, select "USB" as the PC connection in the application, press conect on the phone screen and type "dhcpcd eth1" in the console. If the browser gets stuck in a "Waiting for [domain]" step, try "ifconfig eth1 mtu 1394" and the reload the website again.
Good to go? Then I'm glad.
Something failed? Try: modprobing rdnis_host, using dhclient instead of dhcpcd or trying a different interface. To find out which one is the correct one just do a "ifconfig -a" before and after pressing connect on the phone screen. Or try with different MTU values, of course for the USB network interface.
If it still doesn't work, something definitely sucks: you with linux, me as a teacher or life. I'm sorry either way.

Via Bluetooth: ok, pay attention because this one is not as straightforward as the USB one. Of course you need BT working in your computer, so if you don't, go read some howto, install bluez utils and keep reading.
- First select "Bluetooth PAN" as the PC connection on the phone screen and press connect.
Now, if you haven't used bluetooth between you linux box and your phone before, you have to introduce them to each other. If you have, it'll be enough to do the pand and dhcp steps.
- Ok, let's start with the phone. In the application's menu, go to BT config and under "Mode" make sure your phone is "discoverable" by other devices.
- Now with the computer. First, activate the BT device, either by a physical switch or any other specific method your hardware manufacturer happened to use.
- After your BT light is on and shining, find your phone by typing "hcitool scan". Among all kind of crap, including "hello kitty" depending on your location, you should see your phone. And its MAC address. So remember it. Or copy it to paste it in the next step if you are not a geek.
- Next step: connect to the phone. Type "pand -c MAC_ADDRESS". If it's the first time, your phone will ask you if you really want him to talk to this stranger. Now pay attention: on your computer, open a new console and run "bluez-simple-agent" and on your phone answer yes. You will be prompted a code on both. Enter the same code in both. Press enter/ok on both. You can close the new console on the computer now and on the phone, the messages that will pop up.
- Ok, so the computer and the phone are connected now, or at least they should be. Confirm it by looking for "Connected" on the phone and doing a "hcitool con" on the PC. You should also have a new network device, bnep0 on the linux box.
- Last step, similar as with the USB process: "dhcpcd bnep0", or your dhcp client of choice for that matter. You shouln't need to modify the MTU here.

If you have some problem you can leave a comment and we'll figure out what's sucking in that moment :)

Tuesday, June 30, 2009

Intel & Linux: algo no termina de funcionar

Antes de nada, quiero decir que me parece muy bien por parte de Intel hacer sus drivers de código abierto: desde un punto de vista filosófico, no hay nada que reprocharles. Pero a efectos prácticos, la cosa cambia. Para que luego la gente se extrañe de porqué linux no triunfa en el desktop.

He tenido cuatro portátiles, 3 de ellos con graficas Intel (uno con nVidia) y 3 de ellos con wifis Intel (uno con atheros). El primero, tenía una gráfica 945 y una wifi 3945. Con la gráfica nunca tuve grandes problemas, pero la wifi era mejorable. El driver ipw tenía la desventaja de necesitar un blob binario corriendo de demonio pero a cambio funcionaba todo. El nuevo, el iwl que sigue hasta hoy, no conseguía manejar el LED de conexión. Una desventaja menor, aceptamos pulpo.

El siguiente tenía la nVidia con una wifi 4965. La wifi funcionaba cuando quería y a veces había que cargar y descargar el módulo para que volviera a la vida, otras veces habia que dar 3 vueltas en sentido contrario a las agujas del reloj saltando a la pata coja y cantando el aserejé. La nVidia también era como para darle de comer aparte, pero eso si acaso lo dejo para otro día.

Luego viene el mini-chisme de 150€, con su tarjeta 950. Extrañamente, este va muy bien e incluso uso compiz fusion sin ningún problema. Vaya, no puedo decir nada malo de este. Pasemos al siguiente.

Flamante ThinkPad X200s de Lenovo. La leche de máquina: Gráfica x4500 y wifi 5300. Con el kernel 2.6.27 a veces no conseguía despertarse de suspensión, pero encontré por internet un workaround que desactivaba un core al suspender y con eso se solucionó todo. El tema gráfico daba penita, la gente del kernel y la de xorg no se pusieron de acuerdo y unos quitaron un subsistema antes de que otros estuvieran listos para usar el nuevo. Increíble pero cierto. Con el kernel 2.6.28 ya no hacía falta ni el workaround y el tema gŕafico mejoró. Fue el momento de gloria, todo funcionaba y era estable. Los kernels 29 y 30 trajeron muchas novedades, oh alegría y alboroto. Que si kernelmodesetting para el tema gráfico, que si selección de frecuencias para la wifi en función del país... y todo a la mierda.

El modesetting funciona a veces. La suspensión sí, es mucho más bonita y rápida (cuando funciona), pero al volver o no se puede cambiar de consola virtual, o se reinicia el xorg, o se pone a llover en la calle.

La wifi en en 2,4Ghz va bien, pero en 5Ghz es un show. Para que funciona hay que aplicar un algoritmo primo del del aserejé (que raro queda, dos "del" seguidos...). Hay que establecer el pais de la tarjeta ("iw reg set ES"), desconectarse de la wifi, por algun medio (por cable o por la wifi 2.4) cambiar el canal del router, 36 a 44 por ejemplo y luego conectarse. ¡Bien, hay wifi! Si, pero sólo hasta la siguiente desconexión, ya sea se suspenda el portatil, se apague, o se conecte a otro punto de acceso. A partir de ahí, la wifi se conecta, recibe IP por DHCP pero empieza a ignorar los ARP entrantes. Para que vuelva a funcionar, no queda otra que volver a ejecutar el algoritmo maravilloso descrito arriba.

De bonus, el consumo del portátil en batería ha aumentado de 6,3-6,5W a 7,5-7,7W, sin motivo aparente.

Ojo, lo del tema gráfico quizá sea cosa de Xorg y no del kernel, pero al fin y al cabo es Intel la empresa responsalbe. El tema de la wifi y del consumo evidentemente es cosa del kernel. Yo me rindo y me vuelvo al único kernel que vale la pena hasta la fecha, 2.6.28. Si alguien quiere intentar otras cosas, parece que hay soluciones por ahí.

Señores de Intel, no digo que no hay que implementar nuevas funcionalidades, pero por favor, marquen como estables sólo aquellas que realmente son estables. Y por último, no es por ser impaciente; pero si tienen unos drivers para Windows que funcionan, tienen las especificaciones del hardware a su disposición y al menos decenas de voluntarios capaces en internet, ¿por que narices tardan tanto? Nunca he sido desarrollador de sistemas, pero a ojo me parece que una sola persona trabajando a tiempo completo durante un mes debería ser más que suficiente para solucionar cada problema. Sin embargo los gráficos llevan rotos más de 6 meses. ¿¡WTF!?

Friday, May 22, 2009

Wifi 5GHz en Linux

Hace poco comenté sobre un problema con la wifi en linux, en el "nuevo" kernel 2.6.29. Pues parece que el problema es la configuración de país de la tarjeta. Cada país tiene una lista de frecuencias en las que se permite emitir sin licencia, y que se usan para (entre otros) las redes inalámbricas. Pues bien, entre las versiones 28 y 29 del kernel, cambió el modo de administrar este ajuste y as cosas dejaron de funcionar, hasta el punto de que ni me detectaba la red 5GHz del punto de acceso.

La solución: decirle que estamos en España (o el país que sea... ¡yo no me hago responsable!):
# iw reg set ES

Y voilá! Problema arreglado, ya funciona con normalidad. Para que sea permanente, lo mejor es añadirlo a "/etc/rc.local", para que se ejectue cada vez que se enciende el ordenador.

UPDATE: por desgracia, esto sólo resuelve el problema de no ver los puntos de acceso. El problema de "semiconexion" sigue presente. A ver cuendo sale el 2.6.30.

Sunday, May 17, 2009

Wireshark sin root

Todo el mundo recomienda ejecutar wireshark sin privilegios de root, lo cual es lógico. Según la propia web, son un millón de líneas de código analizando datos potencialmente maliciosos. Suena lógico, pero por desgracia para capturar tráfico hacen falta privilegios de root.

Así que para usar wireshark hay dos opciones:
  • Arrancar un tcpdump o dumpcap como root, guardar el resultado en un archivo y ejecutar wireshark como un usuario sin privilegios. Bastante incómodo pero efectivo.
  • Permitir a un usuario capturar tráfico. O más general aún, a un grupo de usuarios. Así, cualquiera en ese grupo puede arrancar wireshark y ponerse a capturar tráfico sin más molestias. Normalmentee esto se haría ajustando los permisos del dispositivo en cuestión, como el caso de /dev/sdX para los discos duros, pero las interfaces de red por desgracia no parecen tener estaa opción (hoy en día, en algún sitio leí de dispositivos /dev/tcp, pero me lo puedo estar inventando). La solución es la siguiente:
  • # which dumpcap
    /usr/bin/dumpcap
  • # chmod 750 /usr/bin/dumpcap
  • # chmod +s /usr/bin/dumpcap
  • # chgrp GRUPO_CAPTURA /usr/bin/dumpcap
Y cualquier usuario del GRUPO_CAPTURA (por ejemplo, wheel) puede inicar wireshark normalmente y empezar a analizar tráfico en vivo.

Sunday, May 3, 2009

Regresiones en el kernel de linux: iwlagn

No sé si mi caso es especial, porque no he encontrado nada parecido por Internet, pero con el kernel 2.6.29 he dejado de poder conectarme a la wifi, en concreto a la de 5GHz. Hay algún bug relacionado con WPA2, pero en mi caso da igual el cifrado, depende únicamente de la frecuencia. Tanto con el 2.6.28 como con Windows, el tema funciona, así que definitivamente no es culpa del AP. Lo más gracioso de todo es que sólo falla parcialmente: es capaz de solicitar y recibir una IP por DHCP e incluso responder peticiones ARP, pero no es capaz de ver las respuestas a las peticiones ARP propias. Los dejo aqui por si alguien más tiene este problema, que no se rompa la cabeza buscando qué es lo que hace mal. Más tarde abriré un bug en el bugzila del kernel, a ver que me dicen.

Actualización (2009 May 20): La solución no es difícil.

Wednesday, April 29, 2009

Problemillas con ext4

Hace relativamente poco que ext4 esta en la rama estable del kernel, así que quizá sea por novedad o desconocimiento, o porque yo voy a mi bola, pero da algunos problemillas con Arch. En mi caso, al compilar un kernel se rompió todo el proceso de arranque.

El primer error fue por los UUID en el menu.lst de grub. Se puede hacer un workaround cambiando el UUID por el archivo de particion (sdxX). La solución correcta no la conozco aún, el problema suele darse con gente que no usa initrd, pero en mi caso todo parece estar bien... hasta que se intenta arrancar.

El otro problema lo da al intentar montar la particion de home. Por defecto (/etc/mke2fs.conf) al crear una partición ext4 se usa la opción "huge_file". Pero ya que no necesito trabajar con archivos de chorrocientos gigas, tengo desactivado el soporte de "archivos grandes" en el kernel (para este tipo de cosas uso kernel personalizado). Y esto efectivamente causa problemas. Pero la solución es fácil:
# tune2fs -O -huge_file /dev/sdxX
# fsck.ext4 /dev/sdxX
# mount /dev/sdxX
Y todo listo para funcionar!

En cuanto encuentre una solución limpia para el primer problema lo dejaré por aquí, lo mismo le sirve a alguien :)

Friday, March 27, 2009

Energy management in Linux

Nota: este post es una continuación de este otro. Para más info, mirar ahí.
Note: this article is a follow-up of this one. Please take a look at it for extended info.
____________________________________________________

UPDATE: Check this post for related info.

I've been concerned about the energy consumption of my Thinkpad X200s for a while now. It's not that electricity is that expensive or I am sooo worried about global warming, it's more about squeezing the most out of the battery while trying not to damage it. My X200s has the 9cell battery which means 13 hours Lenovo-stated battery time. I'm going to use that twice in it's whole life. The point is in maximizing the long-time battery health. Lithium-ion batteries don't like to be deep-discharged too often, so my goal is to (almost) never let the charge drop below 20%. If someone only needs 2-3 hours of battery time and can charge it back to 100% after that, there is nothing to worry about. There is no way to burn 80% of the battery in that time with this laptop. Of course, if someone travels a lot and can't plug the laptop for a whole day, it makes sense to spend as few watts as possible.

Now, about battery life and energy consumption. Lenovo has made some serious effort to optimize the power drain in software and their Vista drivers are as of now unbeatable. In Vista, the minimum I've seen was 5.2W, in Linux 5.9W or 5.8W. Maybe 0.6W doesn't seem too much, but we are talking about more than 10% here! I've discussed this issue here with some folks, I recommend reading it.

First of all, use common sense. Don't expect 13 hours of number crunching, full-brightness video watching, usb-gadget powering or high-speed downloading. Turn down/off everything you don't use. If you are in a dark room, lower the screen brightness. If you are not listening to music, mute the volume. If you are, use headphones or set the volume a tad lower. Kill all the daemons you don't need. You got it, right?

Second point, my main source of info for all this stuff was this website. Follow all the steps you can. Make sure you have a tickless kernel. Turn on laptop-mode to spin down your hard drive when idle (ONLY if you have a SPINNING drive, you'll gain nothing if you have a SSD). Activate processor energy management and set the cpu frequency governor to ondemand or conservative. When you are familiar with all the goals, keep reading.

Now we are going to get our hands dirty. I'll explain this things for Arch Linux, the exact configuration files / paths may be located in a slightly different place in you distribution, use "locate" command or google to find them.

- General powersaving settings, aka laptop mode: Install and then activate laptop-mode editing the file "/etc/laptop-mode/laptop-mode.conf". After that, check all the files in "/etc/laptop-mode/conf.d/*" and activate all the things you can. Except maybe cpufreq, I rather let cpufreqd do that job, it's much simpler. Start laptop-mode with "/etc/rc.d/laptop-mode start" and add it to your daemon list in your rc.conf file. In case you skip something here, I'll probably mention it anyway, but laptop-mode comes in handy for automating it.

- Cpu frequency scaling. I recommend using cpufreqd, it is very very simple. Install it, do a "echo ondemand > /etc/conf.d/cpufreq" and start the daemon as shown above, also adding it to the daemon list.

- Turn off the video outputs. It sounds weird, but with the xorg 1.5 and the old intel 2.4 drivers, the video chipset doesn't detect the outputs right and turns on HDMI. The newer xorg 1.6 and intel driver 2.6 didn't have this problem when I tried them, but check it anyway. You can do it with "xrandr". If you see a star ( * ) on some line, that output is active. Turn it off with "xrandr --output HDMI-2 --off". You should check again on restart.

- Turn down the wifi power. This is a real power hog, it can drain more than 1.5W doing nothing. The control file is "/sys/class/net/wlan0/device/power_level". With "echo 5 > file" you maximize powersaving. Obviously, "cat file" gives you the wifi status. I've noticed some misbehavior lately, if you are not connected and with some network manager daemon running, it keeps going back to level 0 (maximum power usage). I usually fix it with:
# killall wicd-manager
# /etc/rc.d/wicd stop
# killall wpa_supplicant
# ifconfig wlan0 up
# echo 5 > /sys/class/net/wlan0/device/power_level
# ifconfig wlan0 down
# cat /sys/class/net/wlan0/device/power_level

If the last command shows a "INDEX:5", it'll probably stay that way, but checking it some time later would be good. As usual, let a script do that for you. If it is not 5 but 0, repeat the previous 3 steps. If you are conncected to some network, it usually stays at level 5 without any issue after a simple echo.

- Turn off bluetooth if you are not using it. As easy as "echo disable > /proc/acpi/ibm/bluetooth". Sometimes it doesn't want to wake up again, try a "lsusb" after re-enabling it. Again, acpid is a great way to handle it, here is a chunk of my handler:
*1005)
if [ "$(cat /var/local/bluetooth)" = "disabled" ]; then
echo "enable" > /proc/acpi/ibm/bluetooth
echo "enabled" > /var/local/bluetooth
lsusb > /dev/null
logger "ACPI bluetooth on"
else
echo "disable" > /proc/acpi/ibm/bluetooth
echo "disabled" > /var/local/bluetooth
logger "ACPI bluetooth off"
fi
;;



- Turn on SATA link powersaving. This one is pretty straightforward: "for i in /sys/class/scsi_host/host*/link_power_management_policy; do echo min_power > $i; done". Once every power cycle. If you connect the power plug and disconnect it, only one link file will go back to powersave, so you have to execute it every time you go on battery. Acpid, again, is a great way to do that.

- Turn on PCIe powersaving. The control file is "/sys/module/pcie_aspm/parameters/policy". You can "echo powersave" to it to turn it on and "echo performance" to turn it off. As always, cat will tell you the actual status.

- Activate the sound auto-suspend. Echo the timeout to "/sys/module/snd_hda_intel/parameters/power_save". If you are not using the sound at all, mute it with the hardware button, just in case.

- This one may be VERY DANGEROUS. You can turn off the fan if you are going to do lightweight work and you trust your programs to be infinite-loop-free, so firefox is out of the question here. You have to load the thinkpad_acpi module with "fan_control=1" parameter and then manage the control file "/proc/acpi/ibm/fan". Again, "echo" stuff to set the fan on/off, "cat" to get info. I HIGHLY recommend to use the watchdog function and some script to make sure the processor won't melt. You can read the temperatures at "/proc/acpi/ibm/thermal", "/sys/class/thermal/thermal_zone*/temp" and "/sys/bus/platform/devices/coretemp.*/temp1_input", among others. Google is your friend ;)

- If hal is polling you nonexistent (on a X200) CD drive, kill it.

- If you are not using it, close firefox. The diffrerence may be 1W. If you plan on use it later, a simple "killall -STOP firefox" will do the trick. When you are going to use it again, "killall -CONT firefox". Bind it to a hotkey if you want.

- Also, "ifconfig eth0 down" sure doesn't hurt if you are not using the good ol' ethernet interface.

- Unloading modules doesn't usually work, but you may try it (and post a comment with your findings!). Some people unloads uhci, snd_hda_intel, or iwlagn. I haven't seen any difference trying, but your mileage may vary. You can also take one core of the cpu offline, but it seems to cause to actually consume MORE power than sitting idle. I haven't measured it myself, so if you do, please let me know! The control file is "/sys/devices/system/cpu/cpu1/online", 0 takes it offline, 1 brings it back to work.

- Last but not least: install and run powertop. It's a wise program. Follow it's suggestions. I use it to activate USB autosuspend and see which programs and wreaking havoc. Firefox, amarok2 and any java-based ones are on top positions, but some other programs may be broken and causing the processor to work more than it should. Knotify4 in KDE 4.1 had a 100Hz timer, for instance.

If I remember any other tweak, I'll post it here, stay tuned.

With all these tricks, brightness at minimum, everything off and doing _nothing_, the X200s drains 5.8W. With wifi on, brightness 5/15, browsing and programming (without heavy compiling), it goes at around 6.5W. On full brightness, no wifi, just above 7W. Full brighness + wifi it's under 7.5W. You have to do some pretty heavy stuff to take it above 10W, watching HD movies at full volume and brightness will do it, but anyway, at 10W the battery still lasts more than 8 hours. If you want me to try any specific combination, let me know.

Finally, for more info, try these:
http://www.nabble.com/X200-Battery-Life-td20188937.html
http://www.nabble.com/Linux-Thinkpad-f13633.html
http://www.mail-archive.com/ibm-acpi-devel@lists.sourceforge.net/
Or ask a question in the comments.

Thursday, March 12, 2009

Wireless en Linux y Windows

Algo que ya he comentado en alguna ocasión es mi profundo odio hacia NetworkManager y su forma GNOME de hacer las cosas. Ahora uso wicd en todos mis equipos y la verdad es que comparado con NM funciona estupendo, pero en general sigue teniendo muchos fallos. Al menos usa ficheros de configuración en texto plano en "/etc/wicd/*.conf" y permite el uso de scripting, con lo que a las malas es posible ignorar la lógica de wicd y usarlo como una gui para scripts propios.

Lo que mejor funciona suele ser la línea de comandos, y por tanto los scripts suelen ser bastante fiables, pero parece ser que el progreso de la tecnología no lo llevan demasiado bien.

Hace unas semanas me compré un modem/router con soporte para 802.11n, en concreto el Belkin F5D8635. Aparte de que el modelo sin modem tiene switch gigabit y este no, mi portatil no conseguía conectarse a la wifi si se dejaba el modo N activado, sólo si desde la interfaz web se ponía "802.11g only" o "b/g". Temiendo que fuera un tema de drivers, ya que era mi primer contacto con una wifi N, me puse a indagar.

El comando "iwconfig" no ayuda mucho ya que muestra un bitrate de 54Mb/s o como mucho 60Mb/s. Un escaneo con iwlist scan tampoco ayuda, ya que no muestra por ningún lado que la wifi sea N o que llegue a los 270/300 Mb/s anunciados. Buscando más, resulta que hay un nuevo comando, "iw", que parece que va a ser el nuevo estándar, como el comando "ip" para la gestión de red. Igual que ip sustituye a ifconfig, route, etc, iw sustituirá a iwconfig, iwlist, iwpriv, etc. Para el caso da lo mismo ya que "iw list" tampoco muestra más de 60Mb/s. Desde luego algo raro es, ya que es más de los 54mbits de 11g, pero no deja muy claro qué es lo que significa.

Tras intentar todo lo que se me ocurrió, decidí devolver el router como defectuoso y comprar otro. Esta vez busqué por internet alguno que tuviera de todo:
  • 802.11n (indispensable)
  • Radio de 5GHz (importante, para evitar interferencias de hornos microondas, walkies, bluetooths, las mil wifis de los vecinos....)
  • Posibilidad de meterle Linux (importante)
  • Modem ADSL
  • Puerto USB para discos
  • Switch gigabit
Dado que ninguno cumplía con todos los requisitos acbaé comprando en pixmania el Linksys WRT610N, que tiene de todo menos modem ADSL, pero además puede usar las bandas de 2,4GHz y 5GHz a la vez, dado que tiene 2 radios.

Con el WRT610N sí que me pude conectar a la wifi en modo N, tanto en 2,4 como en 5 GHz, pero con resultados un tanto decepcionantes. Pra las pruebas conecté el X200s a la wifi a 5 GHz, para evitar cualquier tipo de interferencia de la banda de 2,4. Ejecutando como root "ping -f -s 20000 192.168.1.1" me daba una velocidad por debajo de 3,5MB/s. Teniendo en cuenta que con 802.11g me daba por debajo de 2MB/s, supone un rendimiento de apenas el 170%, cuando supuestamente debería dar un 600%.

Dejando el ping a un lado, ya que peude estar limitado por la CPU del router, conecté mi AspireOne por cable y me baje un fichero grande del servidor web en la wifi. Nada, los mismos 3,5MB/s. Para descartar un posible cuello de botella en la ethernet del Acer, conecté el server al switch, esta vez gigabit (el Acer es 10/100). Repetí la prueba y dió unos más que decentes 11,2MB/s, casi el límite teórico de una ethernet 100Mbps, así que la tarjeta del Acer estaba perfectamente.

Tras esta decepción pensé durante un rato alguna otra soulción, puesto uqe había leído por internet que la gente le sacaba 110Mbps al router y yo no llegaba ni a 35. Probé en el otro sentido, ya me sonaba que podía ser asimétrico, aunque no debería. El problema es que no estaba por la labor de instalar un apache o ftpd en el Acer sólo por probar, así que tocaba recurrir al ingenio:
# dd if=/dev/urandom of=/tmp/test bs=1M count=80
# pacman -S netcat
# nc -l -p 8080 -e "cat /tmp/test"

Y problema solucionado, ya tenía un servidor escuchando en el puerto 8080. Elegí usar urandom y no zero por evitar el uso de cualquier compresión a cualquier nivel, por si acaso. Y dado que el AspireOne tiene discos SSD que parece que son tirando a lentillos, /tmp era una punto de montaje tmpfs, es decir, en RAM.

Resultado: unos consistentes 7MB/s, oscilando entre 6,85 y 7,1. Ya era una gran mejora, aproximadamente un 400% del rendimiento de una wifi 802.11g. Pero por un lado no llegaba ni a 70Mbps y por otro seguía siendo asimétrico, como si en la subida no se usara canales de 40MHz.

Como no perdía nada, arranqué Windows Vista. Sí, sigo quieriendo demostrarme a mi mismo que no es tan malo. Y esta vez el Windows se portó bastante mejor que Linux. Para empezar, tanto Windows como la herremienta de Lenovo detectaron y listaron la wifi como 802.11n, sin lugar a dudas. Luego, tras conectarse sin problemas ni "glitches", me bajé el wget para windows para uniformizar el software y repetí la prueba. El resultado fue agridulce, pero dificilmente por culpa de Windows: la transferencia superaba los 10MB/s, llegando en ocasiones a medias de 11MB/s, pero a veces la conexión se caía por varios segundos o incluso una vez por minuto y medio, como si algo por el camino se saturase. Y dada la cercanía con los 100Mbps podía ser bien el Acer o bien el router. En todo caso, el rendimiento de la wifi en Windows parece ser sensiblemente mejor que en Linux.

Deberes para casa: echarle un vistazo a compat-wireless y repetir el benchmark de la wifi a ver si mejora el rendimiento con drivers "experimentales", aparte de buscar el culpable de la inestabilidad de la la wifi a altas velocidades.

Sunday, March 8, 2009

Mensajes en el login en linux

Hoy un post informativo/note-to-self, sin criticar nada. Para variar un poco.

Hace tiempo que tenía una tare en mi TO-DO: personalizar un poco los mensajes que dan mis ordenadores al loguearse. Todos mis equipos capaces de conectarse a una red (PCs, moviles, videoconsolas...) tienen nombres de sondas espaciales. Mi primer PIII 450MHz fue sputnik y por ejemplo mi portatil principal es ranger. La idea que tenía es que al loguearse saliera un mensajito con un resumen de "la vida y obra" de la sonda en cuestión, distinto por supuesto para cada máquina. Si bien cualquiera (eso espero) sabe de que se habla si se menciona el sputnik, si hablamos de explorer, vanguard, venera o transit la cosa cambia. Y al final de tanto nomre hasta yo mismo me olvido y no me viene mal refrescarme la memoria con un mensajito. Para esto en linux hay dos opciones: mensajes antes o después del login.

Antes del login se muestra el archivo "/etc/issue" si es login local, y si es por red (ftp, etc) se intenta primero "/etc/issue.net" si existe. En caso del login ssh, hay que decirle la ruta a sshd en "/etc/ssh/sshd_config" poneindo la ruta del archivo a mostrar en la variable "Banner". En el issue se suele poner un mensaje cortito identificando la máquina/sistema operativo.

Para que el mensaje se muestre una vez validados user y pass, el mensaje va en "/etc/motd", acrónimo de message of the day. Aquí es donde va el mensaje gordo, más que nada porque al ponerlo en issue, se podría hacer un ataque DoS por medio de logins fallidos, dada la asimetría del ADSL (no es el ataque más efectivo pero prudencia nunca hay poca).

Si alguien quiere logins más divertidos tiene muchas opciones. En polishlinux explican los programas cowsay y figlet para un poco de ASCII-art. Otro clásico es fortune, un programa que saca citas aleatorias, normalmente de fráses célebres o gracias de series de TV.

Y para opciones más serias pues se pueden meter avisos de discos a punto de llenarse, errores del log... sólo hace flata meter un script en cron que actualice el motd con la info deseada, eso es cuestión de cada admin, para gustos los colores.

Tuesday, March 3, 2009

Post 100!

Conociendome, creí que nunca llegaría a las 100 entradas en el blog, así que esto ya se puede considerar todo un éxito.

Coincidiendo con la ocasión, en el Media Markt hoy había "netbooks" Acer AspireOne por 150€, con 512Mb de RAM, 8Gb de HDD y Linpus Linux. El portátil mola pero Linpus es muy muy para novatos. Aparte de que los paquetes son del año de la polca. ¿Nmap 4.20? En fin, en cuanto tenga un rato cambiaré la distro.

BackTrack tiene buena pinta para los usos que le voy a dar al bicho, aunque Debian sid, Zenwalk o Slax tampoco las descartaría. O quizá haya alguna distribución especial para el Acer One, me suena que para el Eee hay alguna...

La tarjeta Atheros se controla casi casi igual que una fonera:
# wlanconfig ath0 destroy
# wlanconfig ath0 create wlandev wifi0 wlanmode sta nosbeacon
# wlanconfig ath2 create wlandev wifi0 wlanmode ap
# ifconfig ath0 up
# iwconfig ath2 essid TONTO_EL_QUE_LO_LEA
# ifconfig ath2 up

Y a quedarse con la gente en todos lados :D

Parece que no soporta tantos APs como la fonera, pero con uno hay de sobra. Y siempre se le pueden sacar usos civilizados, como compratir una conexión 3G o una wifi "auditada" con éxito, por ejemplo.

Thursday, February 26, 2009

¿Virus en linux?

Ya se publicó hace un tiempo (quiza tanto como en 2006) pero aún así me parece digno de resaltar un artículo (y varias observaciones) sobre como crear un virus para linux.

Muy interesante cómo se propone saltarse varias protecciones que siempre se resaltan como los puntos fuertes de linux.
- Proteccion contra ejecución: Los archivos ".desktop" son ejecutados por los gestores gráficos (KDE, Gnome) sin necesidad de que se marquen como ejecutables. Este es el fallo/despiste/feature que se explota y que posibilita todo el proceso.
- Privilegios de root: realmente no es necesario ejectuarse como root, si se quiere infectar a un solo usuario, pero suplantando a un programa "sudo" y esperando, al final se puede obtener privilegios de root. Esto se debe a que un usuario "casero" de linux al final está acostumbrado a meter el password cuando se le pide. Si alguien se suele loguear directamente como root desde una consola (sin hacer sudo/su) este paso sería (en principio) imposible.

Realmente es algo muy bien pensado, y si bien quizá ahora mismo pueda funcionar en cuanto los desarrolladores decidan requerir bit de ejecución para los ".desktop", el chollo se va a acabar.

Aún así el método tiene limitaciones, como que por ejemplo no sirve para cualquier distro de linux, tiene que ser adaptado a cada una por las rutas de los iconos o por programas no disponibles en cada una.

Si tengo algo de tiempo intentaré desarrollar una prueba de concepto por mi cuenta, aunque seguro que a estas alturas hay cienes y cienes rondando por internet.