Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Monday, July 27, 2009

Perl ImageMagick convert Images from one format to another

Introduction
A Picture speaks louder than a thousand words. Most of the programming problems I usually worked with and involved in where dealing with just TEXT. So now I wanted to programatically work with images. I needed to warp, rotate, scale, stretch, convert from jpeg to png, png to jpeg, jpeg to bmp, bmp to jpeg etc. So I decided to search on how to do such a thing easily. Well the first obvious answer is to do handle all these in C reading files uncompressing based on the extensions, compressing, write the encoders and do whole lot of "Reinventing the wheel" stuff. So I found this software called ImageMagick which already wrote the codes to do all these for you, and what more? It has a neat Perl API so that you can do the fun stuff that you do on perl on images. Now that's sweet.

Hello World
Now just check out this simple script to convert files from one format to another.


#!/usr/bin/perl
#
#usage: perl im.pl <Source File> <Destination File>
#

use strict;
use Image::Magick;

my $q = Image::Magick->new;

my $source = $ARGV[0];
my $dest = $ARGV[1];

$q->Read($source);
$q->Write(filename=>$dest);

exit;


That is all that is required to convert file from one format to another using ImageMagick and the Perl Image Magick API. For example
perl im.pl IMG_0021.JPG IMG_0021.BMP

would convert the JPG to BMP for you.

Wednesday, July 8, 2009

yum/apt-get update Breaks Perl CPAN

Doing an yum update or apt-get update and upgrading your system might break the PERL installation, the output I got while doing so: (after an update).


[root@desktop]# cpan

cpan shell -- CPAN exploration and modules installation (v1.7602)
ReadLine support enabled

cpan> install WWW::Mechanize
CPAN: Storable loaded ok
Going to read /root/.cpan/Metadata
Database was generated on Mon, 15 Jun 2009 02:27:28 GMT
Going to read /root/.cpan/sources/authors/01mailrc.txt.gz
CPAN: Compress::Zlib loaded ok
Going to read /root/.cpan/sources/modules/02packages.details.txt.gz
Database was generated on Wed, 08 Jul 2009 02:28:24 GMT
CPAN: HTTP::Date loaded ok

There's a new CPAN.pm version (v1.9402) available!
[Current version is v1.7602]
You might want to try
install Bundle::CPAN
reload cpan
without quitting the current session. It should be a seamless upgrade
while we are running...

CPAN: LWP::UserAgent loaded ok
Fetching with LWP:
ftp://ftp.jaist.ac.jp/pub/CPAN/modules/03modlist.data.gz
LWP failed with code[500] message[Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture (i386-linux-thread-multi-2.6.18-53.el5) at /usr/lib/perl5/site_perl/5.8.8/Errno.pm line 11.
Compilation failed in require at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/IO/Socket.pm line 17.
BEGIN failed--compilation aborted at /usr/lib/perl5/5.8.8/i386-linux-thread-multi/IO/Socket.pm line 17.
Compilation failed in require at /usr/lib/perl5/5.8.8/Net/FTP.pm line 18.
BEGIN failed--compilation aborted at /usr/lib/perl5/5.8.8/Net/FTP.pm line 18.
Compilation failed in require at /usr/lib/perl5/site_perl/5.8.8/LWP/Protocol/ftp.pm line 21.
]
Fetching with Net::FTP:
ftp://ftp.jaist.ac.jp/pub/CPAN/modules/03modlist.data.gz
Can't locate object method "new" via package "Net::FTP" at /usr/lib/perl5/5.8.8/CPAN.pm line 2250.


This is due to the architecture check and differences that PERL encounters on Errno.pm module.

