"; */ ?>

tutorials


12
Jul 08

Install rtGui on Ubuntu

rtorrent project logortGui is a web based front end for rTorrent – the Linux command line BitTorrent client. It’s written in PHP and uses XML-RPC to communicate with the rTorrent client.

There are several guides on how to install rtGui on Ubuntu or just POL (Plain Old Linux), but all of them seem to be missing one or two things to make them complete.

Here I went from scratch, step by step to install rtGui on Ubuntu (actually KUbuntu, and to be more specific linuxMCE but it would not matter in this case, since this guide is for any more or less recent Ubuntu distro). I tried to make this guide as complete as possible so it does not miss any installation steps, and if you have any questions/comments, you are welcome to post them in comments section. Now sit back, relax and… let’s get to work! :)

Step 1.  Install PHP with XML-RPC and a SCGI apache module:

sudo apt-get install php5 php5-xmlrpc libapache2-mod-scgi

Step 2. Edit Apache default server config:

sudo vi /etc/apache2/sites-enabled/000-default

(If you are using linuxMCE, edit /etc/apache2/sites-enabled/pluto file instead)
Add the following lines, above the last “</VirtualHost>” (or download example from http://rtgui.googlecode.com/files/000-default ):

LoadModule scgi_module /usr/lib/apache2/modules/mod_scgi.so
SCGIMount /RPC2 127.0.0.1:5000

Restart apache:

sudo apache2ctl restart

Step 3. Create .rtorrent.rc file – see http://libtorrent.rakshasa.no/browser/trunk/rtorrent/doc/rtorrent.rc?rev=latest or download example from http://rtgui.googlecode.com/files/.rtorrent.rc and save to your home directory – ~/.rtorrent.rc

* make sure .rtorrent.rc has this line:

scgi_port = 127.0.0.1:5000

Step 4. Create directories for rtorrent to use, and change the ownership to the user that runs rtorrent:

mkdir /Torrents /Torrents/Downloading /Torrents/Downloading/rtorrent.session
/Torrents/Complete /Torrents/TorrentFiles /Torrents/TorrentFiles/Auto
chown username /Torrents /Torrents/Downloading /Torrents/Downloading/rtorrent.session
/Torrents/Complete /Torrents/TorrentFiles /Torrents/TorrentFiles/Auto

* here “username” is the user who will run rtorrent 

Step 5. Instal XML-RPC library:

sudo apt-get install libxmlrpc-c3-dev
sudo apt-get install libxmlrpc-c3

Step 6. Install latest version of both – libtorrent & rtorrent:

NOTE: Depending on packages installed on the system, you might need these dependencies:

sudo apt-get install libncurses5-dev libsigc++-2.0-dev libcurl4-openssl-dev build-essential

Download latest version (X.Y.Z) of libtorrent from http://libtorrent.rakshasa.no/downloads/ into /usr/local/ directory:

wget http://libtorrent.rakshasa.no/downloads/libtorrent-X.Y.Z.tar.gz
sudo tar xvf libtorrent-X.Y.Z.tar.gz
cd libtorrent-0.11.1
 
sudo ./configure
sudo make
sudo make install

Download rtorrent latest version (X.Y.Z) from http://libtorrent.rakshasa.no/downloads/ in /usr/local/ directory.

wget http://libtorrent.rakshasa.no/downloads/rtorrent-X.Y.Z.tar.gz
sudo tar xvf rtorrent-X.Y.Z.tar.gz
cd rtorrent-X.Y.Z
 
sudo ./configure --with-xmlrpc-c
sudo make
sudo make install

* make sure  you configure rtorrent with “–with-xmlrpc-c” option

After the above 6 steps we are ready to install rtGui (and other GUIs for rtorrent: wTorrent, etc..)

Step 7. Install rtGui:

Download rtgui from http://code.google.com/p/rtgui/downloads/list
Extract files to webserver directory:

sudo tar xvzf ~/rtgui-0.2.3.tgz -C /var/www

* 0.2.3 is the current version at the moment of writing

You can edit “/var/www/rtgui/config.php” if you’d like to change rtGui default settings. Most of the time you don’t have to.

*** Step 8. Start rtorrent:

rtorrent

Step 9. Done! :) Open your browser, and go to http://localhost/rtgui/

*** (!) Since rtGui talks to rtorrent via XML-RPC gateway, rtorrent has to be started – otherwise rtGui has nobody to talk to :) In case rtorrent is not started when you accessing rtGui via web browser, you would get:

Warning: file_get_contents(http://localhost/RPC2) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in /var/www/rtgui/functions.php on line 10

This is because there is nobody listening on port 5000 – remember the line “scgi_port = 127.0.0.1:5000″ in .rtorrent.rc? We have configured rtorrent with ” –with-xmlrpc-c” option, hence when rtorrent is up and running it will listen on “scgi_port” (in this case 5000) and will be able to handle XML-RPC requests/responses.

Happy rTorrenting!


10
Jul 08

Restore/Format USB Flash Drive

Who does not have a flash memory USB drive? (128Mb – 16Gb…) Everybody does, even my dog, if I had one, would have it. However, sometimes these little dongles can be tricky to use if they are not properly formatted. The usual format for the flash memory USB drive is FAT16, and it is understood by many operating systems with no problem. But in case the drive is not formatted properly/or you think it is not formatted properly, you can always reformat it, and here is how.

The whole process consists of 5 steps ans takes about 15 seconds um.. if do it slowly.. :)

In case you need to find the actual device your USB drive was associated with look here “Find USB flash device/drive in Linux

WARNING: All the data will be lost from the flash UBS drive since we are going to reformat it.

We are going to use fdisk utility, so “for starters” here are available commands that you can use with fdisk:

a – toggle a bootable flag
b – edit bsd disklabel
c – toggle the dos compatibility flag
d – delete a partition
l – list known partition types
m – print this menu
n – add a new partition
o – create a new empty DOS partition table
p – print the partition table
q – quit without saving changes
s – create a new empty Sun disklabel
t – change a partition’s system id
u – change display/entry units
v – verify the partition table
w – write table to disk and exit
x – extra functionality (experts only)

Now let’s get to cooking a new and fresh flash memory USB drive…

Step 1. Run fdisk via sudo on your USB flash drive device:

user@host:~$ sudo fdisk /dev/sdb

enter “p” command to list current partition table of the USB drive:

Command (m for help): p
 
Disk /dev/sdb: 1039 MB, 1039663104 bytes
32 heads, 62 sectors/track, 1023 cylinders
Units = cylinders of 1984 * 512 = 1015808 bytes
Disk identifier: 0xf1f494df
 
Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1        1023     1014785   83  Linux

Here you will see whatever partition (if any) currently present. In my case (above) it is a “Linux” partition, in your case it may be something different. But it does not really matter, because we are going to delete it anyway:

Step 2. Enter “d” command to delete existing partition (if you have any). If you have several, delete several by using”d” command multiple times:

Command (m for help): d
Selected partition 1

Step 3. Now let’s get to business and enter “n” command to create a new partition:

Command (m for help): n
Command action
e   extended
p   primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-1023, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-1023, default 1023):
Using default value 1023

As you can see from above, I entered “1” for “Partition number”, and hit enter key twice to leave everything by default.

Now let us list current partitions with “p” command again:

Command (m for help): p
 
Disk /dev/sdb: 1039 MB, 1039663104 bytes
32 heads, 62 sectors/track, 1023 cylinders
Units = cylinders of 1984 * 512 = 1015808 bytes
Disk identifier: 0xf1f494df
 
Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1        1023     1014785   83  Linux

We have a single “Linux” partition which is fine (for now).

Step 4. Time to actually apply our changes, so enter a “w” command that will write out all the changes to the USB drive.

Command (m for help): w
The partition table has been altered!
 
Calling ioctl() to re-read partition table.
Syncing disks.

fdisk will write all the changes to the USB drive and exit. But we are not done yet. Our goal is to make a (in this case) FAT16 partition, so this USB drive can be read by most operating systems.

Step 5. For that we will use mkfs.vfat utility:

user@host:~$ sudo mkfs.vfat -F 16 /dev/sdb1
mkfs.vfat 2.11 (12 Mar 2005)

Now we are good to go! It was easy, as I promised :)

Let’s look at the new USB drive now. Mounting it first:

user@host:~$ sudo mount /dev/sdb1 /mnt/flashka/
user@host:~$ cd /mnt/flashka/
user@host:/mnt/flashka$ ls -l
total 0

Checking what it has under the hood:

user@host:/mnt/flashka$ df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/sdb1             991M     0  991M   0% /mnt/flashka
 
user@host:/mnt/flashka$

It has 991Mb which is what they call 1Gb flash memory USB drive! :)


9
Jul 08

Spring Web Application Context Visibility

spring framework logoWhile developing a Web App using Spring little things can take a lot of time to resolve. At the end they may appear to be very simple, and you may ask your self “how could I not think of it before – it is so obvious!”. Well, yea, it is obvious, but you just have to know it! One of the places that helps you to solve the “obvious” (and not so obvious), so you do not have to spin your wheels is, with no doubts, the spring forum. However you need to know the right search criteria to find what you need.

Here I just want to share something small but important about the visibility of Spring Contexts in a Web App.

Looking at org.springframework.web.servlet.DispatcherServlet API notice this:

“A web application can define any number of DispatcherServlets. Each servlet will operate in its own namespace, loading its own application context with mappings, handlers, etc. Only the root application context as loaded by ContextLoaderListener, if any, will be shared.”

This brings an interesting point – in a Spring Web App you have one root application context which is private, and many dispatcher servlet application contexts which are children of the root application context:

<context-param>
<param-name>contextConfigLocation</param-name>
   <param-value>
      /WEB-INF/classes/applicationContext.xml
      /WEB-INF/classes/otherContext.xml
   </param-value>
 </context-param>
 
...
 
 <servlet>
  <servlet-name>context</servlet-name>
  <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 
...
 
 <servlet>
  <servlet-name>dispatcher-servlet-number-x</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
 </servlet>

In the above, everything that is defined in “contextConfigLocation” is your root application context. Every “dispatcher-servlet-number-x” (“dispatcher-servlet-number-1”, “dispatcher-servlet-number-2”, etc..) would represent a child application context which will see (have the visibility to) all the beans from the parent (root) context, but will not see any of the beans defined by its siblings – another dispatcher servlet contexts.

The only gotcha in the above visibility is BeanFactoryPostProcessor / BeanPostProcessor (s) – like “PropertyPlaceholderConfigurer” for example. These guys apply ONLY to beans in its own context. For example, if you have PropertyPlaceholderConfigurer defined in the root application context, none of root’s children will be able to use it (see) the ${properties}.

Here is the semi-official version “why” from Juergen (Spring Lead Developer):

“PropertyPlaceholderConfigurer is an implementation of the BeanFactoryPostProcessor interface: This interface and its sibling BeanPostProcessor just apply to the BeanFactory that defines them, that is, to the application context that defines them.

If you combine multiple config files into a single contextConfigLocation, a PropertyPlaceholderConfigurer defined in any of the files will apply to all of the files, because they are loaded into a single application context.

However, a DispatcherServlet has its own application context, just using the root web application context as parent. Therefore, it needs to define its own BeanFactoryPostProcessors and/or BeanPostProcessors, in this case its own PropertyPlaceholderConfigurer.”

Happy Springing!


28
May 08

Generate XSD from XML

There are several tools out there to create (or to infer) an XSD schema from XML document. I liked trang command line tool the most. Found it first when reading about Spring web services in Spring in Action book (very good book btw).

Here are four simple steps how to create XSD from XML* using trang:

Step 1. Get trang

Download trang.zip from here (at the moment of writing “trang-20030619.zip”)

Step 2. Extract it

Use “unzip trang-version.zip”, or just winzip/winrar/7z etc.. if on windows

Step 3. Make an alias

This step is optional, but makes it extremely easy to run the tool with a single command. Make an alias to the “trang.jar” by (in my case Ubuntu/Linux) editing “~/.bashrc” and adding the following:

# execute trang.jar (create XSD from XMLs)
alias xml2xsd='java -jar ~/soft/utils/trang/trang-20030619/trang.jar'

above “~/soft/utils/trang” is the directory where “trang” was unzipped to.

Step 4. Create XSD from XML

Let’s look at the XML file we need an XSD for:

$ ls -l
total 4
-rw-r--r-- 1 user group 357 2008-05-28 15:38 holiday-request.xml
 
$ cat holiday-request.xml
<?xml version="1.0" encoding="UTF-8"?>
<holidayRequest xmlns="http://mycompany.com/hr/schemas">
    <holiday>
        <startDate>2006-07-03</startDate>
        <endDate>2006-07-07</endDate>
    </holiday>
    <employee>
        <number>42</number>
        <firstName>Ultimate</firstName>
        <lastName>Answer</lastName>
    </employee>
</holidayRequest>

now run the tool against it:

$ xml2xsd holiday-request.xml hr.xsd
$ cat hr.xsd
<?xml version=”1.0″ encoding=”UTF-8″?>
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema” elementFormDefault=”qualified” targetNamespace=”http://mycompany.com/hr/schemas” xmlns:schemas=”http://mycompany.com/hr/schemas”>
  <xs:element name=”HolidayRequest”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Holiday”/>
        <xs:element ref=”schemas:Employee”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Holiday”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:StartDate”/>
        <xs:element ref=”schemas:EndDate”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”StartDate” type=”xs:NMTOKEN”/>
  <xs:element name=”EndDate” type=”xs:NMTOKEN”/>
  <xs:element name=”Employee”>
    <xs:complexType>
      <xs:sequence>
        <xs:element ref=”schemas:Number”/>
        <xs:element ref=”schemas:FirstName”/>
        <xs:element ref=”schemas:LastName”/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name=”Number” type=”xs:integer”/>
  <xs:element name=”FirstName” type=”xs:NCName”/>
  <xs:element name=”LastName” type=”xs:NCName”/>
</xs:schema>

done!

$

* – NOTE: “trang” can create an XSD from multiple XML documents, not just one.

List of other tools to use as an alternative to trang:

XSD away, Good Luck!


22
Apr 08

Creating Public and Private Certificates/Keys

Public and Private Key PairHave you ever tried to communicate with somebody/something through any kind of technology? Most of the time “those” people/systems like privacy, in a way that they like their communication with everybody including you to be private. Hence once you want to communicate with them they give you something called a “public key” ( or “public-key certificate” ) and ask you to give them yours. Usually when you talk to different sources, nobody would guide you through on how to create that “public key” of yours, “they” would just want it, but you would be left alone to figure out how you should generate it.

Hence this little guide will show you one of many ways on how to generate a pair of X.509 public/private keys, and how to access this magic pair to get that “public key”, so it can be given to anyone who needs it.

First, let us throw a couple of sentences on how these keys are used. It is actually very simple – there is “YOU” and “THEY”:

  • YOU: generate a pair of public/private keys (where whatever is encrypted with your public key can only be decrypted with your private key)
  • YOU: hide your private key from everybody
  • YOU: give your public key to anybody who wants to communicate with you
  • THEY: generate a pair of public/private keys
  • THEY: hide their private key from everybody including YOU
  • THEY: give their public key to anybody who wants to communicate with them

Now when YOU and THEY have each others public keys and their own private keys communication may begin:

  • YOU: write your secret message, encrypt it with THEIR public key and send to them
  • THEY: receive your top secret message and using THEIR private key decrypt it
  • THEY: write you an answer, encrypt it with YOUR public key, and send to you
  • YOU: receive their top secret response and using YOUR private key decrypt it

Told you it is very simple!

Now let’s see how to do the magic – how to generate a pair of YOUR public and private keys.

There are number of ways – tools/libraries/code snippets/etc.. I would show you one of the simplest ways how this can be archived using a tool called… any guess? Yes – a “keytool” – make sense, right?

“keytool” is a java tool that has a great manual, and since its java – it’ll work on any OS that has JVM. In order to get/download a keytool, you just have to install Java (JRE) on your system (95% that you already have it installed, hence you can go ahead and use “keytool” without needing to install/download anything else).

Examples here are run on Linux (Ubuntu), but as long as you have Java installed, it does not really matter what OS you have to get the job done.

So, fire up the terminal (Windows’ “cmd”) and let’s generate a pair of public/private keys now:

$ keytool -genkey -alias otherguy -keypass p@ssw0rd -keystore our.keystore
Enter key store password: ksp@ssw0rd
 
You are about to enter information that will be incorporated into
your certificate request.  This information is what is called a
Distinguished Name or DN.  There are quite a few fields but you
can use supplied default values, displayed between brackets, by just
hitting &lt;Enter&gt;, or blank the field by entering the &lt;.&gt; character
before hitting &lt;Enter&gt;.
 
Common Name (hostname, IP, or your name): myname
Organization Name (company) [The Sample Company]: my company
Organizational Unit Name (department, division): department of departments
Locality Name (city, district) [Sydney]: gorodok
State or Province Name (full name) [NSW]: state of new noisy
Country Name (2 letter code) [AU]: zz

As you might figured already, a keystore is a small database, that we just created, that would hold all the keys (private/public) for many systems – right now we only have one pair, but later we can add more keys to the keystore. So let’s look at this keystore that we just generated:

$ ls -l
total 4
-rw-r--r-- 1 user group 1641 2008-04-22 20:46 our.keystore

