Monday, November 19, 2007

Simple But intriguing

1) How does one create a file starting with hyphen(-)?
2) How does one remove a file starting with hyphen(-)?

My Solution
bash-2.05$touch a
bash-2.05$tar cvf -c.tar a
2)bash-2.05$ rm ./-c.tar

Saturday, October 27, 2007

How can a host determine what address mask is in use on a remote host without logging in?

Interestingly, icmp is so powerful , that it can get us this information.

RFC 792 does not mention about the Address Mask( or type 17/18). However RFC 950 has the inherent rationale(Section 2.3) for embedding this option in icmp.

Using nemesis the solution can be seen in action outright.

@SOURCE_MACHINE>/usr/local/bin/nemesis icmp -qM -i 17 -m 0 -S -D -H 0:3:ba:4e:40:44 -M 00:03:ba:5b:8f:5d

ICMP Packet Injected

@SOURCE_MACHINE>snoop icmp
Using device /dev/eri (promiscuous mode)
DESTINATION_MACHINE -> SOURCE_MACHINE ICMP Address mask reply (Mask = 0xffffff00)

Thursday, October 18, 2007

My failed experiment to detect nodes in Promiscious mode.

Basic Prerequisites: Promiscuous mode,ARP, ICMP and Packet Injection.

The decision to accept/drop the network packets is controlled by the Network Interface Card(NIC). NIC filters out the desired packets which system is entitled to recieve. However by setting the NIC to promiscuous mode the sniffing application receives packets regardless of the system being the intended destination. Sniffing is a difficult problem to acertain as it does not interfere with the network traffic, leaving no digital traces to track.

My Approach in theory
A “dynamic” protocol like Address Resolution Protocol (ARP) can be leveraged to detect the sniffing host. This protocol works alongside the Internet Protocol(IP) in Layer 3. On account of this ARP's operation occurs automatically in the background, without concern to the application user.

ARP works by sending an address request and collecting the response to create its mapping of addresses. The hardware addresses are only needed for hosts on the local network. At the lowest level, the Ethernet driver needs the hardware address of the remote system to which it will send a packet. When it does not have that address, it “broadcasts” a request for the missing address. This request, called an “ARP request”, contains the IP address of the host in question and is sent to all systems on the local network. A system may respond with a reply, called an “ARP reply”, which contains the host IP address and hardware address. The response received is used to build a table of IP addresses and hardware addresses.

Another feature of the protocol is called “gratuitous ARP”. This occurs when a host broadcasts an ARP request for its own hardware address. A Solaris system does this at boot time. It is used to detect if another system is using its IP address, indicating a misconfigured system. The other use of gratuitous ARP is to send updated
hardware address information. Systems that receive requests like this will automatically update the hardware address information for that host.

ARP by default uses BROADCAST method to get the destination MAC address. The idea here is to craft an ARP packet with the destination address being a non-BROADCAST address with a specific target IP address. If the NIC is in non-promiscuous mode, the packet is ignored and after the specified TTL no response is got back. However if the node with the corresponding IP address is in promiscuous mode, a prompt response is given by the sniffing host as the packet is percolated to the higher layers.

Using a handcrafted packet like ICMP with appropriate fields can induce the same effect.

-Defeating Sniffers and Intrusion Detection Systems

-Plummer, Dave. An Ethernet Address Resolution Protocol, RFC 826, Network
Information Center, SRI International, Menlo Park, CA., November 1982.

- Interetworking with TCP/IP VolumeII Design,Implementation and Internals. Douglas E. Comer/David L. Stevens

-Solaris Operating Environment Network Settings for Security , By Alex Noordergraaf and KeithWatson

