Mostrando postagens com marcador linux. Mostrar todas as postagens
Mostrando postagens com marcador linux. Mostrar todas as postagens

sexta-feira, 6 de julho de 2012

My two "just arrived" new kernel books

Understading the Linux Kernel 

amd Linux Device Drivers

terça-feira, 3 de julho de 2012

Resolving names and IPs

Here is two examples of name resolving in linux.. I use getaddrinfo() and getnameinfo() respectively..


getaddrinfo: given a name retuns all translated IPs, one per line
/*
 * File: getaddrinfo.c
 * Compile: gcc getaddrinfo.c -o getaddrinfo
 * Usage: ./getaddrinfo FQN
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char **argv)
{
        int error;

        struct addrinfo saddr, *psaddr, *ptr;

        memset(&saddr, '\0', sizeof(saddr));
        saddr.ai_family = AF_INET;


        saddr.ai_socktype = SOCK_STREAM;

        error = getaddrinfo(argv[1], NULL, &saddr, &psaddr);
        if (error) {
                fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
                exit(EXIT_FAILURE);
        }

        for (ptr = psaddr; ptr; ptr = ptr->ai_next) {
                puts(inet_ntoa(((struct sockaddr_in *)    
                               ptr->ai_addr)->sin_addr));
        }

        return 0;
}

getnameinfo: Given an IP returns the name that first resolves to it. 
/*
 * File: getnameinfo.c
 * Compile: gcc getnameinfo.c -o getnameinfo
 * Usage: ./getnameinfo IP
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

static char hostname[255];

int main(int argc, char **argv)
{
        int error;
        struct sockaddr_in saddr_in;



        memset(&saddr_in, '\0', sizeof(saddr_in));
        saddr_in.sin_family = AF_INET;
        error = inet_aton(argv[1], &saddr_in.sin_addr);
        if (error == 0) {
                perror("inet_aton");
                exit(EXIT_FAILURE);
        }

        error = getnameinfo((struct sockaddr *)&saddr_in, sizeof(saddr_in),
                            hostname, sizeof(hostname),
                            NULL, 0, NI_NAMEREQD);
        if (error) {
                fprintf(stderr, "getnameinfo: %s\n", gai_strerror(error));
                exit(EXIT_FAILURE);
        }

        puts(hostname);
        return 0;
}


Cheers

segunda-feira, 28 de novembro de 2011

Simple socket client

This sample application will connect to addres passed as first argument
and port passed as second argument. Then will send everything received from stdin
to that socket and send everything received as answer from socket to stdout. Simple!
Type quit to exit.

Is useful when you need to rember how to setup PF_INET sockects and when you need something simple
to talk with some socket.

Note: I have used `~' character as prompt.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

#define BUFLEN 0x400
static char buf[BUFLEN];

int main(int argc, char **argv)
{
    int sock;
    int addr_len;
    int error;
    struct sockaddr_in addr;
    struct hostent *host;

        
    if (argc <= 2) { 
        printf("Usage: %s address port\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        pexit("socket");


    host = gethostbyname(argv[1]);
    if (!host)
        pexit("gethostbyname");

    memcpy(&addr.sin_addr.s_addr, host->h_addr_list[0], sizeof(struct
                sockaddr_in));    
    addr.sin_family = PF_INET;
    addr.sin_port = htons(atoi(argv[2]));

    error = connect(sock, (struct sockaddr *)&addr, sizeof addr);
    if (error)
        pexit("connect");

    for (;;) {
        printf("~ "); /* my prompt */
        fgets(buf, BUFLEN, stdin);    
        if (!strcmp(buf, "quit\n"))
            break;

        error = send(sock, buf, strnlen(buf, BUFLEN), 0);        
        if (error == -1) /* error */
            pexit("send");

        error = recv(sock, buf, BUFLEN, 0);
        if (error == -1)
            pexit("recv");

        printf(buf);
    }    

    close(sock);
    return 0;
}

Testing:


sexta-feira, 11 de novembro de 2011

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: