Google
 
Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Monday, March 19, 2012

Multiple SSID on OpenWRT with bandwidth limit

If you're a network junkie and not been living under the rocks, you must have heard of OpenWRT. It's a Linux distribution for embedded devices (routers) and gives you power to do things usually impossible or difficult with inbuilt router firmware. Wireless Freedom indeed.

This was my scenario: I had to create two wireless APs for my office, one for the guests (no password but bandwidth limited) and another for non-guest users (password protected but no limit on bandwidth). That way the visitors will have free wireless internet, but with limited bandwidth. The office staffs will have to connect to a password protected wifi for unrestricted bandwidth.

The requirements for the APs are,

Free Wifi for visitors
- SSID: FreeWifi
- Password: none
- Bandwidth limit: 256Kbps uplink, 128Kbps downlink

Office Wifi for staffs
- SSID: OfficeAP
- Password: 1234567890
- Encryption: WPA2
- Bandwidth limit: none

Here's how I did it on OpenWRT. Connect to OpenWRT shell.

1. First create two wireless APs with above configuration. Add the following lines to /etc/config/wireless (Remove any existing 'wifi-iface' configurations)

# Free Wifi
config 'wifi-iface'
        option 'device' 'wifi0'
        option 'ssid' 'FreeWifi'
        option 'mode' 'ap'
        option 'network' 'lan'


# Office Wifi
config 'wifi-iface'
        option 'device' 'wifi0'
        option 'ssid' 'OfficeAP'
        option 'mode' 'ap'
        option 'network' 'lan'
        option 'encryption' 'psk2'
        option 'key' '1234567890'


As simple as that! Now to enable the wifi, go to shell and

# wifi down; wifi up

2. Now to limit bandwidth, we'll be using wondershaper. To install:

# opkg update
# opkg install wshaper


3. Now find which interface is the FreeWifi assigned to

# iwconfig

On mine, it was on ath0

4. Modify /etc/config/wshaper and start wondershaper

config 'wshaper' 'settings'
    option 'network' 'ath0'
    option 'downlink' '256'
    option 'uplink' '128'


Now, start wondershaper.

# /etc/init.d/wshaper start

5. By default, wshaper isnt enabled at startup. so,

# ln -s /etc/init.d/wshaper /etc/rc.d/S99wshaper

Monday, December 26, 2011

LinuxMint Debian and adjustments

I recently moved to Linux Mint Debian after using Ubuntu for since quite a while. (Reason: Like many, I'm not so much fond of Unity)

However, Debian is not as polished as Ubuntu. Here are some of the fixes I made:

Installing 686-pae kernel

LM Debian comes with 486 kernel, which has support for single CPU only. The first thing to do is install 686-pae kernel

# apt-get install linux-image-686-pae

Reboot and choose the new kernel.

Installing Virtualbox

Virtualbox is available in the repository.

# apt-get install virtualbox

However, virtualbox wont work because of the newly installed 686-pae kernel, so we need to rebuild the vboxdrv modules. This requires linux headers for 686-pae kernel.

# apt-get install linux-headers-686-pae

This should rebuild the vboxdrv modules automatically, post installation. But if it doesnt, do the following:

# dpkg-reconfigure virtualbox-dkms

Installing Wine

Unfortunately, Wine is not available in the repo. Use the repo at http://www.lamaresh.net/

Add the following line to /etc/apt/sources.list, or via Synaptic - Settings - Repositories - Other Software - Add

deb http://www.lamaresh.net/apt squeeze main

Then update and install.

# apt-get update
# apt-get install wine


Fixing Mint-X themes

There are two Mint themes, Mint-X and Mint-X-Metal, which are very soothing and greenish. However there's a little glitch with expander plus (+) signs (eg, visible while installing software using Synaptic). To fix, open /usr/share/themes/Mint-X/gtk-2.0/gtkrc file (as root) and remove the following line:

GtkExpander::expander_spacing = 16

Do the same for /usr/share/themes/Mint-X-Metal/gtk-2.0/gtkrc too.

Also, if you want to change the font size for panels, look for font_name variable in this gtkrc file.

Few other changes

You might also wanna install ttf-devanagari-fonts and ttf-mscorefonts-installer. Also download the latest Firefox (currently 9.0) and install it to /opt/firefox/

# tar -jxf firefox-9.0.tar.bz2 -C /opt/

Tuesday, June 14, 2011

NTC PSTN Number to Name

NTC's website has a nice feature called Telephone search. This is particularly handy when you get a call from landline (PSTN) number and have no idea who's calling. Ofcourse you can go to the site and search, but the following bash script makes it faster.

#!/bin/bash

#
# Nepal Telecom PSTN Number to Name search
#

if [ "$1" == "" ] ; then
echo "Usage: " $0 "phone_number"
exit
fi

# Prefix 01, if not provided
if [[ $1 =~ ^01 ]] ; then
NUMBER=$1
else
NUMBER="01$1"
fi

wget -q http://ntc.net.np/telsearchRes.php
--post-data "searchFor=name&telno=$NUMBER&submitted=Search" -O - | html2text | grep "$NUMBER" | tr '_' ' ' | sed 's/ [\ ]*/ /g'

Save the file, chmod it as executable.

To use,
./telsearch 5544132
| 1 |015544132|Ntc |Cellular Mobile And New S|Jawalakhel|

Tuesday, May 10, 2011

Grub2 recordfail FAIL

I have this headless, keyboardless server running on Ubuntu 10.04. Runs fine, but once in a while while there's power cut off the server still remains dead when the power is back. I connected monitor and keyboard and found that the problem is with Grub2.

Turns out there's a variable named recordfail which is set to 1 during next boot whenever there's some problem with the computer (like due to power failure).

Now if you see /boot/grub/grub.cfg file, it has the following lines:

if [ ${recordfail} = 1 ]; then
set timeout=-1
else
set timeout=10
fi
Which means, the timeout counter is disabled whenever the recordfail variable is set. This is nice for desktop environment, which has a monitor, so I can see the Grub countdown is disabled so I can proceed with Repair option if I have to, but for headless servers the computer just sits idle at Grub screen, puzzling the poor sysadmin.

Fix? I changed the timeout=-1 to timeout=10.

Thursday, February 03, 2011

Fixing resolution for bigger external monitor

If you happen to connect our Linux laptop or netbook to an external monitor, you're likely to get into resolution trouble. For smaller resolutions (<=1024x768), it's not a bigger deal but once you try higher and unusual resolutions, like 1440x900, things don't turn out that well. Here's how to switch to such resolutions under (Ubuntu) Linux. I'm connecting my laptop (Intel 845GM chipset) to an external monitor (1440x900 native).

Fire up terminal and run the following command; first calculate VESA CVT mode lines

$ cvt 1440 900
Output:
# 1440x900 59.89 Hz (CVT 1.30MA) hsync: 55.93 kHz; pclk: 106.50 MHz
Modeline "1440x900_60.00" 106.50 1440 1528 1672 1904 900 903 909 934 -hsync +vsync

Now, lets see my card's supported resolutions out of the box.
$ xrandr
Output:
Screen 0: minimum 320 x 200, current 1280 x 800, maximum 4096 x 4096
VGA1 connected (normal left inverted right x axis y axis)
1360x768 59.8
1024x768 60.0
800x600 60.3 56.2
848x480 60.0
640x480 59.9 59.9
1440x900_60.00 59.6
LVDS1 connected 1280x800+0+0 (normal left inverted right x axis y axis) 331mm x 207mm
1280x800 59.9*+
1024x768 60.0
800x600 60.3
640x480 59.9
TV1 disconnected (normal left inverted right x axis y axis)

In the above output, VGA1 is the external monitor and LVDS1 is the laptop's LCD panel. Now use the modeline information to create a new custom resolution and add it to VGA1
$ xrandr --newmode "1440x900"  106.50  1440 1528 1672 1904  900 903 909 934 -hsync +vsync
$ xrandr --addmode VGA1 1440x900
The changes are temporary though. If you want it to make it permanent, add them to ~/.xprofile

Now go to System > Preferences > Monitors. The external monitor's list of resolutions should show 1440x900.

Some more info:
Connecting to external monitor has two options, mirror or extend. Choosing mirror gives the same output to both monitors. Extend, well, extends the display over both monitors. But it has a catch: for Compiz to extend over external monitor, the maximum possible horizontal resolution (see first line of xrandr output above, in my case 4096) should be at least double of sum of total horizontal resolution of two monitors.

In my case, if I try to extend my 1280x800 to an 1440x900 external monitor, its not gonna work as 2*(1280+1440)=5440 > 4096. So mirroring is the only option. However if you set the resolution while compiz is on, it's gonna be "confused". Here's the workaround:

1. Add the custom resolution as described above
2. Disable Compiz (System > Preference > Appearance > Visual Effects > None)
3. Change Resolution, and set the laptop's output to off
4. Enable Compiz again

Saturday, December 25, 2010

Load Balancing LTSP clients using Ethernet Bridging

Typical LTSP setup has the following configuration:


+-------------+
| Server |
+-------------+
| eth0 | eth1 |
+------+------+
/ |
/ |
Internet Switch
|
+---------+-------------+
| | |
Client-1 Client-2 ... Client-n

LTSP Clients

The problem with this is that the network card bottlenecks the performance. Once the number of clients increases (usually >5), even though the server is capable of handling the load, the network card (usually, 100BASE-TX) can't provide the throughput.

There are two solutions to this:
1. Use 1000BASE-T (gigabit) ethernet cards and switches
2. Use load balancing

Using gigabit ethernet cards solves the problem but they are expensive. The switches are expensive too. Plus there are flow control problems if the clients have 100Base-TX cards, which is usually the case.

Load balancing is an easier and cheaper approach. Although this can also go fairly complicated, here i'm going for the simplest one using ethernet bridging.

The trick is to use multiple NICs connected to multiple switches. Then bridge the cards to provide a common interface. Here's what it looks like:

+--------------------+
| Server |
+------------------- +
| eth0 | eth1 = eth2 |
+------+------+------+
/ | |
/ | |
Internet Switch Switch
| |
+----+-------+ +----+-------+
| | | | | |
C-1 C-2 ... C-n C-1 C-2 ... C-n

LTSP Clients LTSP Clients

Lets say, there are three NICs: eth0, eth1 and eth2. eth0 is connected to internet. eth1 (say, 192.168.0.254) is connected to LTSP clients. eth2 is unused and is supposed to be bridged with eth1.

First install bridge-utils
# apt-get install bridge-utils
Create a bridge (br0) and add eth1 and eth2 to it
# brctl addbr br0
# brctl stp br0 off
# brctl addif br0 eth1
# brctl addif br0 eth2
Now release the IP addresses of eth1 and eth2
# ifconfig eth1 down
# ifconfig eth2 down
# ifconfig eth1 0.0.0.0 up
# ifconfig eth2 0.0.0.0 up
Assign the LTSP IP address to bridge.
# ifconfig br0 192.168.0.254 up
Now connect eth1 and eth2 to separate switches, and each switch to (equal number of) LTSP clients.

Friday, November 12, 2010

Generating Tag Cloud the Unix way

UPDATE: I've modified the script to add color and transparency :)

Ushaft's this tweet on creating tag cloud caught my attention. While there are better tools available online, i decided to give it a try in Linux :)

First we need to generate a frequency list of words out of a file. No brainer. I used the GNU/GPL license as source text.

cat /usr/share/common-licenses/GPL |
tr 'A-Z' 'a-z' |
sed 's/[^a-z ]//g' |
sed 's/\s/\n/g' |
awk '{if (length($1)>=3) print $1 }' |
sort | uniq -c | sort -nr > freq.txt

Explanation (per line):
1. Print the license
2. Convert to lowercase
3. Remove punctuations
4. One word per line
5. Discard words with 2 or less long
6. Grab frequency and write to freq.txt

freq.txt needs some editing to remove irrelevant words like "the", "but", etc.

Now to create tag cloud, i wrote a simple awk script that outputs svg file. Saved this as gentagcloud.awk (Please change the width, height and scale variable to your taste)

#!/bin/awk -f

BEGIN {
WIDTH=1000
HEIGHT=600
SCALE=1

OFS=""

print "<?xml version=\"1.0\"
encoding=\"UTF-8\" standalone=\"no\"?>"
print "<svg width=\"",WIDTH,"\" height=\"",
HEIGHT,"\" version=\"1.1\"
xmlns=\"http://www.w3.org/2000/svg\">"
}

{
R = int(rand()*9)
G = int(rand()*9)
B = int(rand()*9)

print "<text style=\"fill:#",R,G,B,";opacity:0.75;
font-size:",$1*SCALE,"px;\"
x=\"",rand()*(WIDTH-100),"\"
y=\"",rand()*HEIGHT,"\">",$2,"</text>"
}

END{ print "</svg>" }

Now to create tag cloud,

awk -f gentagcloud.awk < freq.txt > tagcloud.svg

Tada! Tag cloud generated, view tagcloud.svg in your browser or image viewer

If you have ImageMagick installed, you can convert it directly to png too. (Transparency isnt handled properly. If you have workarounds, please comment)

awk -f gentagcloud.awk < freq.txt | convert - tagcloud.png

BTW, the tag cloud was like this: (lil' ugly, but WTH :))

Thursday, February 25, 2010

Internet Connection Sharing in Linux over Ad-hoc Wireless

Laptops are common these days and so is wireless networking that comes with it. Almost all of us use Wireless Router for wireless networking and internet sharing. But most of us might not be familiar with ad-hoc mode that works in every wireless card and can eliminate the use of router altogether. Here's how:

To setup ad-hoc wireless, you basically set two or more wireless cards to same ESSID in ad-hoc mode and different IP addresses.

Setting the wireless card in ad-hoc mode

Generally iwconfig is used to set the wireless mode, but if you have madwifi drivers (see this too), the commands are slightly different. Go to terminal and type,

iwconfig
If you see interfaces named wlan0, wlan1, etc iwconfig will work. If you see interface names similar to ath1 and wifi0, then madwifi specific commands are to be used.

For general wifi cards:
sudo iwconfig wlan0 mode ad-hoc
Replace wlan0 with the interface name as listed by iwconfig

For cards using madwifi driver:
sudo wlanconfig ath1 destroy
sudo wlanconfig ath1 create wlandev wifi0 wlanmode adhoc
Now set essid. Pick some name like 'adhocwifi'
sudo iwconfig wlan0 essid adhocwifi
If required, to set encryption key
sudo iwconfig wlan0 key 1234567890
Now set IP address:
sudo ifconfig wlan0 192.168.0.1
Follow the above steps for another wireless card and set IP address in same subnet, say 192.168.0.2, and ping each other.

The whole ad-hoc mode setting can also be done using GUI network-manager, but since i'm not so much fond of graphical interface i'm not covering it. It should be simple.. :)

Internet Connection Sharing

Now to share the internet over wireless,
sudo iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
where ppp0 is the connection you want to share (PPPoE connection in this case)

You also need to enable IP forwarding:
sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
Or, to enable permanently add the following line to /etc/sysctl.conf
net.ipv4.ip_forward=1
Some ISPs might limit the TTL so that you wont be able to share the internet. Fix:
sudo iptables -t mangle -A PREROUTING -j TTL --ttl-inc 1

Using the shared internet (in Linux)

Now to use the shared internet on another computer, set it to ad-hoc mode and assign IP address in the same subnet as described above and perform the following:

1. Set the IP of computer sharing internet as gateway
sudo route add default gw 192.168.0.1
2. Set DNS server. We're using Google's DNS.
sudo sh -c "echo 'nameserver 8.8.8.8' >> /etc/resolv.conf"
You can also use IP and DNS Masquerading to ease the task.


Using the shared internet (in M$ Windows)

If you want to use the shared internet on M$ Windows,

1. Connect to the Wireless Network (in this case 'adhocwifi')
2. Go to Network Connections
3. Right click the Wireless Connection
4. Select the Internet Protocol (TCP/IP) and click Properties
5. Set IP to 192.168.0.2 (or accordingly in the same subnet as set on Linux box), gateway to 192.168.0.1 (as set on Linux box) and DNS to 8.8.8.8

Wednesday, February 17, 2010

Converting Latex document to HTML / ODT / DOC

I do all my documents in Latex. Actually i usually use emacs org-mode first and later convert it to Latex, but when it comes to using bibtex, it's all latex. It works great and the output dvi/pdf files look so professional. However recently i had to submit the file in .doc format, and i had a real hard time finding good tools to do that.

There are no direct Latex to .doc converters, so the best bet is to go Latex -> HTML -> DOC. There are lots of Latex to HTML converters like latex2html, tth and hevea, but most of them either don't produce good HTML or mess with bibliography references. But after some research i found the best: TeX4ht

TeX4ht is available in ubuntu/debian repo, so to install

sudo apt-get install tex4ht
Conversion is simple:
htlatex document
(please note, there is no .tex suffix)

This will generate document.html, css and bunch of .png files.

Now to convert it to wordprocessor files (odt, doc..),
1. Open the html file with OpenOffice.org
2. File > Save as
3. Choose the format you want to save it in (odt, doc)

If you have images in the document, they will be linked instead of embedded in the document. To fix this: (source)
1. Edit > Links
2. Click "Break Link" for each image link

Thursday, February 04, 2010

mpg123: Lightest mp3 player in Linux

If you are in search of the lightest barebone mp3 player in Linux, nothing can beat mpg123. Unless you want flashy visualizations and playlist management and such, mpg123 can save you a lot of memory and cpu horsepower.

Installation is easy. In Ubuntu,

sudo apt-get install mpg123

Mpg123 comes with loads of options. Check out the man page for details. Here I'm gonna share a few usage tips.

Shuffle-play a directory of mp3s:
mpg123 -CZ /path/to/mp3/folder/*

-Z option is for shuffle, -C is for control. From man page:
-C, --control
Enable terminal control keys. By default use ’s’ to
stop, ’p’ to pause, ’f’ to jump forward to the next
song, ’b’ to jump back to the beginning of the song,
’,’ to rewind, ’.’ to fast forward, and ’q’ to quit.
Type ’h’ for a full list of available controls.

Equalizer:

Don't fall off your chair! Yes, mpg123 also comes with 32-band equalizer. But there's no inbuilt graphical UI for that, you need to create the plain-text file. There's an editor though if you like, but creating one is not hard either. From man page:
-E file, --equalizer
Enables equalization, taken from file. The file needs to
contain 32 lines of data, additional comment lines may be
prefixed with #. Each data line consists of two floating-
point entries, separated by whitespace. They specify the
multipliers for left and right channel of a certain
frequency band, respectively. The first line corresponds
to the lowest, the 32nd to the highest frequency band.
Note that you can control the equalizer interactively
with the generic control interface.

I've made one with party feel: party.txt

Usage:
mpg123 -CZ -E party.txt mp3_file

Songs again and again:

Plus if you kind of person who listens to couple of songs again and again for weeks (instead of shuffled huge playlist), then hi5! :) and here's how to do that with mpg123:
mpg123 -CZ song1.mp3 song2.mp3

Wednesday, February 03, 2010

Making DLink DWL-650+ PCMCIA Wireless card work under linux

The DLink DWL-650+ PCMCIA Wireless card doesn't work on recent Linux distros (I tried Ubuntu Hardy to Jaunty). After plugging in, the system hangs with CapsLock flashing.

Turns out the card is handled by acx module and the support is broken for this card. So use ndiswrapper instead.

First blacklist acx module. Open /etc/modprobe.d/blacklist.conf file and add the following line

blacklist acx
Now install ndiswrapper
sudo apt-get install ndiswrapper-common
Now get the Windows driver for the card from here. Extract the file, go to the winxp folder and,
sudo ndiswrapper -i AIRPLUS.INF
The card should work now.

Sunday, May 31, 2009

NTC's GPRS in Linux via Bluetooth using Nokia phone

The following guide explains how to connect to Nepal Telecom's GPRS service from Linux via Bluetooth using Nokia phone. This guide is based on Linux GPRS Guide. The steps have been tested on Nokia 6600, 6630 and 5300 but should work on all Nokia phones.

NTC's GPRS is *really* slow so I won't recommend it for everyday use. However simple mail checking and tweeting ;) should do just fine.

Requirements
1. Nokia Phone
2. Nepal Telecom GPRS Account
3. Bluetooth Dongle (if not inbuilt in your PC/laptop)
4. Linux (the following steps were tested on Ubuntu)

Steps

1. Download ntgprs.tar.gz and extract (ntgprs, ntgprs-wvdial.conf and ntgprs-disconnect)
2. Copy the files to /etc/ppp/peers/ (you need root or sudo access)
3. Turn on Bluetooth on your Nokia phone
4. Plug in Bluetooth Dongle to PC or enable it (if inbuilt)
5. Fire up terminal (the commands to be entered are in bold-face):

Make sure the bluetooth is running on PC:

$ hciconfig
hci0: Type: USB
BD Address: 11:11:11:11:11:11 ACL MTU: 672:3 SCO MTU: 48:1
UP RUNNING PSCAN ISCAN
RX bytes:149397 acl:1046 sco:0 events:764 errors:0
TX bytes:40320 acl:628 sco:0 commands:74 errors:0

The following command will find bluetooth address of your phone
$ hcitool scan
Scanning ...
00:0E:6D:C2:99:42 Nokia

Create a RFCOMM port and bind it to phone's Bluetooth address.
$ sudo rfcomm bind /dev/rfcomm0 00:0E:6D:C2:99:42 1

Please note that the bluetooth address in the above command should match the address found by 'hcitool scan' command.

Check if the port has been created
$ rfcomm -a
rfcomm0: 00:0E:6D:C2:99:42 channel 1 closed

Now dial.
$ sudo pon ntgprs

--> WvDial: Internet dialer version 1.60
--> Initializing modem.
--> Sending: ATH
ATH
OK
--> Sending: ATE1
ATE1
OK
--> Sending: AT+CGDCONT=1,"IP","internet","",0,0
AT+CGDCONT=1,"IP","internet","",0,0
OK
--> Sending: AT+CBST=0,0,1;+CHSN=6,0,0,0;+CGDCONT=,,"ntnet"
AT+CBST=0,0,1;+CHSN=6,0,0,0;+CGDCONT=,,"ntnet"
OK
--> Modem initialized.
--> Sending: ATD*99#
--> Waiting for carrier.
ATD*99#
CONNECT
~[7f]}#@!}!} } }2}#}$@#}!}$}%\}"}&} }*} } g}%~
--> Carrier detected. Waiting for prompt.
~[7f]}#@!}!} } }2}#}$@#}!}$}%\}"}&} }*} } g}%~
--> PPP negotiation detected.
Serial connection established.
using channel 9
Using interface ppp0
Connect: ppp0 <--> /dev/rfcomm0
sent [LCP ConfReq id=0x1 ]
rcvd [LCP ConfAck id=0x1 ]
rcvd [LCP ConfReq id=0x0 ]
sent [LCP ConfAck id=0x0 ]
sent [PAP AuthReq id=0x1 user="user" password="pass"]
rcvd [PAP AuthAck id=0x1 ""]
PAP authentication succeeded
sent [IPCP ConfReq id=0x1 ]
rcvd [IPCP ConfReq id=0x0 ]
sent [IPCP ConfNak id=0x0 ]
rcvd [IPCP ConfNak id=0x1 ]
sent [IPCP ConfReq id=0x2 ]
rcvd [IPCP ConfReq id=0x1 ]
sent [IPCP ConfAck id=0x1 ]
rcvd [IPCP ConfAck id=0x2 ]
Cannot determine ethernet address for proxy ARP
local IP address 10.1.4.101
remote IP address 10.0.0.1
primary DNS address 202.70.64.5
secondary DNS address 202.70.64.15
Script /etc/ppp/ip-up started (pid 9902)
Script /etc/ppp/ip-up finished (pid 9902), status = 0x0

To disconnect
$ sudo poff ntgprs

Tuesday, April 07, 2009

Easy bandwidth shaping in Linux

There is an extensive and nicely written HOWTO on this topic but here I'm talking about some really easy to use bandwidth shaping tools -- wondershaper and trickle.

Wondershaper
This is the easiest tool I have found to limit bandwidth of a particular interface. All it takes is,


$ sudo wondershaper {interface} {down} {up}
the {down} and {up} are bandwidth in kilobits. So for example if you want to limit the bandwidth of interface eth1 to 256kbps uplink and 128kbps downlink,

$ sudo wondershaper eth1 256 128
To clear the limit,

$ sudo wondershaper clear eth1
Easy, eh?

Trickle
Unlike wondershaper, which limits the bandwidth to an entire interface, trickle is user-space bandwidth limiting tool. The syntax is,

$ trickle -u {up} -d {down} {program}
Both {up} and {down} and bandwidth in KB/s. Now if you invoke it as,

$ trickle -u 8 -d 8 firefox
It will fire up Firefox, limiting the bandwidth to 8KB/s. This is very useful specially if you are a web developer and want to test your application under various bandwidth conditions.

Furthermore, you can also run trickle as daemon (trickled) which can limit the bandwidth to several programs.

Monday, January 05, 2009

No Wifi to Master-mode

Linux recognizes my wifi card as AR242x and there's no out-of-the-box support till now.

$ lspci | grep 'Wireless'
02:00.0 Ethernet controller: Atheros Communications Inc. AR242x 802.11abg Wireless PCI Express Adapter (rev 01)
However compiling the latest snapshot from madwifi.org works. (Instructions here)
$ wget -c http://snapshots.madwifi-project.org/madwifi-hal-0.10.5.6-current.tar.gz
$ tar xvf madwifi*.tar.gz
$ cd madwifi*r*

$ sudo make install
$ sudo modprobe ath_pci
$ sudo modprobe wlan_scan_sta
Cool. But the problem is no other modes except managed-mode seem to work.
$ sudo iwconfig ath1 mode ad-hoc
Error for wireless request "Set Mode" (8B06) :
SET failed on device ath1 ; Operation not permitted.
I was little curious about this as every wireless card supports at least ad-hoc mode if not managed. So I did a lil' diggin into madwifi's source code and found out that it supports all modes including master (or ap) mode too. This was quite startling to me coz i've been told that Master (or AP) mode is only for dedicated Wireless APs or expensive wireless cards.

Madwifi comes with nice wlanconfig tool.
$ wlanconfig
usage: wlanconfig athX create [nounit] wlandev wifiY
wlanmode [sta|adhoc|ap|monitor|wds|ahdemo] [uniquebssid]
usage: wlanconfig athX destroy
usage: wlanconfig athX list [active|ap|caps|chan|freq|keys|scan|sta|wme]
Now to start AP mode,
$ sudo wlanconfig ath1 destroy
$ sudo wlanconfig ath1 create wlandev wifi0 wlanmode ap
Now set the ESSID for the wireless network and IP for the interface
$ sudo ifconfig ath1 192.168.0.1
$ sudo iwconfig ath1 essid 'TestAP'
Voila! It worked and I can connect to this AP from another computer, set the IP to 192.168.0.x range and ping too. Now I'm wondering if AP mode is available in every card but is restricted by software so that ppl are forced to buy expensive APs.

Thursday, January 01, 2009

Battery charged notification

Load-shedding is driving us nuts! My solution is to move all my works to laptop and buy a spare battery. I think this is more cost effective and energy saving than buying expensive inverters. I've got an extra 8-cell battery for my laptop and altogether I have 6+ hours of backup.

But the problem is I keep forgetting to charge the batteries. The one in laptop starts charging when light is back but when it's done charging I forget to switch battery.

The solution lies at /proc/acpi/battery/BAT1/state

$ cat /proc/acpi/battery/BAT1/state
present: yes
capacity state: ok
charging state: discharging
present rate: 1342 mA
remaining capacity: 2201 mAh
present voltage: 11432 mV
Our line of concern is 'charging state:' which can have one of three values - charging, discharging or charged. So here's a simple bash script to monitor this file for charged state and pop a message to switch the battery.

#!/bin/sh

charged=0
while : ; do
if grep -iq 'charged' /proc/acpi/battery/BAT1/state
then
# nofify if previous state is uncharged
if [ $charged = 0 ] ; then
zenity --info --text "Battery charged. You might wanna charge another."
fi
charged=1
else
charged=0
fi
sleep 5m # wait for 5 minutes
done
Now put this program to System > Preferences > Sessions > Startup Programs.

Thursday, December 25, 2008

Gnome: drag text to file

Got this one by accident. In Gnome, if you drag some text and drop it to desktop or nautilus, it creates a file with the dragged text in it. Simple, but might come handy sometimes..

Drag the text

After dropping, you land into file rename mode :)

Saturday, November 29, 2008

Fedora 10 Cambridge Release Party

Last Tuesday (Nov, 25th) marked the release of yet another edition of Fedora (v10, Cambridge) and today we gathered at IOE, Pulchowk Campus to celebrate the Release party.

We had several events to mark the celebration. Apart from the introductory and 'formal' stuffs, we had a race (yup, a real one), lucky draw for Fedora t-shirts and pendrives (which fortunately I didn't win, that obviously would be against nature's will) and a candlelight display of Fedora logo. It was awesome!

Although Ubuntu is the distro of my choice nowadays, I was a loyal Fedora user from the very first to the sixth edition. The one thing that still fascinates me about Fedora is the incredible and vibrant artwork it has. Provided a good marketing and more easier installation methods (like wubi), I believe Fedora has the potential to be the ultimate killer-distro!

Thursday, November 27, 2008

Merging PDF files in Linux

Sometimes you might have to merge two or more pdf files into one single pdf document. While there are commercial softwares like Adobe Acrobat or something similar to do the job, it's much simpler in Linux using commandline. There are several softwares for the job and most of them require simple one line command!

The following commands merge first.pdf and second.pdf to merge.pdf. You can also merge more than two files using similar command.

Using Ghostscript
Ghostscript is a PostScript and PDF language interpreter and previewer. You can do quite handful tasks related to ps and pdf files with Ghostscript; merging happens to be one of them.

gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=merged.pdf -dBATCH first.pdf second.pdf

Using ImageMagick
ImageMagick is basically an image manipulation software but it also handles pdf files.

convert first.pdf second.pdf merged.pdf

Using PDFTk
If PDF is electronic paper, then pdftk is an electronic staple-remover, hole-punch, binder, secret-decoder-ring, and X-Ray-glasses. Pdftk is a command-line tool for doing everyday things with PDF documents.

pdftk first.pdf second.pdf cat output merged.pdf

Using pdf2ps and ps2pdf
pdf2ps and ps2pdf comes with Ghostscript. The former converts pdf file to ps and latter the reverse. We can use them to first convert pdf files to ps format, merge all ps files and then converting ps file back to pdf.

pdf2ps first.pdf first.ps
pdf2ps second.pdf second.ps
cat first.pdf second.ps > merged.ps
ps2pdf merged.ps merged.pdf


If you are looking for some GUI version, there's a Nautilus script which acts as frontend to PDFTk. If you are on KDE, Kommander script is also available (also depends on PDFTk)


NOTE: To install Ghostscript (already installed in most distros by default), ImageMagick or PDFTk in Linux,

sudo apt-get install ghostscript
sudo apt-get install imagemagick
sudo apt-get install pdftk

Sunday, November 02, 2008

Getting out of Failsafe mode

Few days ago, for no implicit reason my GNOME installation refused to start. Failsafe mode worked but normal login would throw me back to login screen. Online forums recommended me to check my session scripts and all. But lazy me, i did the following in the terminal.

cp -r /etc/skel/* ~
/

What i did was recovered the skel(eton) home folder files and it worked! I lost few settings related to Compiz but rest were all in place.

Tuesday, July 08, 2008

debugfs and rdump

If you have broken ext2/ext3 filesystem, these two commands can be your lifesaver. Atleast it brought my friend Abish's HDD 'out of coma' ;)

He had his important files in an ext3 filesystem which wasnt being mounted. It turned out that it had its journal broken. Did everything from disabling the file system's journal to trying out alternate superblocks. Even tried to convert it to ext2 format. fsck.ext3 didnt seem to repair a thing and hacks using tune2fs also didnt turn out good. We were on verge of finally letting go of data and formatting the hdd.

Then i found debugfs. The man page reads,

debugfs - ext2/ext3 file system debugger. The debugfs program is an interactive file system debugger. It can be used to examine and change the state of an ext2 file system.

Surprisingly debugfs seemed to list the files and folders of the filesystem. Cool enough, it also has a tool called rdump which recursively dumps a folder to another mounted disk.

So after invoking

# debugfs /dev/sda1
debugfs: rdump /home/ /mnt/externalhdd


and all the files were dumped to the external hdd safely. Simple, yet awesome!

PS: Me, Abish and Tushar were together when the recovery happened. Abish was so happy he took us all for a tea party right away. But no shops were open. Can you guess why? It was 2 at night!