Fix
This can be called a fix or rather a tweak by commenting out these lines (Add #'s to the beginning) on
/usr/lib/perl5/site_perl/5.8.8/Errno.pm


"$Config{'archname'}-$Config{'osvers'}" eq
"i386-linux-thread-multi-2.6.18-53.1.14.el5pae" or
die "Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture ($Config{'archname'}-$Config{'osvers'})";

Change the lines to:

#"$Config{'archname'}-$Config{'osvers'}" eq
#"i386-linux-thread-multi-2.6.18-53.1.14.el5pae" or
# die "Errno architecture (i386-linux-thread-multi-2.6.18-53.1.14.el5pae) does not match executable architecture ($Config{'archname'}-$Config{'osvers'})";

Sunday, February 1, 2009

PERL Code to change Google talk status

Code : stat.pl
The following code changes the status of gmail/gtalk user status.
Requires NET::XMPP module, and with SSL modules installed.


#!/usr/bin/perl
#usage : perl stat.pl <status>
use strict;
use Net::XMPP;


## Pls fill in these here :)
my $username = "";
my $password = "";


my $hostname = 'talk.google.com';
my $port = 5222;
my $componentname = 'gmail.com';
my $connectiontype = 'tcpip';
my $tls = 1;

my $Con = new Net::XMPP::Client(debuglevel=>0);

my $status = $Con->Connect(
hostname => $hostname,
port => $port,
componentname => $componentname,
connectiontype => $connectiontype,
tls => $tls,
timeout => 10);

if (!(defined($status))) {
exit(0);
}

my $sid = $Con->{SESSION}->{id};
$Con->{STREAM}->{SIDS}->{$sid}->{hostname} = $componentname;

my @result = $Con->AuthSend(
username => $username,
password => $password,
resource => "neuron");

$Con->Send("<iq type='get' to='gmail.com'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>");
$Con->Process();

my $iq = $Con->SendAndReceiveWithID("<iq type='get' to='$username\@gmail.com'><query xmlns='google:shared-status'/></iq>");

my ($status,$statuslist,$show) = ("","","");
$status = $1 if($iq->GetXML() =~ m/<status>(.*?)<\/status>/);
$statuslist = $1 if($iq->GetXML() =~ m/(<status-list(.*)<\/status-list>)/);
$show = $1 if($iq->GetXML() =~ m/<show>(.*?)<\/show>/);

my $status = $ARGV[0];

#Change status
$Con->Send("<iq type='set' to='$username\@gmail.com'><query xmlns='google:shared-status'>
<status>$status</status><show>$show</show>
$statuslist
</query></iq>");
$Con->Process();
$Con->PresenceSend(type=>'unavailable');
$Con->Process();
$Con->Disconnect();
$Con->Process();
exit;


Usage
perl stat.pl "my status"


Worked? or Crap?
Lemme know....
;)

Tuesday, November 18, 2008

8086 Assembly Language Program to find the factorial upto 255!

Intro
The following assembly language program is for MASM 5.1 up calculates factorial of numbers upto 255!, that is quite a large number to compute a factorial. See below:


Number:255
Factorial
3350850684932979117652665123754814942022
5840635917407025767798842862087990357327
7100562613812676331425928080211850228244
5926550135522251856727692533193070412811
0833303256593220417000297921662507342533
9051375446604571124033846270103402026299
2581378423147276636643647155396305352541
1055414394348401099150682854306750685916
3858198060416294038335658673919826878210
4924614076605793562865241982176207428620
9697768031494674313868079724382476891586
5600000000000000000000000000000000000000
0000000000000000000000000


for the Faint Hearted
The program calculates and computes big numbers by simulating the traditional way of multiplication and division of numbers. Hence it can do this upto any number of digits as much as the memory can hold. In this example, I have used 512 digited numbers, which is more than enough for holding 255!.

The key parts of the following program is bignum_mul and bignum_add macro which simulates the traditional method of multiplying and adding numbers (not using any vedic maths, which can certainly improve the efficiency I guess).

The following is the assembly language program, try digesting...

.asm Program

data segment
b1 db 512 dup(0)
b2 db 512 dup(0)
msg db 0dh,0ah,"Number:$"
fac db 0dh,0ah,"Factorial",0dh,0ah,"$"
data ends

bignum_get macro var
local exit,get,loo,skip
xor cx,cx
lea si,var
mov di,si
mov ah,01h
get:
int 21h
cmp al,0dh
je exit
sub al,30h
mov [si],al
inc si
inc cx
jmp get
exit:
shr cx,1
jz skip
dec si
loo:
mov ah,[si]
mov al,[di]
mov [si],al
mov [di],ah
dec si
inc di
loop loo
skip:
endm

geti macro
local exit,get
xor bx,bx
mov dx,bx
mov cx,00ah
get:
push bx
;Read character
mov ah,01h
int 21h
xor ah,ah
pop bx
;If enter stop
cmp al,0dh
jz exit
sub al,30h
;Multply By 10
push ax
mov ax,bx
mul cx
mov bx,ax
pop ax
;add
add bx,ax
;redo
jmp get
exit:
mov ax,bx
endm

bignum_put macro var
local put,en,nxt,exit
lea si,var
mov di,si
mov cx,0200h
add di,cx
dec di
en:
cmp BYTE PTR [di],00h
jne nxt
dec di
jmp en
nxt:
mov ah,02h
put:
mov dl,[di]
add dl,30h
int 21h
cmp si,di
je exit
dec di
loop put
exit:
endm



bignum_add macro b1,b2
local ader,exit
lea si,b1
lea di,b2

mov cx,0200h
mov bl,10
ader:
mov al,[di]
mov ah,[si]
add al,ah
jz exit
xor ah,ah
div bl
mov [si],ah
inc si
add [si],al
inc di
loop ader
exit:
endm

bignum_mul macro b1
local loo,exit
cmp dl,01h
jz exit
lea si,b1
mov dh,10
xor bx,bx
mov cx,0200h
loo:
mov al,[si]
xor ah,ah
mul dl
add ax,bx
div dh
mov [si],ah
inc si
mov bl,al
loop loo
exit:
endm

puts macro msg
push ax
push dx
mov dx,offset msg
mov ah,09h
int 21h
pop dx
pop ax
endm


assume cs:code,ds:data
code segment
start:
mov ax,data
mov ds,ax

lea si,b1
mov BYTE PTR [si],01h

puts msg
geti
mov dl,al
loo:
push dx
bignum_mul b1
pop dx
dec dl
jnz loo

puts fac
bignum_put b1
mov ah,4ch
int 21h
code ends
end start


The Simple Factorial code upto 8!

geti macro
local exit,get
xor bx,bx
mov dx,bx
mov cx,00ah
get:
push bx
;Read character
mov ah,01h
int 21h
xor ah,ah
pop bx
;If enter stop
cmp al,0dh
jz exit
sub al,30h
;Multply By 10
push ax
mov ax,bx
mul cx
mov bx,ax
pop ax
;add
add bx,ax
;redo
jmp get
exit:
mov ax,bx
endm

puti macro buffer
local exit,put
mov bx,0ah
lea si,buffer
add si,06h
mov BYTE PTR [si],'$'
put:
xor dx,dx
dec si
div bx
add dl,30h
mov [si],dl
cmp ax,0h
jnz put

mov dx,si
mov ah,09h
int 21h

endm

puts macro msg
push ax
push dx
mov dx,offset msg
mov ah,09h
int 21h
pop dx
pop ax
endm

data segment
msg1 db 0dh,0ah,"Enter Number : $"
msg2 db 0dh,0ah,"Factorial : $"
buff db 20 dup(?)
data ends

assume cs:code,ds:data
code segment
start:
mov ax,data
mov ds,ax
puts msg1
geti
push ax
puts msg2
pop ax
mov cx,ax
dec cx
jz over
xor dx,dx
re:mul cx
loop re
over:
puti buff
mov ah,4ch
int 21h
code ends
end start


Thanks to ABA (Bellari) for challenging me to do the 255!.. Yo!!!

Sunday, August 10, 2008

Free Online 8085 Assembler and Simulator

Free Online 8085 Assembler and Simulator
I just made this long back, just put it online for anyone that might be interested in using it.

Quick Start

  • Enter the code as shown in the sample in the code view,
  • Click Compile and Simulate.
  • Click HexView to see the hex code of the program
  • Click SimView and Click Step or Exec to simulate the program.


There is a built in special function call for keyboard reads : CALL KBINPUT
Displays a prompt for directly entering into the Accumulator.

In addition memory locations can be assigned in code using
ORG Hex Address
AA BB CC DD
EE FF 00 11
22 33 44 55
66 77
etc

Assembly Source CodeView


HexView


SimView


The SimView Screen is divided into 4 Sections:
  • The extreme left shows the code and highlights the current section being executed.
  • The middle box shows the registers and flags
  • The extreme right shows the stack.
  • The bottom box prints values of memory locations.


More features would be posted as memory comes to me
;)

Saturday, July 26, 2008

T9 Dictionary Implementation in C, BASH

/*
t9.c
Dependency : t9.dic
A file with lots of words to populate our t9 trie structure.
All in small letter no spaces no other characters
Terminated by a line with only a 0 (zero)
=================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct t9
{
struct t9 * node[27];
};

struct t9 * t9_new()
{
struct t9 * r = (struct t9 *)malloc(sizeof(struct t9));

int i=0;
for(;i<27;i++) r->node[i] = (struct t9 *)0;

return r;
}

void t9_free(struct t9 * root)
{
if(root)
{
int i=0;
for(;i<27;i++)
t9_free(root->node[i]);
free(root);
}
}

struct t9 * t9_insert(struct t9 * root ,char *val)
{

if(!root){ root = t9_new(); }

if(!*val) return root;
*val |= ('A' ^ 'a');
char c = *val - 'a';
root->node[c] = t9_insert(root->node[c] ,++val);

return root;
}

void t9_print(char *pre, struct t9 * root,int depth)
{
int i=0,flag=0;
for(;i<27;i++)
{
if(root->node[i])
{
pre[depth]='a'+i;flag=1;
t9_print(pre,root->node[i],depth+1);
pre[depth]=0;
}
}
if(flag == 0)
{
pre[depth]=0;
printf("%s\n",pre);
}
}

int in_mob_ks(struct t9 * root,char val,int o)
{

int a[]={0,3,6,9,12,15,19,22,26};
/* 2=>0 1 2
3=>3 4 5
4=>6 7 8
5=>9 10 11
6=>12 13 14
7=>15 16 17 18
8=>19 20 21
9=>22 23 24 25
*/
if(o && o>=a[val+1]) return -1;


int s=o?o:a[val];
int e=a[val+1];
//printf("From %d-%d",s,e);
for(;s<e;s++)
if(root->node[s])
return s;
return -1;
}

void t9_search_mob(char *pre, struct t9 * root,int depth,char *val)
{

if(*(val+depth)==0)
{
pre[depth]=0;
t9_print(pre,root,depth);
return;
}

int i=in_mob_ks(root,*(val+depth)-'2',0);
if(i==-1)
{
pre[depth]=0;
//printf("%s\n",pre);
}
while(i>=0)
{
pre[depth]=i+'a';
t9_search_mob(pre,root->node[i],depth+1,val);
pre[depth]=0;
i=in_mob_ks(root,*(val+depth)-'2',i+1);
}
}


struct t9 * t9_search(struct t9 * root, char *val)
{
while(*val)
{
if(root->node[*val-'a'])
{
root = root->node[*val-'a'];
val++;
}
else return NULL;
}
return root;
}

int main()
{
struct t9 * root = (struct t9 *) 0;
char a[100],b[100];int i;
FILE *fp = fopen("t9.dic","r");
while(!feof(fp))
{
fscanf(fp,"%s",&a);
if(a[0]=='0')break;
root=t9_insert(root,a);
}

while(1)
{
printf("mob keys 2-9:");
scanf("%s",&a);
if(a[0]=='0')break;
t9_search_mob(b,root,0,a);
}
t9_free(root);
}



V2
Nothin's changed except for the input method and output limited:

/*
t9.c
Dependency : t9.dic
A file with lots of words to populate our t9 trie structure.
All in small letter no spaces no other characters
Terminated by a line with only a 0 (zero)
Input :
2-9 mobile keys
0 for a new word
q to quit
=================
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <termios.h>
#include <unistd.h>

int getch( )
{
struct termios oldt,newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}

int maxdepth = 0;

struct t9
{
struct t9 * node[27];
};

struct t9 * t9_new()
{
struct t9 * r = (struct t9 *)malloc(sizeof(struct t9));

int i=0;
for(;i<27;i++) r->node[i] = (struct t9 *)0;

return r;
}

void t9_free(struct t9 * root)
{
if(root)
{
int i=0;
for(;i<27;i++)
t9_free(root->node[i]);
free(root);
}
}

struct t9 * t9_insert(struct t9 * root ,char *val)
{

if(!root){ root = t9_new(); }

if(!*val) return root;
*val |= ('A' ^ 'a');
char c = *val - 'a';
root->node[c] = t9_insert(root->node[c] ,++val);

return root;
}

void t9_print(char *pre, struct t9 * root,int depth)
{
int i=0,flag=0;

if(depth < maxdepth)
for(;i<27;i++)
{
if(root->node[i])
{
pre[depth]='a'+i;flag=1;
t9_print(pre,root->node[i],depth+1);
pre[depth]=0;
}
}
if(flag == 0)
{
pre[depth]=0;
printf("%s\n",pre);
}
}

int in_mob_ks(struct t9 * root,char val,int o)
{

int a[]={0,3,6,9,12,15,19,22,26};
/* 2=>0 1 2
3=>3 4 5
4=>6 7 8
5=>9 10 11
6=>12 13 14
7=>15 16 17 18
8=>19 20 21
9=>22 23 24 25
*/
if(o && o>=a[val+1]) return -1;


int s=o?o:a[val];
int e=a[val+1];
//printf("From %d-%d",s,e);
for(;s<e;s++)
if(root->node[s])
return s;
return -1;
}

void t9_search_mob(char *pre, struct t9 * root,int depth,char *val)
{

if(*(val+depth)==0)
{
pre[depth]=0;
t9_print(pre,root,depth);
return;
}

int i=in_mob_ks(root,*(val+depth)-'2',0);
if(i==-1)
{
pre[depth]=0;
//printf("%s\n",pre);
}
while(i>=0)
{
pre[depth]=i+'a';
t9_search_mob(pre,root->node[i],depth+1,val);
pre[depth]=0;
i=in_mob_ks(root,*(val+depth)-'2',i+1);
}
}


struct t9 * t9_search(struct t9 * root, char *val)
{
while(*val)
{
if(root->node[*val-'a'])
{
root = root->node[*val-'a'];
val++;
}
else return NULL;
}
return root;
}

int main()
{
struct t9 * root = (struct t9 *) 0;
char a[100],b[100];int i;
FILE *fp = fopen("t9.dic","r");
while(!feof(fp))
{
fscanf(fp,"%s",&a);
if(a[0]=='0')break;
root=t9_insert(root,a);
}

i=0;
while((a[i]=getch()) != 'q')
{
if(a[i]=='0'){i=0;continue;}
if(a[i] >= '2' && a[i] <= '9')
{
i++;
a[i]=0;
maxdepth = i;
printf("%s:\n",a);
t9_search_mob(b,root,0,a);
fflush(stdout);
}
}
t9_free(root);
}


t9.dic

T9 Dictionary sample file

Now in BASH!

#!/bin/bash
# bash script does something outrageous.
# It attempts to reproduce the T9 capability of the Mobile Phones !

# And does it in fewer commands than before!
# Adapted from Rahul's Original T9.sh

umask 077
NUMN=/tmp/numn.$$
trap "exit 1" HUP INT PIPE QUIT TERM
trap "rm -f $DICTN $NUMN" EXIT

cat t9.dic | tr a-z 22233344455566677778889999 > $NUMN

if [ $# -eq 0 ] ; then
echo "Usage : t9.sh "
exit 1;
else
paste -d: $NUMN t9.dic | grep "^$1" | cut -d":" -f2 | sort
fi

Sunday, June 29, 2008

Dataone Account Usage Checker in PERL

The following Script in PERL is a Dataone account usage checker.


#!/usr/bin/perl
# http://digitalpbk.blogspot.com/2008/06/free-dataone-account-usage-checker-perl.html

use WWW::Mechanize;
use HTTP::Cookies;
use HTTP::Request::Common;

my $verbose = 0;
my $username;
my $password;
my $url="http://10.240.64.195/weblogin.jsp";

for(my $i=0;$i<=$#ARGV;$i++)
{
if($ARGV[$i] eq "-v" or $ARGV[$i] eq "--verbose"){ $verbose = 1; }
elsif($ARGV[$i] eq "-u" or $ARGV[$i] eq "--user"){ $username = $ARGV[++$i]; }
elsif($ARGV[$i] eq "-p" or $ARGV[$i] eq "--pass"){ $password = $ARGV[++$i]; }
elsif($ARGV[$i] eq "-i" or $ARGV[$i] eq "--url"){ $url = $ARGV[++$i]; }
}
unless($username)
{
print "Username : ";chomp($username = <STDIN>);
}
unless($password)
{
print "Password : ";
`stty -echo`;
chomp($password = <STDIN>);
`stty echo`;
print "\n";
}
$cj = HTTP::Cookies->new(file => "cookie.jar",autosave=>1);
$mech=WWW::Mechanize->new(cookie_jar=>$cj);

print "GET $url\n" if($verbose);
$mech->get($url);
exit unless($mech->success());

my $cnt = $mech->response->as_string;

$cnt =~ s[action="../(.*?)"][action="$1"]is;
$mech->update_html($cnt);

$mech->form_number(1);
$mech->field("username",$username);
$mech->field("password",$password);
print "LOGIN\n" if($verbose);
$mech->submit();

exit unless($mech->success());
$cnt = $mech->response->as_string;

$|=1;
my $uri;my $maxre=0;
while($cnt =~ m/location.replace\('(.*?)'\)/is)
{
print "FOLLOWING .. " if($verbose);

$uri = $1;
if($uri =~ m/loginerr/g)
{
print "\nLOGIN Failed !\n";
exit;
}

$mech->get($uri);
exit unless($mech->success());
print $uri,"\n" if($verbose);
$cnt = $mech->response->as_string;
last if($maxre++ > 4);
}

exit if($maxre > 4);
print "GET Service Records\n" if($verbose);
$mech->get("serviceRecords.jsp");
exit unless($mech->success());
$cnt = $mech->response->as_string;

$mech->form_number(1);
$mech->submit();
print "POST Form\n" if($verbose);

$cnt = $mech->response->content;
$cnt = $1 if($cnt =~ m:<body[^>]*>(.*?)</body>:sig);

$cnt =~ s/<[^>]+>//sig;
$cnt =~ s/&nbsp;/ /sig;
$cnt =~ s/([\n\r\t ]){2,}/;/sig;

$cnt = $1 if($cnt =~ m/(Total Send Volume([^;]+;){10})/);

@sl = split /;/,$cnt;

$sl[4] = "Excluding Night";
for($i=0;$i<=($#sl/2);$i++)
{
printf("%25s : %s\n",$sl[$i],$sl[$i+5]);
}

$mech->get("../logout.jsp");



Installation

On Linux
Copy paste to a new file data1.pl
Install WWW::Mechanize if not already installed.

chmod 755 data1.pl


On Windows
Copy paste to a new file data1.pl
Get Active Perl and install if PERL is not installed.
Install Module WWW::Mechanize.

Usage
Linux
./data1.pl Options


Windows, not TESTED
perl data1.pl Options

PS : Comment `stty` lines when using on windows or ignore the errors
perl data1.pl -u username -p password


Options
No need any if your not good at the Command line.
-v to turn on Verbose, describe what is being done.
-u username to specify username
-p password to specify password

...
Any more doubts ?
Use the link that says comment
;)


100th

Post

Thursday, November 29, 2007

Asynchronous Reading from Input

Intro
Normal working of a C program taking an input is done via the scanf method. The problem in scanf is that when we invoke scanf it waits until we input something i.e, our program is waiting for the user input. This valuable time could be used for processing other things. Let us consider an example of a chat client made using C. When we want to send some message we type them and send. In all other cases it is required that the chat client listens for incoming messages. This is impossible using the normal scanf method, because at all times it would be waiting for our input and there would not be any recieved messages in that time period. So the process of receiving information while checking for input is an example of asynchronous reading.

How ?

On Windows ...
On windows the input STDIN can be tested for data by the function kbhit()
defined on conio.h. A simple program template would be


#include <conio.h>

int main()
{
//...
while(1) //Main Process loop
{
//Other Process Block
{
/*
* Something else to do
*/

}
if(kbhit())
{
//Input present and process input
}
}
}

kbhit does not take any arguments, it returns 1 if there has been a keyboard hit i.e., a key has been pressed.
The key can be read using getch() or similar functions.

On Linux...
the same thing seems to be a bit different. There is no conio.h defined for linux so there is no kbhit function that can be used in linux. However linux has a set of functions that can be used to test any input for the presence of input. The following is the list of functions that are used to test the input for data.

#include <sys/time.h>

int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *errorfds, struct timeval *timeout);

void FD_SET(int fd, fd_set *fdset);

void FD_CLR(int fd, fd_set *fdset);

int FD_ISSET(int fd, fd_set *fdset);

void FD_ZERO(fd_set *fdset);

Sunday, November 4, 2007

UNIX Networking : Sockets TCP Transmitter and Reciever

Intro

Networking in UNIX or Linux is done with sockets. The following are 2 programs I made up.
1. Sends messages in TCP, Client
2. Listens and Recieves messages from TCP, Server

TCP or Transmission Control Protocol is a 2way connection which is more like a stream or a pipe. Both the ends must be connected.


The Transmitter
Reads messages from input and sends it to localhost:34000.
To Setup a transmitter following must be done:
1. Setup a port address and open a socket and bind to it.
2. Connect to server
3. Send messages
4. Close connection when done

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>

/*Some are unused, But I read these are
general headers used in a network program
:)*/

int main(void)
{
struct sockaddr_in sin;
int s;

s = socket(AF_INET, SOCK_STREAM, 0);
if(!s)
{
perror("socket()");
return 1;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
sin.sin_addr.s_addr = INADDR_ANY;//Just any would do

if(bind(s, (struct sockaddr *)&sin, sizeof(sin)))
{
perror("bind()");
return 1;
}

struct sockaddr_in sout;

sout.sin_family = AF_INET;
sout.sin_port = htons(34000);//Destination PORT!
sout.sin_addr.s_addr = inet_addr("127.0.0.1");//Destination IP Address, here localhost.

connect(s,(struct sockaddr *)&sout, sizeof(sout));//Connect to Server
char msg[1000];//Buffer

do
{
printf("Message: ");
scanf("%s",msg);
sendto(s, msg, strlen(msg)+1, 0,NULL,0);
//Sends the message
}while(*msg!='0'); /*Just an exit condition*/

close(s);//Close Socket

return 0;
}


The Reciever
This program listens to localhost:34000 and accepts first connection and prints the messages whenever it recieves one.
To Setup a reciever following must be done:
1. Setup a port address and open a socket and bind to it.
2. Listens for Clients to connect.
3. Accept connections
4. Recieve data
5. Close connection

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>

int main(void)
{

struct sockaddr_in sin;
char msg[10000];
int ret;
int sin_length;


int s,s2;

s = socket(AF_INET, SOCK_DGRAM, 0);
if(!s)
{
perror("socket()");
return;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(34000);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(s, (struct sockaddr *)&sin, sizeof(sin)))
{
perror("bind()");
return 1;
}
if(listen(s,10))//Listen for connections
{
perror("listen()");
return 1;
}
int size=sizeof(sin);
if((s2=accept(s,(struct sockaddr *)&sin, &size) < 0))//Accept connections
{
perror("accept()");
return 1;
}
printf("\nConnected to %s[%d]",inet_ntoa(sin.sin_addr),sin.sin_port);

do
{
ret = recv(s2, msg, 10000, 0);
//Waits until a message is recieved...
printf("Message : %s\n", msg);
}
while(msg[0]!='0');

close(s);//Close Socket
return 0;
}


Thats all
Tested and proved working on Fedora Core 6.
Do let me know your results and comments.....
To know more about the functions check the Linux Manual for each function.

Check out... (UDP Transciever)
:)

Monday, October 29, 2007

UNIX Networking : Sockets UDP Transmitter and Reciever

Intro

Networking in UNIX or Linux is done with sockets. The following are 2 programs I made up.
1. Sends messages in UDP.
2. Listens and Recieves messages from UDP.

User Datagram Protocol or in short UDP is like a letter or telegram, its arrival is not anticipated and there is no connect and disconnect procedures to send and recieve UDP messages unlike TCP/IP. So the program is a little more easier and simpler to understand.


The Transmitter
Reads messages from input and sends it to localhost:34000.
To Setup a transmitter following must be done:
1. Setup a port address and open a socket and bind to it.
2. Send message to specified port and IP addresses.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>

/*Some are unused, But I read these are
general headers used in a network program
:)*/

int main(void)
{
struct sockaddr_in sin;
int s;

s = socket(AF_INET, SOCK_DGRAM, 0);
if(!s)
{
perror("socket()");
return 1;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(9999);
sin.sin_addr.s_addr = INADDR_ANY;//Just any would do

if(bind(s, (struct sockaddr *)&sin, sizeof(sin)))
{
perror("bind()");
return 1;
}

struct sockaddr_in sout;

sout.sin_family = AF_INET;
sout.sin_port = htons(34000);//Destination PORT!
sout.sin_addr.s_addr = inet_addr("127.0.0.1");//Destination IP Address, here localhost.

char msg[1000];//Buffer

do
{
printf("Message: ");
scanf("%s",msg);
sendto(s, msg, strlen(msg)+1, 0, (struct sockaddr *)&sout, sizeof(sout));
//Sends the message
}while(*msg!='0'); /*Just an exit condition*/

close(s);//Close Socket

return 0;
}


The Reciever
This program listens to localhost:34000 and prints the messages whenever it recieves one.
To Setup a reciever following must be done:
1. Setup a port address and open a socket and bind to it.
2. Start Recieving...

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>

int main(void)
{

struct sockaddr_in sin;
char msg[10000];
int ret;
int sin_length;


int s;

s = socket(AF_INET, SOCK_DGRAM, 0);
if(!s)
{
perror("socket()");
return;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(34000);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(s, (struct sockaddr *)&sin, sizeof(sin)))
{
perror("bind()");
return 1;
}


do
{
sin_length = sizeof(sin);
ret = recvfrom(s, msg, 10000, 0, (struct sockaddr *)&sin, &sin_length);
//Waits until a message is recieved...
printf("Message[%s:%d] : %s\n",
inet_ntoa(sin.sin_addr), sin.sin_port,msg);
}
while(msg[0]!='0');

close(s);
return 0;
}


Thats all
Tested and proved working on Fedora Core 6.
Do let me know your results and comments.....
To know more about the functions check the Linux Manual for each function.

Check out... (TCP/IP Transciever)
:)

Monday, October 1, 2007

PERL Referencing and Dereferencing

Intro

PERL - Practical Extraction and Report Language.

Referencing a variable means creating a pointer to the variable.
Referencing in C is done by the & operator, but in PERL referencing is done by the \(backslash) operator.

Check out the following examples to understand better:

my $scalar = "http://digitalpbk.blogspot.com";
my $scalar_ptr = \$scalar; //Scalar reference

my $array= (1,2,4,3,5);
my $array_ptr = \@array; //Array reference
//or

my $array_ptr = [1,2,3,4,5];//Array reference
//Note the [Square brackets]


my %hash = ("one",1,"two",2);
my $hash_ptr = \%hash; //Hash reference
//or

my $hash_ptr = {"one" => 1,"two"=>2};//Hash reference
//Note the {Curly brackets}


my $sub_ref = \&a_subroutine;//Subroutine reference
//or

my $sub_ref = sub { print "somethings"; };//Sub reference




Dereferencing is the opposite of referencing i.e, to get the value pointed by the referencing/pointing variable. Dereferencing in C is done by the * operator, whereas in PERL it is done by prepending, adding an appropriate @,$ or % to the reference variable.



my $scalar_ptr = \$scalar; //Scalar reference
my $scalar = $$scalar_ptr; //Scalar Var

my $array_ptr = \@array; //Array reference
//or

my $array_ptr = [1,2,3,4,5];//Array reference
my $array = @$array; // Array Var


my $hash_ptr = \%hash; //Hash reference
my %hash = %$hash //Hash Var

my $sub_ref = \&a_subroutine;//Subroutine reference
my $sub_ref = sub { print "somethings"; };//Sub reference
&$sub_ref //Call Subroutine



Thats all about referencing and dereferencing...

Saturday, September 8, 2007

Perl - cPanel V3 and the @INC

Modifying @INC in a SCRIPT

use Module;

is executed during compile time so if you modify the @INC array at run time it will not be reflected back in the compile time. So if you have to include any more include locations in the @INC inside a script, give it inside the BEGIN { }block.


BEGIN
{
push @INC,"location";
}

The BEGIN blocks are executed during compile time. So @INC is updated at compile time and the use module are correctly searched for in the updated directories.

cPanel-v3 Script

my $homedir = (getpwuid($>))[7];
my $n_inc = scalar @INC;
for (my $i = 0; $i < $n_inc; $i++ ) {
if (-d $homedir . '/perl' . $INC[$i]) {
unshift(@INC,$homedir . '/perl' . $INC[$i]);
$n_inc++;
$i++;
}
}


This script dint work for me much, so I manually included the include locations into the BEGIN segment.


#! /usr/bin/perl -w
BEGIN {
unshift @INC,"/home/directory/perl/usr/lib/perl5/site_perl/5.8.7/";
}
.
.
.

Wednesday, July 4, 2007

cPanel Mail Forwarder

Forwarder

This handly little program forwardes all emails coming to a certain specified email address and forwards to a forwarding list.

Setting up the email capturing

e-Mail can be captured using a PERL script. The contents of the email must be pipped in. The capturing an passing of the email can be done through cPanel.


Click Mail

Click Forwarders

Add Forwarder


In the text box to the right side, you can provide an email address or a path to your PERL program that can process your email and extract relevant information.

In order to send the contents of the email to a PERL program we have to PIPE it to the program. PIPING is just redirection of standard output of the mail receiving program to your custom PERL script.
Eg:


"|perl /home/domain/scripts/process.pl"



#!/usr/bin/perl
use strict;


my $Email = join '',<STDIN>;

$Email // has your email contents

Saturday, June 23, 2007

JSON- Javascript Object Notation

Intro
JSON stands for Javascript Object Notation. JSON is a way of writing or expressing JavaScript Objects so that it can be easily read by both the computer and humans. Unlike XML or eXtensible Mark up Language the JSON is much more compact and easier to Parse.

XML takes the form


<Tag>
<Tag2>Information</Tag2>
<Tag>


JSON takes the form

var obj = {
an_array : [element1, element2 , element3 ....],
a_property : "property",
a_multi_array : [ [,,,],[,,,],...]
};


In order to parse an XML response, we have to use the following notation,
Suppose we are returning an XML response from a server using Ajax. The common method to extract the useful information is :

var xml = xmlHttp.responseXML;
var list= xml.getElementsByTagName("TAG");

for(i=0;i < list.length;i++)
{
// loop through and extract the values
}


This can be replaced with the new JSON object notation by

var strobj = xmlHttp.responseText;
var obj = eval("("+strobj+")");
obj.an_array[0];
obj.a_multi_array[0][0];
// ....


The Notation
All object lies between the { }
each of the properties has a label and an associated value or an array.
It is specified as label : value
a , separates the label-value pairs.
Arrays are enclosed in square brackets [ ] and comma separated.

In short a JSON object looks like

var blog = {
name: "the Digital Me",
author : "arun prabhakar",
pages : ["http://url1/","http://url2/"];
complexarray: [[0,10,10],[7,5,7],[1,9,8],[7,1,4]];
};


JSON and PHP
PHP has 2 built in functions to help with the JSON format.
json_encode
json_decode

Links

json.org
php.net JSON Functions

Sunday, June 17, 2007

Orkut Perl Script - Login, Scrapper and more

Intro
This is a PERL script that logs you into Orkut and allows you to scrap yiur friends. Following is the program and beneath it lies the manual to use the program. I assume that you already have PERL installed on your system with the required modules:

  • LWP
  • WWW::Mechanize


Program
#! /usr/bin/perl -w

use WWW::Mechanize;
use HTTP::Cookies;
use HTTP::Request::Common;

use subs qw(print_c login logout home grab proces scrap);


#autoflush STDOUT 1;

printf ("%45s","Command Line Orkut\n");
printf ("%50s","By http://digitalpbk.blogspot.com\n");

#inits
$cj=HTTP::Cookies->new(file => "cookie.jar",autosave=>1,ignore_discard=>1);
$mech = WWW::Mechanize->new(cookie_jar => $cj);

@prc = ("\n","[FAILED]","[ OK ]\n");
#main loop
print_c;
while(<STDIN>)
{
chomp;
@args = split(/ /);

if(@args)
{
exit 0 if($args[0] eq "exit" || $args[0] eq "q");

if($args[0] eq "login") {login(@args);}
elsif($args[0] eq "home") {home(@args);}
elsif($args[0] eq "logout") {logout(@args);}
elsif($args[0] eq "grab") {grab(@args);}
elsif($args[0] eq "process") {proces(@args);}
elsif($args[0] eq "scrap") {scrap(@args);}
elsif($args[0] eq "populate") {populate(@args);}
elsif($args[0] eq "captchaget") {captchaget(@args);}
elsif($args[0] eq "clear") {system("clear");}
print "\n";
}
print_c;
}

exit 0;


sub print_c
{
print "";
print "> ";
print "";
}

sub login
{


print "\nGmail iD : ";
$email = <STDIN>;
print "Password : ";
$pass = <STDIN>;
print $prc[0];

chomp $email;chomp $pass;

RELOGIN:
for($i=3; $i>=0;$i--)
{
printf("%-60s","GET /Home.aspx");
$mech->get("http://www.orkut.com/Home.aspx");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);
print $prc[2];


$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if($mech->title =~ m/orkut.*home/i)
{
print "\nAlready Logged In",$prc[0];

$cnt =~ m/<b>(.*)\@gmail.com<\/b>/;

print "\nLogout $1?[n] : ";
$com=<STDIN>;chomp $com;
if($com eq "y")
{
logout;
goto RELOGIN;
}
else
{
return;
}
}

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

printf("%-60.59s","Parsing for Login Page ");
#print $cnts;
if($cnt !~ m/id='liframe'.*?src='(.*)'/)
{
printf("%10s",$prc[1]);
print " Login page URL Not Found!\nTry Again OR Update the script! ".$prc[0];

return;
}

print $prc[2];
$url = $1;
$j=3;
REDO:
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","GET $url");
$mech->get($url);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);

print $prc[2];

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

$mech->form_number(1);
$mech->field("Email",$email."\@gmail.com");
$mech->field("Passwd",$pass);


printf("%-60.59s","Logging In ... ");

$mech->click("null");

$j--;
if($j && !$mech->success())
{
printf("%10s\n",$prc[1]);
goto REDO;
}
return unless($j);

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(!$mech->find_link(text => "click here to continue"))
{
printf("%10s",$prc[1]);
print "\nWrong Usename or Password!",$prc[0];
return;
}


print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","Continuing ...");
$mech->follow_link(text => "click here to continue");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return if($i<=0);

print $prc[2];

printf("%-60s","Parsing REDIRECT URL");
$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if($cnt !~ m/location.replace\("(.*)"\)/)
{
printf("%10s",$prc[1]);
print "\nRedirect script missing!",$prc[0];
return;
}

$url = $1;
$url =~ s/\\u003d/=/g;

print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","GET $url");
$mech->get($url);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}
return if($i<=0);

print $prc[2];
print "Logged In!";

#for($i=3; $i>=0;$i--)
#{
# printf("\n%-60s","GET /Home.aspx");
# $mech->get("http://www.orkut.com/Home.aspx");
# last if($mech->success());
#
# printf("%10s",$prc[1]);
# print " Retry (",$i,")".$prc[0] if($i);
#}

#return if($i<=0);
#print $prc[2];

}

