sexta-feira, 11 de novembro de 2011

IP Fail over script writen in perl

This perl script provides an IP Fail Over enviroment, by testing the routes an jumping from one to another if the current route falls out of service.
More information on script comments.


#!/usr/bin/perl  
#
# (c) Daniel Hilst Selli, 2011, <danielhilst@gmail.com>
#
# IP FAIL OVER 
#
# Desc: Provides a IP FAIL OVER environment by testing the current routing and
#       changing it to next route if it fails. "ip" utility is used to change
#       the routes. 
#
# Usage: You need to configure the routes at @routes array. 
# /\_______update_the_comment_______________________/\
#
#       When ping fails on current route, the script searches for a new valid
#       route. That valid route will be the new default route.
#
#       The entry 0 is the standard route. You can request the script to go back
#       to standar route by sending a SIGUSR to it. The standard route will be
#       checked, if is not yet valid the script will not change the current
#       route.
#
#       $dest_host is the url that you will ping. I have setted it to
#       "www.google.com" but you can change it if needed.
#
#       This script goes to background as soon as possible. As a service should
#       do. You can define the log of it on $daemon_log variable. Its default is
#       the name of the script followed by ".log".
#


use strict;
use warnings; 
use Net::Ping; 
use POSIX qw(setsid);
use Time::localtime;
use Fcntl qw(:flock SEEK_END);


#
# START CONFIGURE HERE
#
my @routes = (
        {
#                iface =>  "ppp0",
                source => "200.171.87.72",
                gateway => "dev ppp0",
  init =>  sub {
      print ctime() .  " Rebooting ppp0\n";
      `ifdown ppp0`;
      `ifup ppp0`;
  },
        },
        {
                iface => "eth2",
                source => undef,
                gateway => "via 192.168.5.1",
        },
);
my $dest_host = "www.google.com";
my $standard_route = 1; # Used as index to @routes. So $routes[0] is the 
                        # standard route   
my $daemon_log = $0 . ".log"; 
#
# STOP CONFIGURE HERE
#



#
# Initialization 
# 
my $continue = 1;
my $pid;
my $indx = undef; 
my $current_route = undef;
my $pid_file = "$0.pid";
my $pid_fh = undef;
my $file_lock_fh = undef;
my $file_lock_fname = "$0.lck";
$| = 1; # unbuffered STDOUT

$SIG{TERM} = sub { $continue = 0 };

$SIG{USR1} = sub {
        print ctime() . " Standard route requested\n";
        if ($routes[$standard_route] == $current_route) {
                print ctime() . " the standard route is already".
                " being used, nothing to do\n";
        } elsif ($routes[$standard_route]->{ping}->ping($dest_host)) {
                print ctime() .  " Standard route is valid, ".
                "backing to it\n";
                $indx = $standard_route;
                set_route();
        } else {
                print ctime() . " Standard route offline, nothing to do\n";
        }
};

sub init_routes {
        for my $r (@routes) {
                if ($r->{source}) {
                        $r->{ping} = Net::Ping->new("icmp", 1);
                        $r->{ping}->bind($r->{source});
  } elsif ($r->{iface}) {
      $r->{ping} = Net::Ping->new("icmp", 1, 64, $r->{iface}); 
  } else {
      die "Route without source and iface member\n".
   "You need at least one of them\n";
  }
        } 

        die "\$standard_out setted to out of bounds of ". 
        "\@routes array\n" if $standard_route > $#routes;

        $indx = $standard_route;
        set_route();
}

sub do_flock {
        open($file_lock_fh, ">$file_lock_fname") or die "Can't open lock file".
 " $file_lock_fname";
        unless(flock($file_lock_fh, LOCK_EX | LOCK_NB)) {
                die "Cannot obtain lock. If there is another instance of".
                "this running kill it and try again";    
        }
}

sub do_funlock {
        my ($fname) = @_; 
        unless(flock($file_lock_fh, LOCK_UN)) {
                die "Cannot release lock, this shouldn't be happening";
        }
        close($file_lock_fh);
}

sub set_route {
        $current_route =  $routes[$indx];
        print ctime() . " Changing route to ".
        "$current_route->{gateway}\n";
 
 $current_route->{init}() if $current_route->{init};

        my $error = `ip route del default`; 
        print " Can't delete default route\n" if $error;

        $error = `ip route add default $current_route->{gateway}`;
        die " Can't add default route" if $error;

 print ctime() . " Route changed\n";
}

# Args
# 1 => Ref to global $indx variable
# 2 => The limmit 
sub next_indx {
        my ($indx, $limit) = @_;
        $$indx++;
        if ($$indx > $limit) {
                $$indx = 0;
        }
}


sub on_fail {
        my $error;
        
        print ctime() . " Ping failed\n";
        print ctime() . " Default route is $current_route->{gateway}. Adding new route\n";
        $error = `ip route del default via $current_route->{gateway}`; 
        die $! if $error;

        next_indx(\$indx, $#routes);
        set_route();

        print ctime() . " New route $current_route->{gateway} added\n";
}


sub daemonise {
        umask 0;
        open STDIN, '/dev/null'   or die "Can't read /dev/null: $!";
        open STDOUT, ">$daemon_log" or die "Can't write to log: $!";
        open STDERR, ">$daemon_log" or die "Can't write to log: $!";
        defined(my $pid = fork)   or die "Can't fork: $!";
        exit if $pid;
        setsid                    or die "Can't start a new session: $!"; }

#
# MAIN LOOP
#


do_flock();
daemonise();
init_routes();
while ($continue) {
        if ($current_route->{ping}->ping($dest_host)) {
#               print ctime();
#   if ($current_route->{source}) {
#       print " $current_route->{source} live\n";
#   } else {
#       print " $current_route->{iface} live\n";
#   }
                sleep(3);
        } else {
                on_fail();
        }
}
do_funlock();


# vim:ft=perl:tabstop=8:shiftwidth=4:smarttab:noexpandtab:softtabstop=4:ai:tw=80


container_of

/*
 * This example show how get sibling members of a struct. Suppose that you
 * have a struct foo with members A and B. With the macros provided here you can
 * get the address of B, having a pointer to A and knowing that B is the B member
 * of struct foo. This is not my work, is just based on macros provided by gcc
 * compiler __builtin_offsetof() and the container_of() macro found on linux
 * kernel sources. 
 */ 
#include <stdio.h> 

/*
 * You can get the offset of a member on a struct by dereferencing that member on
 * address 0 of such structure.
 */
#define offset_of(type, member) ((unsigned long) &((type *)0)->member)

/*
 * With the capability to get offsets, is possible to get the address of the
 * struct that contains some data. We just need a pointer to that data and the
 * offset of that data on the struct. With this informations we can calculate
 * the address of struct by subtracting the offset from the pointer to that data
 * contained on struct. In the macro above the @ptr is the data contained on
 * struct.
 */
#define container_of(ptr, type, member) \
        ((type *) ((char *)ptr - offset_of(type, member)))

struct foo {
        char *str;
        int len;
};

void print_sibling(int *ip);

int main(void)
{
        struct foo bar = {
                .str = "Hello World",
                .len= 11,
        }; 
        print_sibling(&bar.len);
        
        return 0;

}

/*
 * This function receives an int pointer (@ip) that is known to be the member "len" of
 * a "struct foo". With such information we can do the magic and take any
 * "sibling" member of that struct.
 */
void print_sibling(int *ip)
{
        struct foo *tmp = container_of(ip, struct foo, len);
        puts(tmp->str);
}


sábado, 22 de outubro de 2011

Character device Hello World

This is a little character device hello World, more
information on code.

/*
 * file: gkos_char_device.c
 *
 * Desc: A simple device that
 *      echos a message when read,
 *      write method not implemented
 *
 *      This was made on top of 
 *      LDD and LKMPG examples 
 *      
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>

#define DEVICE_NAME "gkos_char_device"


/*
 * Prototypes 
 */
int init_module(void);
void cleanup_module(void);
static int dev_open(struct inode *inode, struct file *);
static int dev_release(struct inode *inode, struct file *);
static ssize_t dev_read(struct file *fp, char *buf, size_t len, loff_t *off);
static ssize_t dev_write(struct file *, const char *buf, size_t len, 
                loff_t *off);
static int dev_init(void);

/*
 * Our variables, @use_counter
 * will block concurrenty opens.
 * @buffer is the message and
 * @buffer_len the lenght of @buffer (duh)
 */
static char use_counter = 0;
static char buffer[] = "Hello character device world\n";
static int buffer_len = sizeof(buffer);

static dev_t dev;
static struct cdev *cdevp;


static struct file_operations fops = {
        .owner = THIS_MODULE,
        .read = dev_read,
        .write = dev_write,
        .open = dev_open,
        .release = dev_release
};

/*
 * Any device specific initialization
 * goes here. Its called at bottom of init_module()
 */
static int dev_init(void)
{
        return 0;
}

/*
 * Called when device is opened
 */
static int dev_open(struct inode *inode, struct file *fp)
{
        if (use_counter)
                return -EBUSY;
        use_counter++;
        try_module_get(THIS_MODULE);
        return 0;
}

/* 
 * Called when device is released. The device is
 * released when there is no process using it.
 */
static int dev_release(struct inode *inode, struct file *fp)
{
        use_counter--;
        module_put(THIS_MODULE);
        return 0;
}


/*
 * @off controls
 * the "walk" through our buffer, is whith @off
 * that we say to user where is stoped.
 * @len is how much bytes to read. I almost ignore it.
 * I just check if is greater than 0.
 *
 * Called when device is read. 
 * This method will read one, and only one byte per call,
 * If @off is longer than my buffer size or len is not
 * greater than 0 it returns 0, otherwise I copy one byte
 * to user buffer and returns the bytes readed, so 1.
 */
static ssize_t dev_read(struct file *fp, char *buf, size_t len, loff_t *off)
{
        if (*off >= buffer_len || len <= 0)
                return 0;

        if (copy_to_user(buf, &buffer[*off], 1u))
                        return -EFAULT;

        (*off)++;
        return 1;
}


/*
 * Not implemented at all
 */
static ssize_t dev_write(struct file *fp, const char *buf, size_t len, 
                loff_t *off)
{
        return -ENOSYS;
}

/*
 * Called when module is load
 */
int init_module(void)
{
        int error;

        /* Alloc a device region */
        error = alloc_chrdev_region(&dev, 1, 1, DEVICE_NAME);
        if (error) 
                goto error_out;

        /* Registring */
        cdevp = cdev_alloc();
        if (!cdevp) 
                return -ENOMEM; 

        /* Init it! */
        cdev_init(cdevp, &fops); 

        /* Tell the kernel "hey, I'm exist" */
        error = cdev_add(cdevp, dev, 1);
        if (error < 0) 
                goto error_out;

        printk(KERN_INFO DEVICE_NAME " registred with major %d\n", MAJOR(dev));
        printk(KERN_INFO DEVICE_NAME " do: `mknod /dev/%s c %d %d' to create "
                        "the device file\n", 
                        DEVICE_NAME, MAJOR(dev), MINOR(dev)); 

        /* Device initialization isn't needed yet */
        if (dev_init())
                goto error_out;

        return 0;

error_out:
        return -EFAULT;
}

void cleanup_module(void)
{
        cdev_del(cdevp);
}

MODULE_LICENSE("GPL");

Makefile:
obj-m += gkos_char_device.o

all:
 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules 
 
clean:
 rm *.ko *.o *.mod.c *.mod.o

Building and Running:

sexta-feira, 21 de outubro de 2011

Perl assembly generator

I wrote a little perl script that receives input and creates an x86 assembly program. This program put all data on stack and then print it using printf c function. Useless but cool
#!/usr/bin/perl

use warnings;
use strict;

undef $/;
my $input = <>

$input = unpack("H*", $input);
my @integers;

while (length($input) > 8) {
 my $str = substr($input, 0, 8);
 $str =~ s/(.{2})(.{2})(.{2})(.{2})/$4$3$2$1/;
 push(@integers, ("0x".$str));
 $input = substr($input, 8);
}

my $buf = "";
while (length($input) > 0) {
 $buf .= substr($input, -2);
 $input = substr($input, 0, -2);
}

push(@integers, sprintf("0x%08x", hex($buf)));
my $stck_deep = ($#integers + 1) * 4;

print <<EOS
        .section        .text.startup,"ax",\@progbits
        .globl  main
        .type   main, \@function
main:
        pushl   %ebp
        movl    %esp, %ebp

 subl \$$stck_deep, %esp

 movl \$$integers[0], (%esp)
EOS
;

for my $i (1 .. $#integers) {
 printf("\tmovl \$%s, %d(%%esp)\n", $integers[$i], $i * 4); 
} 

print <<EOS
 movl \$0x0, $stck_deep(%esp)
 
 pushl %esp
 call printf
 popl %eax

 addl \$$stck_deep, %esp


 xorl %eax, %eax
 leave
 ret
EOS

;

Here is a try:
https://ideone.com/cuvXe
https://ideone.com/2oA9q
[]'s

terça-feira, 11 de outubro de 2011

Pickshit game ported to autotools

I have made just a exercise of applying autotools to my Pick stick game


Here is the "autotool'ed" source

[]'s

Procfs hello world

Fuck you world... I will learn kernel, getting payed or not!!


Here is a simple procfs hello world


The source (proc2.c)
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>

static struct proc_dir_entry *proc_file;

int procfile_read(char *buf, char **buf_location, off_t offset,
 int buf_len, int *eof, void *data)
{
 return sprintf(buf, "Hello Word\n"); 
}

#define PROC_FILE_NAME "hello"
int init_module()
{
 proc_file = create_proc_entry(PROC_FILE_NAME, 0644, NULL);
 if (!proc_file) { 
  remove_proc_entry(PROC_FILE_NAME, NULL);
  return -ENOMEM;
 } 
 proc_file->read_proc = procfile_read;
 proc_file->mode = 0644;
 proc_file->uid = 0;
 proc_file->gid = 0;
 proc_file->size = 37;
 return 0;
}


void cleanup_module()
{
 remove_proc_entry(PROC_FILE_NAME, NULL);
}

The Makefile
obj-m += proc2.o

all:
 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

Compiling and running


Cheers :-P

quinta-feira, 16 de junho de 2011

Java script

This is real life?

Yeah it is, so I get tired to run toward my dreams
and try to get a dev job. I choose php + javascript. I don't
really like php, but JavaScript can be really fun!!! Better than
live with support stress.

Here is my latest betting:


and
 The O'Reilly books are really the best ever! They come from
basic to advanced in a book that promises only the basic and
in a easy, clearly and deep speak.

So, web, there I go!