But now you need to be able to access this “database” to get a public key, so you can share it with others. It is done by exporting this public key – again, very simple:

$ keytool -export -rfc -alias otherguy -file us-to-otherguy.cer -keystore our.keystore
Enter key store password: ksp@ssw0rd

let’s see what files we have now:

$ ls -l
 
total 8
-rw-r--r-- 1 user group 1641 2008-04-22 20:46 our.keystore
-rw-r--r-- 1 user group 1189 2008-04-22 20:48 us-to-otherguy.cer

And here it is (!) your public key certificate – “us-to-otherguy.cer”. Let’s see what’s inside:

$ cat us-to-otherguy.cer
-----BEGIN CERTIFICATE-----
MIIDQjCCAwGgAwIBAAIBATAJBgcqhkjOOAQDMIGGMQ8wDQYDVQQDDAZteW5hbWUxEzARBgNVBAoM
Cm15IGNvbXBhbnkxIjAgBgNVBAsMGWRlcGFydG1lbnQgb2YgZGVwYXJ0bWVudHMxEDAOBgNVBAcM
B2dvcm9kb2sxGzAZBgNVBAgMEnN0YXRlIG9mIG5ldyBub2lzeTELMAkGA1UEBgwCenowHhcNMDgw
NDIzMDA0NjM4WhcNMDgwNzIyMDA0NjM4WjCBhjEPMA0GA1UEAwwGbXluYW1lMRMwEQYDVQQKDApt
eSBjb21wYW55MSIwIAYDVQQLDBlkZXBhcnRtZW50IG9mIGRlcGFydG1lbnRzMRAwDgYDVQQHDAdn
b3JvZG9rMRswGQYDVQQIDBJzdGF0ZSBvZiBuZXcgbm9pc3kxCzAJBgNVBAYMAnp6MIIBuDCCASwG
ByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2N
WPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P2
08UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA
9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3
zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKL
Zl6Ae1UlZAFMO/7PSSoDgYUAAoGBAPDA5E5GVGzMBw3IWldpyGBs8Dwr7ArYdNRIPH7veELcENhO
7jNdBinJ/JUCcY0XoIhNVXVNkyABpGsBISfGPwgv1meyLcs0DK6ndEDBYGH0Cwoahhtb7EBhcqWQ
kqojyVtPRdNTPd8cyPDjbOOapv65+8Xe0FQoCtJXWiwF8Z17MAkGByqGSM44BAMDMAAwLQIVAJHL
9Syzc8LIEp6uNjVI+f/ox4dhAhQOug96d7B5V/rGytlAJiml9f8Qqg==
-----END CERTIFICATE-----

that is exactly what you send to everybody else to encrypt their secret messages!

The last thing that I want to show you is how to see what’s inside the keytore database:

$ keytool -list -v -keystore our.keystore
Enter key store password: ksp@ssw0rd
Key store type: gkr
Key store provider: GNU-CRYPTO
 
Key store contains 1 entry(ies)
 
Alias name: otherguy
Creation timestamp: Tuesday April 22, 2008 AD - 8:46:38;616 o`clock PM EDT
Entry type: key-entry
Certificate chain length: 1
Certificate[1]:
Owner: CN=myname,O=my company,OU=department of departments,L=gorodok,ST=state of new noisy,C=zz
Issuer: CN=myname,O=my company,OU=department of departments,L=gorodok,ST=state of new noisy,C=zz
Serial number: 1
Valid from: Wednesday April 23, 2008 AD - 1:46:59;989 o`clock AM EDT
until: Tuesday July 22, 2008 AD - 1:46:59;990 o`clock AM EDT
Certificate fingerprints
MD5: BB:35:C0:6B:D0:B2:67:26:BF:AB:AD:5A:87:51:AA:32
SHA-160: 19:67:F9:8B:DF:52:24:4A:61:4D:76:1C:79:2E:4B:5B:8E:A8:AA:E1
 
*******************************************

Here you can see that a public certificate that we exported is ” Valid from: Wednesday April 23, 2008 until: Tuesday July 22, 2008″, hence 90 days. That means it will need to be changed in 90 days, which would also, of course mean you would have to issue a new certificate to all your contacts in 90 days. In order to change this time frame, when generating a keystore, just add a “-validity <number of days>”when generating keys:

$ keytool -genkey -alias otherguy -keypass p@ssw0rd -keystore our.keystore -validity 3600

that would create a pair valid for 3600 days from the current date.

What if somebody wants to share secret with you? Well, now you are ready! :)