sub logout
{

printf("%-60s","Parsing Logout");
if(!$mech->find_link(text => "Logout"))
{
printf("%10s",$prc[1]);
print "\nNot Logged In?",$prc[0];
return;
}


print $prc[2];
for($i=3;$i>=0;$i--)
{
printf("%-60.59s","Logging Out ...");
$mech->follow_link(text => "Logout");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}
return if($i<=0);

print $prc[2];
}

sub home
{
REHOME:
for($i=3; $i>=0;$i--)
{
printf("%-60s","GET /Home.aspx");
$mech->get("http://www.orkut.com/Home.aspx");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

if($i<=0)
{
print $mech->response->as_string;
return;
}
print $prc[2];

if($mech->title !~ m/orkut.*home/i)
{

print $mech->response->as_string;
print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto REHOME;
}
else
{
return;
}
}

#$mech->save_content("home.html");

$cnt = $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;
if($cnt =~ m/You are connected to <b>(.*)<\/b> people through <b>(.*)<\/b> friends./){
printf("\n%-20s: %0s (%0s)","Friends",$2,$1);}

if($cnt =~ m/([0-9]+) fans/){
printf("\n%-20s: %0s","Fans",$1);}

if($cnt =~ m/<b>([0-9]+)<\/b> scraps/i){
printf("\n%-20s: %0s","Scraps",$1);}

$cnt =~ m/my friends/g;
print "\nRecent : ";
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
print "\n\t$3";
}
}

sub grab_community
{
$comid = shift;
unless($file = shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}

$url = "/CommMembers.aspx?cmm=$comid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($mech->title !~ m/orkut.*Community.*Members/)
{
print "Unexpected Page ! : ",$mech->title;
return 0;
}


$cnt = $mech->response->as_string;
#$cnt =~ m/showing <b>1-15<\/b> of (.*?)<\/b>/g;
#print " $1";

open APP,">$file";
$grabed=0;
printf("%-25s","Grabbed: $grabed ");
for($page=2;;$page++)
{
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
$grabed++;
print APP "\n$1>$3";
}
print "\e[25D";
printf("%-25s","Grabbed: $grabed ");
sleep(3);
if($mech->find_link(text_regex => qr/next/i))
{
$mech->follow_link(text_regex => qr/next/i);
}
else
{
last;
}

last if(!$mech->success());

$cnt = $mech->response->as_string;
}
print "\nSaved to \"$file\"".$prc[0];
close APP;
return $grabed;
}

sub grab_flist
{

$comid = shift;
unless($file = shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}

$url = "/FriendsList.aspx?uid=$comid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($mech->title !~ m/orkut - (.*) Friends/)
{
print "Unexpected Page ! : ",$mech->title;
return 0;
}

print "$1 Friends : ".$prc[0];
$cnt = $mech->response->as_string;
#$cnt =~ m/showing <b>1-15<\/b> of (.*?)<\/b>/g;
#print " $1";

#$file =~ s/>//;
open APP,">$file";
$grabed=0;
printf("%-25s","Grabbed: $grabed ");
for($page=2;;$page++)
{
$cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g;
while($cnt =~ m/Profile\.aspx\?uid=(.*?)">(<b>)*([^<]+)(<\/b>)*<\/a>/g)
{
$grabed++;
print APP "\n$1>$3";
}
print "\e[25D";
printf("%-25s","Grabbed: $grabed ");
sleep(3);
if($mech->find_link(text=> $page))
{
$mech->follow_link(text => $page);
}
else
{
last;
}

last if(!$mech->success());

$cnt = $mech->response->as_string;
}
print "\nSaved to \"$file\"".$prc[0];
close APP;
return $grabed;
}

sub grab_wild
{
$limit = shift;
$got = 0;
my $file;

unless($file=shift)
{
print "\nFile to store : ";
$file = <STDIN>;
chomp $file;
}


print "\nCommunity ID : ";
$comid = <STDIN>;chomp $comid;


open APP4, ">>$file";
print APP4 "\n<comment>CommMem $comid</comment>";
close APP4;

if($comid)
{
$got = grab_community($comid,">$file");
}
else
{
print "\nFriend ID : ";
$comid=<STDIN>;chomp $comid;
print $comid;
return 0 unless($comid);

open APP3, ">>$file";
print APP3 "\n<comment>FriendOf $comid</comment>";
close APP3;

$got = grab_flist($comid,">$file");
}

return 0 unless($got);

$offset=0;
$visits=0;
RESPIDER:
$file =~ s/>//;
open DLL, "$file";
@uids = <DLL>;
close DLL;

$cnt = join("\n",@uids);
$cnt =~ s/<comment>.*?<\/comment>//g;
@uids = split(/\n/,$cnt);
@uids = @uids[$offset..$#uids];

foreach $userid (@uids)
{
if($userid =~ m/([0-9]+)>/)
{
$file =~ s/>//;
if(open APP2, ">>$file")
{
print APP2 "\n<comment>FriendOf $1</comment>";
close APP2;
}
else {print $!," $file";exit}

$got+= grab_flist($1,">$file");
$visits++;
print " Got $got ".$prc[0];
last if($limit < $got);
}
}
if($limit > $got)
{
$offset = $#uids + 1;
goto RESPIDER;
}
print "\n Spider Results : ".$prc[0];
printf("%-30s : %0s\n","Indexed",$got);
printf("%-30s : %0s\n","Spidered",$visits);
print " Tip : Dont forget to simplify the uid file ".$prc[0];
}

sub grab
{
shift;
$what = shift;
$where = shift;
$file = shift;
if(!($what && $where))
{

print "\nArguments missing".$prc[0];
return;
}
if(lc($what) eq "comm" || lc($what) eq "community") {grab_community($where,$file);}
elsif(lc($what) eq "flist" || lc($what) eq "friendlist") {grab_flist($where,$file);}
elsif(lc($what) eq "wild") {grab_wild($where,$file);}
}



sub process_uids
{
my $file;
unless($file=shift)
{
print "\nFile to read : ";
$file = <STDIN>;
chomp $file;
}

open DLL, "$file";
@uids = <DLL>;
close DLL;

$cnt = join("\n",@uids);
$cnt =~ s/<comment>.*?<\/comment>\n//g;
$cnt =~ s/[\n]+/>/g;
$cnt =~ s/>//;

%hc = split(/>/,$cnt);

$file .= ".s";
if($dest = shift) {$file=$dest;}

open DLL,">$file" or die("$!");

$inx=0;
foreach $key (sort keys %hc)
{
$val = $hc{$key};
$inx++;
printf("%6d %28s %0s\n",$inx,"$key","$val");
print DLL "$key>$val>";
}
close DLL;

}


sub proces
{
shift;
$what = shift;
$file = shift;
$extra = shift;
unless($what)
{
print "\nArguments missing".$prc[0];
return;
}

if(lc($what) eq "uids") {process_uids($file,$extra); }

}






sub scrap
{
shift;
$pat = shift;

unless($source=shift)
{
print "\nFile to read : ";
$source = <STDIN>;
chomp $source;
}

if(!open FILE,"$source")
{
print " File not found!".$prc[0];
return;
}
@contents = <FILE>;
close FILE;
chomp @contents;
$cnts = join("",@contents);

$cnts =~ s/<//g;

%hc = split(/>/,$cnts);
$no = 1;
$scrapall=0;
$sc_start=0;
$sc_end=0;
@fkeys=();

$pat = ".*" unless($pat);

foreach $key (sort keys %hc)
{
$val = $hc{$key};
if($val =~ m/$pat/i)
{
printf("%6d %28s %0s\n",$no,"$key","$val");
$no++;
push @fkeys, $key;
}
}

if($no==0)
{
print " Friend Not found !".$prc[0];
}

print "Enter Friend # : ";
$myc = <STDIN>;
chomp $myc;
#todos ...

if($myc =~ m/([0-9]+)-([0-9]+)/)
{
$scrapall=1;
$myc=$sc_start=$1;
$sc_end=$2;
}

if($myc > $no)
{
print "Invalid Response!!!".$prc[0];return;
}
print "Enter Scrap Text : ";
$sctext = <STDIN>;
$sctext =~ s/\\n/\n/g;
#PS: Please do not remove the following if you really like this .... :)
#Please post a link to my website http://digitalpbk.blogspot.com
#thank you :)
$sctext = $sctext."\n[red](Powered by [blue]digitalpbk[/blue].blogspot.com)";
chomp $sctext;

SCRAPNEXT:
$friendid = $fkeys[$myc-1];

print " Scrapping $myc $friendid [$hc{$friendid}]".$prc[0];
sleep(4);
$url = "/Scrapbook.aspx?uid=$friendid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}


return 0 if($i<=0);
print $prc[2];

$cnt= $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(($mech->title()) =~ m/orkut.*login/i)
{

print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto SCRAPNEXT;
}
else
{
return;
}

sleep(3);
goto SCRAPNEXT;
}


if($cnt =~ m/"POST_TOKEN" value="(.*?)"/){
$post_token = $1;}

#print $post_token," ";
if($cnt =~ m/"signature" value="(.*?)"/){
$signature=$1;}
#print $signature;
sleep(3);
for($i=3;$i>=0;$i--)
{
printf( "%-60s","POST scrap");

#$mech->agent_alias("Linux Mozilla");
$mech->request(POST "http://www.orkut.com$url",["POST_TOKEN"=>$post_token,"signature"=>$signature,"scrapText"=>$sctext,"Action.writeScrapBasic"=>"Submit+Query"]);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($scrapall && $myc < $sc_end)
{
$myc++;
goto SCRAPNEXT;
}
print " Done.".$prc[0];
}

sub populate
{

shift;
$pat = shift;

unless($source=shift)
{
print "\nFile to read : ";
$source = <STDIN>;
chomp $source;
}

if(!open FILE,"$source")
{
print " File not found!".$prc[0];
return;
}
@contents = <FILE>;
close FILE;
chomp @contents;
$cnts = join("",@contents);

$cnts =~ s/<//g;

%hc = split(/>/,$cnts);
$no = 1;
$scrapall=0;
$sc_start=0;
$sc_end=0;
@fkeys=();

$pat = ".*" unless($pat);

foreach $key (sort keys %hc)
{
$val = $hc{$key};
if($val =~ m/$pat/i)
{
printf("%6d %28s %0s\n",$no,"$key","$val");
$no++;
push @fkeys, $key;
}
}

if($no==0)
{
print " Friend Not found !".$prc[0];
}

print "Enter Friend # : ";

$myc = <STDIN>;
chomp $myc;
#todos ...

if($myc =~ m/([0-9]+)-([0-9]+)/)
{
$scrapall=1;
$myc=$sc_start=$1;
$sc_end=$2;
}

if($myc > $no)
{
print "Invalid Response!!!".$prc[0];return;
}

ADDNEXT:
$friendid = $fkeys[$myc-1];

print " Adding $myc $friendid [$hc{$friendid}]".$prc[0];
sleep(4);
$url = "/FriendAdd.aspx?uid=$friendid";


for($i=3; $i>=0;$i--)
{
printf("%-60s","GET $url");
$mech->get("http://www.orkut.com$url");
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}


return 0 if($i<=0);
print $prc[2];

$cnt= $mech->response->as_string;
$cnt =~ s/\n|\s+/ /g;

if(($mech->title()) =~ m/orkut.*login/i)
{

print "Not Logged In!",$prc[0];
print "\nLogin? [y] : ";
$com=<STDIN>;chomp $com;
if(not($com eq "n"))
{
login;
goto ADDNEXT;
}
else
{
return;
}

sleep(3);
goto ADDNEXT;
}


if($cnt =~ m/"POST_TOKEN" value="(.*?)"/){
$post_token = $1;}

#print $post_token," ";
if($cnt =~ m/"signature" value="(.*?)"/){
$signature=$1;}
#print $signature;
sleep(3);
for($i=3;$i>=0;$i--)
{
printf( "%-60s","POST add");

#$mech->agent_alias("Linux Mozilla");
$mech->request(POST "http://www.orkut.com$url",["POST_TOKEN"=>$post_token,"signature"=>$signature,"level"=>"3","Action.yes"=>"Submit+Query"]);
last if($mech->success());

printf("%10s",$prc[1]);
print " Retry (",$i,")".$prc[0] if($i);
}

return 0 if($i<=0);
print $prc[2];

if($scrapall && $myc < $sc_end)
{
$myc++;
goto ADDNEXT;
}
print " Done.".$prc[0];



}


sub captchaget
{
$mech->request(GET "http://www.orkut.com/CaptchaImage.aspx");
open JPEG, ">captcha.jpg";

print JPEG $mech->response->content;
close JPEG;

}


Installing and Executing
To Install Copy the above full program. Paste it in a new text file and rename it as orkut.pl.
To Execute the program open a terminal / DOS Prompt and navigate to the folder where you have the orkut.pl.
Then type
perl orkut.pl


Getting Started
Once you execute the program you get a screen as follows

Command Line Orkut
By http://digitalpbk.blogspot.com
>


Quick Start Scrap all your friends

Command Line Orkut
By http://digitalpbk.blogspot.com
> login
> home
> grab flist [uid here Profile.aspx?uid=some numbers right? copy that numbers here]
Enter File : myfriends
> process uids myfriends
> scrap
Enter File : myfreinds.s
1
2
3
4
.
.
.
N
Enter Friend Number: 1-N
Enter Scrap text : This is coooool.




Avaliable commands
  • login: This command is used to Login into Orkut.com, you will have to enter a valid Username and Password to enter the site. If someone is already logged in the command asks your confirmation to logout that person and log you in or to continue with the existing.

    > login

    Gmail ID : example@example.com
    Password : Password

    GET /Home.aspx [ OK ]
    Parsing for Login Page [ OK ]
    GET https://www.google.com/accounts/ServiceLoginBox?service [ OK ]
    Logging In ... [ OK ]
    Continuing ... [ OK ]
    Parsing REDIRECT URL [ OK ]
    GET http://www.orkut.com/RedirLogin.aspx?msg=0&page=http%3A [ OK ]
    Logged In!



  • home: This command parses the Home.aspx file and gives you a summary of the page as shown below. If you are not logged in the command executes the login and continues if successful.

    > home
    GET /Home.aspx [ OK ]

    Friends : 291 (57,431,788)
    Fans : 138
    Scraps : 4
    Recent :
    abcd (305)
    xyz (391)
    def (151)
    I maybe wrong... (301)
    fghhh (376)
    someone (289)
    exmple (673)
    real (679)


    The number in brackets in friends indicate the total number of people in orkut.
    Recent shows the recently online friends on orkut. All others mean what they stand for.

  • grab what from [to] : Before you can start scrapping or do anything further, you must first build a database of friends or list of orkut id's. The Grab function is used to make the database. It takes two parameters and an optional third parameter:
    • what where: can take values [comm or community | flist or friendlist | wild ]

      comm or community : indicates that the list of friends is going to be grabbed from a community. In this case the from specifies a community id. (Community.aspx?cmm=ID)

      flist or friendlist: indicates that the list of friends is going to be from a friend's friends. In this case the from specifies the Orkut uid (FriendsList.aspx?uid=ID)

      wild : this is a combo of the above and grabs as much people specified by second parameter.

    • to : is an optional parameter that specifies the file to store the grabbed id's. If this parameter is left out, you will be asked to enter the file. If the file exists the new data is appended to the old file.


  • process uids : The grabbed ids by grab is not well formatted and may contain duplicates the process uids command formats the database and makes a final file. This command asks for the source file and makes a new destination file named by appending a .s extension to the original file. The formatted database is displayed.


  • scrap [filter] [source db] : is used to scrap multiple people. It takes 2 optional arguments.
    1. Filter : filters the source db according to the name. If skiped all persons in the database will be marked for scrapping.
    2. Source DB : The .s file that is required. If skiped you will be asked to enter location.


    > scrap just

    File to read : sample.id.s
    1 12312312313123123123 Just for keepin the communities
    Enter Friend # : 1
    Enter Scrap Text : hii \n how are you?
    Scrapping 1 12312312313123123123 [Just for keepin the communities]
    GET /Scrapbook.aspx?uid=12312312313123123123 [ OK ]
    POST scrap [FAILED] Retry (3)
    POST scrap [ OK ]
    Done.

    Enter Friend #: Takes a number or a format like X-X where X is a number. When X-X format is given all people between those two numbers will be marked for scrapping.

    Enter Scrap Text: The scrap text to be entered. To add new lines type \n and the scrap will have newlines when scrapped.

  • populate [Filter] [Source DB]: Same as scrap but this time its used to add the specified people as your friends.

  • captchaget : Just to read a Captcha and store the image as captcha.jpg



License
You are free to modify and edit by retaining a link or reference to this site.
There is no warranty what so ever. Any incidents of Orkut Banning you, or similar events shall not be my responsibility. Provided solely for education purpose. Any damage or inconvenience caused by the script is deeply regretted.
You have been warned.

Winding up...
I know this manual was too brief. I have tried as much to describe the Script. You will have confusions and doubts regarding the usage so please post your questions as a comment. I will be more than glad to answer them. If you really loved it or got it working or was helpful to you let me know. And dont forget to place a link to this page, if you are submitting to another site or forum.

Thanx Happy Orkutting...
:)

PS: If you noticed the Perl script colour coded, and like that check this out.