The Reality ( Getting the hands dirty )
Destination Machine
eri0 DESTINATION-MACHINE 00:03:ba:5b:8f:5d
@SOURCE-MACHINE>ping -s !$
64 bytes from DESTINATION-MACHINE ( icmp_seq=0. time=1.26 ms
64 bytes from DESTINATION-MACHINE ( icmp_seq=1. time=0.920 ms
2 packets transmitted, 2 packets received, 0% packet loss
round-trip (ms) min/avg/max/stddev = 0.920/1.09/1.26/0.24

Source Machine

@SOURCE-MACHINE>ifconfig -a
lo0: flags=2001000849 mtu 8232 index 1
inet netmask ff000000
eri0: flags=1000843 mtu 1500 index 2
inet netmask ffffff00 broadcast
ether 0:3:ba:4e:40:44

Packet Injection

@SOURCE-MACHINE>/usr/local/bin/nemesis icmp -S -D -H 0:3:ba:4e:40:44 -M 00:03:ba:5b:8f:5d

ICMP Packet Injected

@SOURCE-MACHINE>snoop icmp

SOURCE-MACHINE -> DESTINATION-MACHINE ICMP Echo request (ID: 15815 Sequence number: 46167)
DESTINATION-MACHINE -> SOURCE-MACHINE ICMP Echo reply (ID: 15815 Sequence number: 46167)

Now sending a wrong MAC address to Destination ( last letter changed from d to e )

@SOURCE-MACHINE>/usr/local/bin/nemesis icmp -S -D -H 0:3:ba:4e:40:44 -M 00:03:ba:5b:8f:5e

ICMP Packet Injected

@SOURCE-MACHINE>snoop icmp
Using device /dev/eri (promiscuous mode)
SOURCE-MACHINE -> DESTINATION-MACHINE ICMP Echo request (ID: 12112 Sequence number: 10553)

Interesting thing to note was that the Packet was seen in the snoop output on DESTINATION-MACHINE but was not replied.

There goes the failed experiment. Reality turns out to be different than the assumed theory. Digging further as to how snoop manages to get a snapshot of the packet and not process the packet.

Thursday, October 04, 2007

Getting the Kth smallest element in two Sorted Lists

Let A and B be two sorted arrays. The intent is to find the kth smallest number in the union of the two lists.

Sounds Simple, but the catch is to get it done with a better time complexity than O(size(A) + size(B)).

I now have the solution which works with O(log(size(A) + size(B)), but i gave a crappy solution to my friend who gave me this puzzle. I used the intuitive, 2 pointer solution. Dont fall for it.

Tuesday, October 02, 2007

Implementing a queue with 2 Stacks

Interesting, but intuitive question.

My Solution:-


import java.util.Stack;

public class QueueWith2Stacks {

Stack< Object> insertStack=new Stack< Object>();
Stack< Object> popStack=new Stack< Object>();

void enqueue(Object element){
Object dequeue(){
if(popStack.empty()&& insertStack.empty())
if(popStack.empty())//This is the only interesting part about it.
void display(){

Sunday, August 12, 2007

Configuring SSO

After analyzing JOSSO and CAS as candidates for SSO , the JOSSO implementation seems very promising.
What is SSO ?


1) Just works. Can easily embed my application to the SSO framework.
2) Out-of-the box seem less integration with custom made tomcat. Inbuilt SSL configurations.
3) To-Do steps
i) Download Josso tomcat
ii) Refer to
iii)\conf\jaas.conf (Spent a romantic night for this. Had to write it )
iv) For getting the login data from the DB refer to this

1) Pathetic Docs
2) In-active community.

I could not get CAS working on my system. I know it works, but somehow the jigsaw is not complete. The community is very active and vibrant.Updated wiki . Let me know if anyone gets it working.

Thursday, August 09, 2007

"C" the Bug - Part I

1. Find the bug.

All necessary Headers included like stdio.h, stdlib.h, string.h etc.

int main()
char *str = NULL;
int i = 1;
str = (char*)malloc(sizeof(char)*2);
if(!str) {
printf("Malloc Failed\n");
strcpy(str, "Hi");
printf("%c\n", str[i*i+i/i]);
str = (char *)realloc(str, sizeof(char)*20);
if(!str) {
printf("Realloc Failed\n");
strcpy(str, "Hello World\n");
i = 2;
printf("%c\n", str[i*i+i/i]);
return 0;

2. In a doubly linked list, the nodes are paired and these pairs have to be reversed.

For Ex: If the linked is as below,
Output should be:

Struct is as below:
typedef struct node {
int data;
struct node *next;
struct node *prev;

Handle all the conditions. This question was asked in Microsoft Interview.
Deadline is on 18th Aug 2007.
Send it to me at or post in the comment.

Challenging the Code
* You need to have trust in me.
* Specify in your mail or comments as "Challenge".
* Rs.50/person.
* Max. challenge amount = Rs.(No. of Persons challenging * 50). Conditions Apply.
* If your code breaks under any conditions, you will lose the amount.
* If your code works smooth, you will win the Total Challenged amount.
The challenge amount increases if anyone supports me. Specify in your mail or comments as "Support". For those supporting me will definitely get a share if someone loses the challenge.

If not interested in challenge or support, you can also mail or post comment as "Fun".

Friday, August 03, 2007

Curiously Recurring Template Pattern (CRTP)

The funny named phrase is used to describe the use of a derived class type as a template parameter for its own base class! In simplest form, this is what I'm talking about:

template < typename T >
class Base{ };

class Derived : public Base< Derived > { };

Let me give a very simple example of where this might be useful. Suppose you want to keep track of how many objects of a particular class are alive at any point in time:

Simple approach is:
1) Keep a private static "count" member in the class
2) Increment the count in every constructor
3) Decrement the count in the destructor
4) Provide a public interface to query the value of the count

This approach is fine. However you have to do this for every class that you want to count the objects of. CRTP can pitch in and provide an elegant solution that is highly reusable.

template < typename CountedType >
class ObjectCounter
    static int counter;

      ++( ObjectCounter< CountedType >::counter );

    ObjectCounter( const ObjectCounter< CountedType >& obj )
      ++( ObjectCounter< CountedType >::counter );

      --( ObjectCounter< CountedType >::counter );

    static int live()
      return ObjectCounter< CountedType >::counter;

template < typename CountedType >
int ObjectCounter< CountedType >::counter = 0;

Any class that wants to do object counting will inherit from the above class as follows:

class TestClass : public ObjectCounter< TestClass >{ };

TestClass::live() will give the number of objects alive at that point in time.

Friday, July 13, 2007

American Way v/s Russian Way

The joke is that America [NASA] spent millions of dollars on developing a pen that would write in outer space, while the Russian Cosmonauts simply used pencils.

The below mail conversation would tell why I mentioned the above joke.
[American Way]


After several installations of SuSE Linux Enterprise Server-10 Service Pack-1 on the new test machine, still the system hangs.
I analyzed the error and found that it is a problem with the ACPI [Advanced Configuration and Power Interface].

Below is my analysis and a pointer to resolving it.

Error found in /var/log/messages [ command is dmesg ]
ACPI: DSDT (v001 INTEL DQ965GF 0x000016f2 MSFT 0x01000013) @ 0x0000000000000000

The above message says there is a bug in DSDT.

what is DSDT ?
Differentiated System Description Table (DSDT)
An OEM must supply a DSDT to an ACPI-compatible OS. The DSDT contains the Differentiated Definition Block,
which supplies the implementation and configuration information about the base system.
The OS always inserts the DSDT information into the ACPI Namespace at system boot time and never removes it.

Basically, what this boils down to is that the DSDT describes the configuration of your system.
It has definitions of all of the devices that ACPI supports, and describes their capabilities.

The above problem can be resolved as follows :

#cat /proc/acpi/dsdt > /home/yourname/dsdt.dat
#cd /usr/bin
#./iasl -d /home/yourname/dsdt.dat

This will create a file called dsdt.dsl, which contains the disassembled DSDT.
Copy this file from /usr/sbin to /home/yourname as we are going to work on it.

Recompile the DSDT.
# cd /usr/bin
# ./iasl -tc /home/yourname/dsdt.dsl

While compilation 1 error appears as below:
XXXTSTMC1:/usr/bin # ./iasl -tc /home/XXX/dsdt.dsl

Intel ACPI Component Architecture
ASL Optimizing Compiler version 20060127 [Jun 16 2006]
Copyright (C) 2000 - 2006 Intel Corporation
Supports ACPI Specification Revision 3.0a

/home/XXX/dsdt.dsl 90: Store (0x01, \_SB.TCOI.IGFX.SCIS)
Error 1061 - Object does not exist ^ (\_SB.TCOI.IGFX.SCIS)

ASL Input: /home/XXX/dsdt.dsl - 5195 lines, 178611 bytes, 1658 keywords
Compilation complete. 1 Errors, 0 Warnings, 0 Remarks, 566 Optimizations
which can be fixed by removing the line 90 in the file. [ not sure about the fix, but works fine].

We get 2 files namely, dsdt.hex and dsdt.aml

There are 2 methods to incorporate the files built above into the kernel which is best described
at this Discussion Forum

Basically, we have to recompile the kernel every time we install it, which is not usually recommended.


Reply to this mail : [Russian Way]

My 2 cents here:

What if we pass "acpi=off" to the kernel command line? :)

Hope this helps.


Passing commands to Kernel on Linux.

Saturday, June 30, 2007

mozilla & stumble

First of all, sorry for a lengthy inactive period

Second, I dono if somebody else has already reported this...

I tried installing Stumble on my yet unupdated Mozilla

It kept saying "Software installation is currently disabled. Click "edit options" on the right, enable it and then try again"

And it gave me a small edit options box...Clickin on it produced the "Contents" tab in Mozilla's preferences box. That didn't help too much. So googled it up and found the following :

Enabling software installs

Some users may have disabled the software installation option based on security issues which have since been resolved [1]. To re-enable:

Firefox 1.5: If you previously disabled this option and then updated to Firefox 1.5, the disabled setting will be carried over. Since the option to enable software installation no longer exists in the interface, you will need to:

  1. Type about:config in the Location Bar and hit enter.
  2. Type xpi in the Filter box and find xpinstall.enabled in the list.
  3. Make sure its value is set to "true" (double-click will toggle)

You mite find some other raw config options in "about:config" ;)

Thursday, June 28, 2007

From PVR

when i clicked on online booking, i get this

"Please wait....

PVRDB.Database.1 error '80020009'

Transaction (Process ID 67) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

/pvr/include/login_redirect.asp, line 48 "

Thank you!

Sunday, June 24, 2007

Patching a Hardware Bug

What do you do when you find a bug in a software ? Simple ! Find a solution and release a patch. But what if a hardware has bug ? Again, find a solution and release the patch ! Surprised ?? Just read through this article posted on MIT Tech Review.

Operating Systems...

well, we have read many definitions of operating systems based on its role.
one, as a "facilitator" for applications development.
two, as a "manager" of hardware, core routines(processes/daemons,and hence software), imposing security/protection of itself and the hardware it manages.

here is one definition where the OS is defined based on its objective. Its from the Project Oberon notes...

"The fundamental objective of an operating system is to present the computer to the user and to the programmer at a certain level of abstraction."

phew!!! this one defines the complexity, role and the objective of an OS. This definition also gives the implementer freedom to design his OS the way he wants to, based on wat level of abstraction he wants to give his "user and programmer". Nice place to start building one!

Monday, June 11, 2007

Is this implementation of select() syscall in Linux correct?

Here is the code
linuxMachine:/tmp # uname -a
Linux linuxMachine 2.4.21-309.PTF.97199.1-smp #1 SMP Mon Jul 24 12:20:00 UTC 2006 i686 unknown
linuxMachine:/tmp # cat testSelectCall.c
#include "stdio.h"
#include "sys/time.h"
#include "sys/types.h"
#include "unistd.h"

main(void) {
fd_set rfds;
struct timeval tv;
int retval;

FD_SET(0, &rfds);

tv.tv_sec = 5;
tv.tv_usec = 0;

retval = select(1, &rfds, NULL, NULL, &tv);
/* Here is the tricky part! */

if (retval)
printf("Data is available now.\n");
printf("No data within five seconds.\n");

return 0;
linuxMachine:/tmp # !gcc
gcc testSelectCall.c
linuxMachine:/tmp # !time
time ./a.out

No data within five seconds.

real 0m5.000s
user 0m0.000s
sys 0m0.000s
linuxMachine:/tmp #

On a solaris box

solarisBox>uname -a
SunOS solarisBox 5.10 Generic_118835-02 sun4u sparc SUNW,Sun-Blade-100
solarisBox>gcc testSelectCall.c
time ./a.out

No data within five seconds.

real 0m5.025s
user 0m0.003s
sys 0m0.010s

Man Page has the following description
man 2 select

Some code calls select with all three sets empty, n zero, and a non-null
timeout as a fairly portable way to sleep with subsecond precision.

On Linux, the function select modifies timeout to reflect the amount of
time not slept; most other implementations do not do this. This causes
problems both when Linux code which reads timeout is ported to other
operating systems, and when code is ported to Linux that reuses a struct
timeval for multiple selects in a loop without reinitializing it. Con�
sider timeout to be undefined after select returns.

Monday, June 04, 2007

Microsoft announces surface

I am sure, many are aware of it. In case you haven't then check this out

Wednesday, May 30, 2007

Play it on TV

I was thinking about how to watch movies stored on my computer on TV screen, without much investments.
The major problem is that most movies are stored on computer in different formats and players are freely available to install and run. If you want them to play, need to have a DVD/CD player with right set of decoders or use converters to DVD format, not a cost & time saving one's.
Found this cool stuff on the net about how to play movies on your computer on TV.

Getting shell script variable values

Here is the problem

bash-2.05# cat
echo "Environment variables" > out.log
env >> out.log
echo $ATM_PIN

bash-2.05# sh

bash-2.05# cat out.log |grep -i atm

While debugging a shell script, if the values of the variables are required in an intermittent state of the shell script execution use the -a option.

bash-2.05# sh -a
bash-2.05# cat out.log |grep -i atm

Thursday, May 17, 2007

Configuring rsh service on Linux

By default the rsh service is not enabled (obviously).

So here are the steps

1. Check if the rpms are installed. (else use the cd's to install)
redhat# rpm -qa|grep rsh
2. In /etc/xinetd.d/rsh set disable = no
3. Edit the following files

redhat# cat /etc/hosts.allow
# hosts.allow This file describes the names of the hosts which are
# allowed to use the local INET services, as decided
# by the '/usr/sbin/tcpd' server.
ALL : localhost/hostA
redhat# cat /etc/hosts.equiv
redhat# cat .rhosts
+ user1

4. /etc/init.d/xinetd restart
5. Test the above
redhat# rsh localhost
//password less login to remote machine

Disclaimer: more secure services like ssh are recommended than services like rsh.

Sunday, April 29, 2007

Friday, March 30, 2007

How does one sort the files based on size in Unix ???

Again elementary but not used much

ls does not give an option to sort the files based on file sizes. (some os have -S option not sure which)

Here is a way to do it in a very generic way

bash-2.05# ls -hl /tmp/a.out /tmp/test.c |sort -k 4 -n
-rw-r--r-- 1 root other 0 Mar 30 21:41 /tmp/a.out
-rw-r--r-- 1 root other 108 Mar 29 11:49 /tmp/test.c

sort -k does the trick. So position can be any column in the output.
For more details man sort

Wednesday, March 28, 2007

Debugging tomcat applications using IDE's

You have deployed your war file into tomcat. You have the source code, but you cannot innitate a DEBUG from the IDE(Eclipse or Netbeans). How does one debug?

Run tomcat in DEBUG mode

EDIT %CATALINA_HOME%/bin/catalina.bat
set JAVA_OPTS=-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=3091,suspend=n


JAVA_OPTS=-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=3091,suspend=n

Restarting tomcat will render it in debug mode listening on port 3091.

Now in your favourite IDE have the REMOTE DEBUGGING listening on port 3091.
Then the course is normal, place breakpoints in your code and trace for possible bugs.

Friday, March 16, 2007

Did You Know ???

This might sound like an interview question, but very interesting one's, sorry there are 2 questions ;-)

1. Whats the output of the following?

struct a {
char b;
int a;
int main()
printf("Size of struct a is %d\n", sizeof(struct a));
return 0;

Ans: Assuming int = 4 bytes, size will be 8 bytes.

Ok, now the real question, how do you make "sizeof(struct a)" to print 5 bytes,
which is the actual size of structure.

Solution ;-),just add a line to direct the compiler using pragma.

#pragma pack 1
struct a {
char b;
int a;
int main()
printf("Size of struct a is %d\n", sizeof(struct a));
return 0;

Now, check out the output, it says 5 bytes !!!

2. Run a program without a main() function in it ??
Please, don't google for it, just look below ;-)

By the way, I tried this only on HP-UX,
so please try out on different OS, post it in comments.
Basically, you need to do "man cc", to check out the
compilation option.

#vi t.c

int f1()
printf ("Hello world\n");
return 0;

# cc t.c -o t -ef1
Warnings: Are meant to be ignored by programmers ;-)
# chmod +x t
# ./t

Aila, it's running !!!

Wednesday, March 14, 2007

Partitioning in postgres

Partioning is useful to drop group of data in a table in bulk. In most cases year old data is purged on a regular basis by an application. Partitions are a useful design design to manage the data.

create table master (i int);

create table slave1 ( CHECK ( i > 0 AND i <> 10 AND i <> 20 AND i < postgres="#"> 0 AND i <> 10 AND i <> 20 AND i < 30) ) inherits (master);

postgres=# insert into master values(5);
postgres=# insert into master values(15);
postgres=# insert into master values(25);
postgres=# select * from master;
(3 rows)
postgres=# select * from slave1;
(1 row)
postgres=# select * from slave2;
(1 rows)
postgres=# select * from slave3;
(1 rows)

Note: Copy command of postres does not copy the rules associated with the table. So to make sure the rules are reflected, create partitions as a trigger.

Also here is an interesting thing

postgres=# update master set i=15 where i=5;
ERROR: new row for relation "slave1" violates check constraint "slave1_i_check"

This says it all

Saturday, March 03, 2007

Effective JDBC

JDBC supports connection pooling, which essentially involves keeping open a cache of database connection objects and making them available for immediate use for any application that requests a connection. Instead of performing expensive network roundtrips to the database server, a connection attempt results in the re-assignment of a connection from the local cache to the application. When the application disconnects, the physical tie to the database server is not severed, but instead, the connection is placed back into the cache for immediate re-use, substantially improving data access performance.

To get more of it checkout these links

From my limited research, I understand tomcat implements connection pool by default.
Here is the link taking at length about it

Also during the research came up with this nice article by the Martin Fowler talking about the design decisions of allowing certain business logic in the database rather than handling them exclusively in the application software (esp things like orderby, filtering tools (WHERE,LIKE etc))
Here's the link

This was typically the point made by the oracle database legend Tom Kyte in the article JDBC : SQL vs PL/SQL, Which performs better

Simple anology(not entrirely a perfect analogy) ,
when we know we need to grep for say automountd process to just know the pid of the process
instead of ps -aef|grep auto
a simple ps -a -o comm,pid|grep auto
will be more effective.

This design problem is tackled at across various layers. A simple typical case is the OS, where we typically end up getting huge data( say in truss or ps output), there after prunning the processed(cpu) data using grep,awk like utilities. A tool which stops from generating the unwanted data from being generated always scores over the basic tools we use.

Friday, March 02, 2007

How to know the current process state

This one feature though trivial will be thoughly learnt on a need basis.

When we need to find out what is the current state of a process is (aka Running(R), Sleeping(S), Stopped(T),Zombie(Z) etc), we can use the ps command effectively.

Here is the basic setup
test@shantanu>more simple1.c
int main()
int i=0;
printf("Waiting for a console output\n");
test@shantanu>gcc simple1.c -o simple1
Waiting for a console output
........///No input is yet given

In another terminal run
test@shantanu>ps -a -o comm -o s|grep simple1
./simple1 S

So the process is currently sleeping for my input.
All the state changes hereafter can be observed independently.

Tuesday, February 27, 2007

core file generation

Got to know this interesting bit today

By default in solaris core dump occurs when an application misbehaves(say segmentation fault).
But in linux the default core dumping is disabled.

Using ulimit command one can turn on this feature.

Just enable the application to core dump by
$>ulimit -c unlimited

For more on this refer to

Friday, February 23, 2007

Amazon turks now in Indian rupees

Amazon turk now renders Indian rupee transaction. Check it out

Saturday, February 10, 2007

Sun Tech days in Hyderabad

Sun tech days from Feb 21st to 23rd. Though most of the technical community is aware of this event , please check this link to get the details. The list of talks,hands on labs, codecamps are here

Tuesday, February 06, 2007

Continuations in java

Continuation is an object that represents the execution state of a program at a certain point. We can use continuation to restart the execution from the point stored in it.
One area that has seen practical use of continuations is in web programming

Check out an enumeration here