Unite al grupo

Grupos de Google
Suscribirte a webandbeer
Correo electrónico:
Consultar este grupo

sábado, 18 de octubre de 2008

Introducción a DNS

Ayer, buscando una guía de configuración de bind, me encontré con este artículo que explica las nociones fundamentales sobre qué es un DNS y cómo funciona.

Me pareció muy bueno y bastante completo, así que lo comparto. A menudo noto que los programadores que trabajan en desarrollo web (y en algunos casos me incluyo), desconocen los protocolos que subyacen a sus tareas más cotidianas (HTTP, FTP, SSL, SSH, DNS, etc.) y esto dificulta muchas veces comprender lo que están haciendo o encontrar las razones de un problema específico. De la misma forma en que estoy convencido que para programar en PHP hay que tener alguna noción de C, para conocer "lo que hay abajo", creo que para laburar en desarrollo web hay que conocer estos protocolos.

Sin más preámbulos dejo el link: ¿Cómo funciona el DNS? según Javier Smaldone.

miércoles, 17 de septiembre de 2008

chistes de programadores

Nuestro amigo Tio Oscar nos pasa estos chistes como para relajarnos un rato.



Hiban 3 ingenieros en un auto, un ingeniero quimico, otro electronico y otro
de Microsoft, derrepente el auto queda detenido en el medio de la ruta sin
dar señales de vida, el ingeniero electronico sugiere: Vamos a hacer esto,
desmantelamos toda la instalacion electrica de coche, y vamos revisando las
partes modularmente para ver si no es un problema electrico, a lo que el
ingeniero químico sugiere: Yo creo que es un problema de conbustible,
podemos desmantelar la parte mecanica y mientras tanto medir la
dencidad y la propiedad de combustion de la nafta, a lo que los 2 se
pusieron a discutir, uno decia que era la parte electrica, el otro que
era el combustible, y asi muientras el ingeniero de microsoft
escuchaba, cansados de discutir le preguntan a este que se suponia era
el mas preparado para resolver problemas, a lo que este les dice que
tiene la solucion para estos casos: Hagamos esto; primero cerramos
todas las ventanas, luego salimos, luego volvemos a entrar, abrimos
nuevamentes las ventanas y de seguro todo funcionará de nuevo.


Dos programadores se encuentran en el campus de la facultad de
ingenieria, uno con una bicicleta muy copada, a lo que el otro le
pregunta de donde la habia sacado, el le responde: Era tarde y estaba
caminando de una reunion de Quake III a mi casa cuando aparecio mi
vecina la modelo, tiro la bicicleta a un lado, se saco la ropa y lo
tiro al otro y me dijo, toma de mi lo que quieras!... A lo que el otro
le responde: Buena eleccion, la ropa de seguro no te quedaba.


Un hombre se compra un globo aerostatico, facinado se le va la mano
con el fuego y se pierde, sin saber la direccion del globo y en el
medio del campo derrepente ve a un hombre en bisicleta, baja un poco
con el globo y le pregunta;

-Disculpe, sabe donde me encuentro?-
-Esta en un globo aerostatico a unos 10M del piso con un rumbo de unos
20kms/h hacia el suroeste.
- es usted programador no?, a lo que le responde;
- si, como se dio cuenta?,
- Porque toda la informacion que me dio es tecnicamente correcta, pero
no me sirve de nada
- Y usted es Jefe de una empresa de programacion no?
- Si, y usted como se dio cuenta?
- Por que no sabe a donde va, ni donde esta, pero ahora me hecha la culpa a mi.


Habia 3 ingenieros en un baño publico, uno que trabajaba
desarrollando en Mac, otro en Linux y otro en Windows.
Primero termina el de windows, bien arreglado, de traje y corbata, va
al lavamanos y usam mucha agua y mucho jabon para lavarse y acota "Los
que hacemos las cosa en Windows, las hacemos bien", el mac'ero
termina, se lava con poca agua, poco jabon, y usa solo una esquina de
la toalla y acota: "Los mac'eros no solo lo hacemos bien, sino que
optimizandolo bien, y el linuxero termina, se dirije a la puerta y les
dice "Los linuxeros no nos meamos las manos..."


Un chabon va a una tienda de electrodomesticos y le dice al vendedor,
Buenas quieria un lavarropas pequeño pero que soporte mucha carga,
que pueda lavar desde una media a toda la ropa de un equipo de futbol
siempre utilizando lo sumamente necesario para cada cada caso, que
venga con los planos y especificaciones de cada componente y
obviamente que sea gratis, claro, el transporte obviamente lo pongo
yo.
El tipo de la tienda lo mira, y enojado le dice, no, no tenemos nada
asi, por favor vallace.. el vendedor va a tomarse un descanzo a donde
estan los otros vendedores y al verlo llegar enojados le pregunta; que
paso luis?..
- Otro linuxero mas!!! otro linuxero!!!

Que tienen en comun un Hacker con un Abogado?
- Que los 2 se la pasan buscando errores en el codigo

viernes, 12 de septiembre de 2008

bug en svn

Estando trabajando con SVN, intente agregar una carpeta con archivos, en la cual habia un simpatico archivo llamado ---index.old.php


Resultados, paso a mostrarlos:


[root@developers /usr/local/www/depaginas.com]# svn add *
svn: invalid option: ---index.old.php
Type 'svn help' for usage.
[root@developers /usr/local/www/depaginas.com]#



En fin, me parece impresentable.

viernes, 5 de septiembre de 2008

TIps de SEO por profesionales.

SEO por Web&Beer

Gracias a la inquietud de saber un poco mas del tema, la semana pasada envie un mensaje a la lista, para ver si alguien me daba una mano con algun cosejo, para mejorar el SEO en mis sitios.

En resumen, aca esta todo lo que consegui

- Nombre del site, despues del verdaero title, ejem: "articulo sobre amapolas | pepe.com";
- h1, h2 , h3 ... bien puestos, en lo posible igual al title
- Keywors y description recomiendo que sean igual al titulo, mas una breve descripcion del contenido
- El url rewrite en base al titulo es mejor, ej: articulo-sobre-amapolas.html
- En lo posible, el "header" del site (contenido html repetitivo despues del body) que este semanticamente despues del contenido, y sin CSS tu documento tiene que quedar perfecto (bien maquetado digamos).
- Los menues dentro de listas, ya que google indexa con el tiempo esos links como "directorios" de contenido.
- Arma un sitemap dinamico, con php, y subido a google webmaster
- El robot.txt con que le indiques que indexe todo basta y sobra
- Si le pones google analytics tu site de indexa mucho mas rapido
- URLs con páginas .html las trata un poco mejor Google.
- El posicionamiento, por lo general, se hace eligiendo una/s palabra/s clave/s por página. Esa palabra o frase clave es la que vas a querer enfatizar a lo largo de todo el documento con las cosas que dijo Cesar, poniéndolo en el título, en los h1,h2,h3, etc., en negrita ( strong ) a lo largo del texto, etc. Es fundamental elegir bien esas palabras para obtener buenos resultados.
- La palabra o frase clave debe estar al principio y al final del documento (en el title, a principio del body pero también cerca del body en algún footer o algo así).
- La densidad de las palabras claves (es decir la cantidad de veces que aparece una palabra o frase en todo el documento, en relación con las otras palabras) no debería superar el 6 o 7%. Más de eso puede ser penalizable.
- Evitar a toda costa redirecciones de javascript. Siempre que sea necesario hacer redirecciones HTTP y preferentemente con HTTP Status 301 (moved permanently) en vez de otras como 301, 307, etc.
- Utilizar palabras claves en nombres de archivos (css, js, etc) y en las clases y Ids de los elementos HTML. También aprovechá algunos atributos y etiquetas que se usan poco, tipo poner muchos "name" (siempre en relación con el texto, spamear tu propio html no sirve), sobre todo en los links y otras boludeces así.
- Te recomiendo la extensión para Firefox "SEOQuake" que trae muchas herramientas copadas. Sino también esta URL tiene algunas cosas muy útiles: http://www.webconfs.com/
- Algunos meta-tags ya ni le dan bola los navegadores, pero no está de más ponerlos (robots, revisit-after). Los más tradicionales (descriptions, keywords y podríamos agregar searchtitle) tampoco se usan mucho pero son buenos. Ahí la recomendación es no poner muchas más palabras que las claves. Agregar sólo algunas más para balancear la densidad y en también puede ayudar agregar las palabras claves mal escritas (tipo: "hospedaje, ospedaje, hospedage").
- Un sitemap tradicional (no el sitemap.xml, sino una página con links a las principales secciones del sitio), también ayuda ya que da un punto de entrada asegurado a todas las páginas que querés que los buscadores indexen y además puede ser útil para los usuarios.
- Sugiero que al robots.txt le agregues un par de restricciones, sobre todo para que Google no indexe pelotudeces inútiles. Ponele le podés decir que no te indexe las carpetas donde tenés los JS y/o los CSS. También podés evitar que indexe secciones administrativas que sean accesibles desde internet.
- Siempre ayuda tener el XHTML y el CSS válidos.
- Mira el sitio con un navegador de texto (lynx x ejemplo) para que veas como lo "ven" los spiders
- La frecuencia con la cual actualizas los sitios
- Los backlinks siguen siendo lo mas importante, o sea agrega un par de bookmarks 2.0 (como por ejemplo: enviar a meneame), asi te pueden linkear

Después la clave está en ir aumentando el PageRank obteniendo links en otras páginas con buen PR, de temáticas relacionadas y con anclas (el texto del "a") que tengan que ver con aquella keyword para la que estás optimizando tu sitio.

La estrategia de posicionamiento se debe hacer con objetivos claros, para poder medirlos bien. También es importante la búsqueda de palabras claves, lo más específicas posibles, por ejemplo aparecer primero en "Vuelos baratos" de Argentina y España te va a costar mas que pedirle a Demián que adore al ZF.

Si tu sitio es nacional y se destaca por los viajes al interior trata de posicionarte en "viajes al interior del pais" por ejemplo. Aca tenes que ver cuales son las búsquedas que hacen los usuarios.

Cuando se evalua la relevancia de un contenido, un factor importante son los links a ese contenido, tanto externos como internos.

Los externos en cierta forma son dificiles de controlar, ya que depende de muchas cosas, y mas que nada del tipo de site, pero los internos si los podemos manejar, y el hecho de mayor cantida de links en si que tenga el site, como de links hacia un mismo lugar, aumentan el valor del contenido.

Un ejemplo (siguiendo con el tema del diario online), vos tenes las categorias, que son links hacia N cantidad de notas, pero si en cada nota haces referencias a notas "relacionadas", vas aumentando la cantidad de links internos hacia una misma nota.

Otra cosa importante es la cantidad de links, y como hacer para "mutar" esos links con el fin de obtener mas, y aca podemos usar una de las soluciones favoritas por mi, que son los filtros de busquedas por links, los cuales tinene 2 cosas positivas, potencia la cantidad de links, y no son contenido duplicado para google.

Por ejemplo, entro en la portada, y tengo todas las noticias del dia, pero arriba por medio de links establesco los filtros de "Espectaculos", "Sociales", "Policiales", etc. Cada vez que hago click en esos links, me filtra las noticias de la portada, mostrando las notas referidas a esa categoria. Por lo que en vez de tener solamente la "home", pase a tener N paginas representadas por cada categoria. Como es un diario, si tengo por fechas, tengo N x Z, donde N son las categorias, y Z los dias.
Pero esto es casi basico, ahora vamos a inventar mas links... como "Noticia mas leida del dia", "La mas comentada" (fundamental los comentarios de usuarios, son los que generaran mas paginas, y contenido todo el time para que nos indexen, yumi yumi).

Lean sobre esto, por que hay miles de estrategias para ser groso en materia SEO (www.educaedu.com.ar es un site bien indexado, depaginas.com.ar es otro groso del SEO, va el mejor).

Este documento fue extraido de la lista de de usuarios de webandbeer. Este contenido es parte del aporte de varios usuarios.

lunes, 1 de septiembre de 2008

WebAndBeer 4º edicion

Estimados colegas, ya es hora del 4º webandbeer, ya que todos asi lo han demandado.


Prometo sorpresas para la proxima edicion del webandbeer, y les recomiendo notebooks, por que vamos a hacer cosas interesantes.


En esta edicion, contaremos con el sponsoreo de Dream Designers, o los chicos de DePaginas para los amigos, donde habra comida y chupi gratis, ademas de buenas charlas y cosas de ese estilo.

Fecha: 09-09-2008, 19:30 hs.

El encuentro sera en el CicloBar, Guatemala 5800 (esq. Carranza), Buenos Aires, Argentina.


Esta vez, haremos pizza y birra, mas vino para los entendidos, y whisky para los borrachos de nivel Sr.



Para registrarse en el evento http://www.eventioz.com/events/webandbeer-4o-edicion


Invita: BSD Solutions – DreamDesigners


jueves, 28 de agosto de 2008

Nuevo algoritmo para incrementar la eficiencia de las redes

Estaba de paso y vi este artículo en Slashdot.

Una gente de la Universidad de California, desarrolló un nuevo algoritmo para incrementar significativamente la eficiencia de los ruteos de las redes de computadoras. Básicamente, según lo describe este artículo, el algoritmo es una nueva solución a la pregunta "¿Cuál es la mejor forma para ir de acá a allá?".

Es un algoritmo cuyo uso se justifica en redes dinámicas, donde los nodos se activan y desactivan constantemente. El artículo mencionado indica que la forma de trabajo actual hacía que cada vez que un nodo se desconectaba, todos los demás debieran actualizar su tabla re ruteo recalculando los mejores caminos para enviar los paquetes. Este algoritmo básicamente lo que hace es seleccionar cuáles de los updates es necesario enviar y cuáles no.

El paper completo se puede descargar en PDF de aquí.

miércoles, 27 de agosto de 2008

El bug más grande de internet

A través de Slashdot llego a esta noticia de Wired, según la cual un par de investigadores de seguridad informática revelaron el que sería el bug más grande de toda la arquitectura de internet.

Se trata de un error en el protocolo BGP (Border Gateway Protocol), a través del cual cualquier hijo de vecino (con conocimientos avanzados de networking, hacking y programación, por supuesto), podría tener acceso a todo el contenido no cifrado que circula por internet, modificandolo a su antojo. Básicamente a través de este agujero se puede "engañar" a los routers de todos lados para redirigir el tráfico hacia un eavesdropper, y hacer un ataque man-in-the-middle, y lo único que se necesita es tener un router con soporte para BGP (algo bastante común).

Este bug aparentemente había sido detectado en 1998 por Peiter "Mudge" Zatko, quien testificó e informó a "los burócratas de Washington" (como diría Monty Burns), y evidentemente todavía no se hizo nada al respecto. En realidad, parece que es algo sobre lo que se venía hablando hace tiempo, pero nadie lo había podido demostrar. En teoría era factible, pero nadie lo había llevado a la práctica. En la última DefCon Hacker Conference, Anton "Tony" Kapela y Alex Pilosov lo demostraron interceptando tráfico de la red de la conferencia, mandandolo a su sistema en New York y ruteandolo de vuelta a la conferencia. Ahora bien, esto no lo hicieron realmente a través de un bug o falla del protocolo BGP, sino explotando la forma en que el mismo funciona. Es decir que es un error estructural, porque la arquitectura de BGP se basa en la confianza en los nodos.

En la nota se da un ejemplo bastante sencillo:
Para enviar un mail desde los clientes de Sprint en California a los de Telefónica en Espala, las redes entre las compañías usan routers BGP para ver cuál es el camino nñas rápido y eficiente para que la información llegue a destino. Pero el protocolo BGP asume que el router realmente dice cuál es el mejor camino. De esta manera, los eavesdroppers pueden engañar a los routers diciendo que les manden el tráfico a ellos.


Más especificamente, cuando cualquiera hace un request a un server, el DNS resuelve una IP de destino a partir del dominio. Luego el router del ISP consulta una tabla BGP para obtener la mejor ruta. Esa tabla está compuesta de anuncios (casi como propagandas) hechos por ISPs y otras redes, que se llaman ASes Autonomous Systems, donde declaran el rango de IPs (o prefijos de IPs) a las cuales entregarán tráfico. En esa tabla se busca la IP de destino para los paquetes entre los distintos prefijos. Si hay dos ASes que tienen la misma IP, la que tenga el prefijo más específico "gana" el tráfico. Por ejemplo, si hay un prefijo que matchea con un rango de 90.000 IPs y otro con un grupo de 24.000, el tráfico se envía al segundo.


Entonces, para interceptar la información, un eavesdropper "publicita" un rango de IPs más acotado que el de otras redes y, una vez propagado el aviso, el tráfico empieza a llegar al interceptor. Esto no es algo nuevo y se llama IP Hijacking (lo que hizo una compañía pakistaní el año pasado con YouTube). El tema es que de la forma en que se venía haciendo se creaban desconexiones en la red (outages), lo cual hacía que los hijackings se descubrieran rápidamente.

La mejora de Kapela y Pilosov es que usan un método llamado "AS path prepending" (algo así como "preposición de la ruta del AS"), a través del cual pueden hacer que el tráfico llegue a su destino original (es decir, un man-in-the-middle, no como en el caso anterior donde el tráfico terminaba en otro lugar). Entonces, al no producirse fallas, no se detecta.

Luego el artículo sigue bastante y se explican diversas formas en que el error se puede combatir. De hecho los especialistas dicen que los ISPs están en condiciones de combatir este tipo de ataques, pero no lo hacen porque implica mucho trabajo y resulta costoso.

Realmente es un tema muy interesante y hay que seguirlo de cerca para ver qué cambios se hacen en la arquitectura de internet. Mientras tanto, y esto tampoco es nuevo, cualquier información importante ¡¡¡¡¡TIENE QUE VIAJAR ENCRIPTADA!!!!!

Ya salio Firebug 1.2

De esta manera se anunció el release oficial de la versión 1.2 del Firebug.

Básicamente es un release final luego de varias betas.

Aquí pueden ver las release notes completas, con todos los bugs corregidos y los nuevos features.

lunes, 4 de agosto de 2008

Instalar PHP 5.2.x en Centos

Estimado, tube un caso con un cliente al cual tube que instalar el PHP 5.2.x en su Centos 4.x, y fue una cosa que me volvio loco.


Despues de mucho googlear, encontre esta solucion que quiero compartir.

http://www.jasonlitka.com/2007/06/01/upgrading-to-php-523-on-rhel-and-centos/

[Articulo]

PHP 5.2.3 has been released. This version does not have the massive number of bug fixes that came with 5.2.2 (which included many of the patches from the Month of PHP Bugs), but it does have some useful fixes included, including the fix for the HTTP_RAW_POST_DATA bug that was introduced in PHP 5.2.2.

This build was relatively straight forward and didn't require any modifications to the spec file from my build of 5.2.2. I'll probably do a respin when MySQL 5.0.42 is finally marked as "released" (the source package is already available but the changelog hasn't been updated with an official release date).

For those that like to build from source, feel free to use the Source RPM from the link below. For my repository users, the new version is already available and all you'll need to do is run a "yum update".

UPDATE (6/19/2007): The PHP 5.2.3 packages have been updated. The Source RPM link below has also been updated to prevent anyone from downloading an out-of-date file.


If you want compile the src rpm yourseld here are the directions.

mkdir /usr/src/redhat
chmod -R 777 /usr/src/redhat

rpm -ivh php-5.2.3-jason.1.src.rpm

cd /usr/src/redhat/SPECS/

here you have a file dot spec with the configure and build lines.

rpmbuild -bb name_of_your_package.spec (in this case i think that is PHP)

when all finish right you have one or many package in the RPMS folder, you need update your current rpms with this, with the following command.

rpm -Uvh name_of_package_output.rpm








Convertir FreeBSD en PC-BSD

Util articulo que explica como convertir un FreeBSD a un PC-BSD (bue, el articulo es solo para aprender a hacerlo, ya que el flaco usa FreeBSD 7 y le deja un PC-BSD viejo, que require FreeBSD 6.3...)


http://sas-spidey01.livejournal.com/169139.html


[Articulo]


Converting FreeBSD into PC-BSD

Abstract




This post describes an example of how one can manually convert a FreeBSD installation into a PC-BSD one using the install disk. There are more elegant ways of doing it, such as pulling things from PC-BSDs SVN and compiling only PC-BSD specific components.




Disclaimers and warnings




This was done purely for 'fun' to see if the programs would work reasonably well. Which is why FreeBSD 7.0-Release was used as a base and PC-BSD 1.5.0 as the overlay (which is based on an old build of FreeBSD 6.3). I do not recommend, endorse, or even suggest actually doing something like this beyond exploratory or playful thoughts at heart !!!




If anyone actually tries this, your on your own.




If someone actually tries this they should probably use a PC-BSD 1.5.1 disk build, the files are newer.




Installing the PC-BSD v1.5.0-v1.5.1 update will install FreeBSD 6.3 files and may break your system -- note that I didn't enable the updater for my user account during this process.




Now that you are warned...




My test partition is reserved fro testing various alpha/beta/rc releases of operating systems I wish to test. So I wiped it clean and set out to install a basic working FreeBSD system.




I Installed FreeBSD 7.0-Release via CD-ROM, using the express option, auto
partitioning to save time, X-Developer dist set, and configured the system
lightly (set root pw, network services etc).



You want the X.org and related drivers from the disk, so they match your release level -- you also want source code for later to build a custom kernel (optional)




Booted the system and logged in as root, one vtty for work and one for logging my notes in vim over ssh.




Then began converting the system to a FreeBSD-PC-BSD hybrid. Since the FreeBSD auto mode for partitioning the slice only gave me a 512mb / and 512mb /tmp, I created a /usr/work directory to use.




NOTE:
actual PC-BSD systems require several gigs of space for / to ensure safe updates and this is noted during previous upgrade notes. My guess after reading some of the 1.4/1.5 scripts is the developers have 'yet' to figure out how to use mount -a for mounting the needed file systems before extracting files and reserved storage places with the default partitioning scheme



pkg_add -r lzma && rehash  # to unpack pc-bsd files
mount -t cd9690 /dev/acd0 /mnt # mount pc-bsd disk 1
mkdir -m 0700 /usr/work
lzma d /mnt/PCBSD.tar.lzma /usr/work/PCBSD.tar
...
# lzma has fast decompression speeds but
# this is a ~451mb lzma file being
# unpacked into a 1.9gb tar file!

tar -C / -kpf /usr/work/PCBSD.tar # extract files without overwrite

cp /etc/rc.conf /etc/rc.conf.local # fix rc.conf
tar -C /tmp -f /usr/work/PCBSD.tar -px './etc'
cp /tmp/etc/rc.conf /etc/rc.conf
cp /tmp/etc/devfs.conf /etc/devfs.conf # modified in pc-bsd

vi /etc/ttys # start x on boot up
... # note the ttyvNum is arbitrary
#ttyv8 "/usr/local/bin/xdm -nodaemon" xterm off secure
ttyv8 "/PCBSD/bin/pdm" xterm on secure
...
X -configure && mv /root/xorg.conf.new /etc/X11/xorg.conf

#
# create users and groups that come with PC-BSD 1.5.0 but not FreeBSD
# 7.0-Release. Numerical values for -u userid and -g groupid are taken from
# viewing a unified diff of the group files.
#
pw groupadd -n haldaemon -g 560
pw groupadd -n cups -g 193
pw groupadd -n cyrus -g 60
pw useradd -n haldaemon -u 560 -g 560 -L daemon -d /nonexistent \
-s /usr/sbin/nologin
pw useradd -n cups -u 193 -g 193 -L daemon -d /nonexistent -s /usr/sbin/nologin
pw useradd -n cyrus -u 60 -g 60 -L daemon -d /nonexistent -s /usr/sbin/nologin

#
# add my own user with the bash shell as a test (because it. Note that I typically set
# user/group id numbers by year of birth.
#
pw groupadd -n Terry -g 1988
pw useradd -n Terry -u 1988 -L default -m -s bash -g Terry \
-G wheel,operator
passwd Terry
...

#
# now build a custom kernel merging GENERIC with /PCBSD/conf/PCBSD.i386
# I find Micro GNU Emacs (mg) to be both light and effective for this task.
# -- normally I would use vimdiff
#
pkg_add -r mg && rehash # if using mg !
cat > ~/.mg
auto-fill-mode
set-fill-column 78
global-set-key "\^x\^f" find-file
global-set-key "\^h" delete-backward-char
set-default-mode blink
^D # end of ~/.mg

diff -u /usr/src/sys/i386/conf/GENERIC /PCBSD/conf/PCBSD.i386 > /tmp/kern.diff
cd /usr/src/sys/i386/conf
mg KAI
... # kernel config attached at EOF
# used GENERIC and /tmp/kern.diff to
# write the file if needed.

cd /usr/src # compile & install kernel
make -j12 buildkernel KERNCONF=KAI
... # roughly 10 minutes later..
make -j12 installkernel KERNCONF=KAI
...
umount /mnt && cdcontrol -f /dev/acd0 eject
reboot # let's rock it and roll on to KDE




On reboot, I was greeted with KDM, PC-BSDs login theme, and a clean startup of KDE (no error message popups). I was able to install and use the Firefox PBI from PBIDir without problems. But as one can see in the screen shots, there are sound system related core dumps



Free Image Hosting at www.ImageShack.us

Free Image Hosting at www.ImageShack.us

Free Image Hosting at www.ImageShack.us



I was also interested to see that there is now a 'snd_emu10kx' driver added in FreeBSD 7.0-Release which supports my card. So I guess I won't have to manually compile the 'outdated, unmaintained, etc' audio/emu10kx port to get working sound, the manual page seems to suggest it is the same driver more or less. I only had to add an entry to my loader.conf file to get it loaded before PC-BSD sound detection system, just like audio/emu10kx from ports it won't work (for me) if kldload'ed later on.




I found that although everything I tested was working fine, audio and video related apps were dumping core (mplayer at start, kaffeine during playback). So I did a pkg_delete on kaffeine and kaffeine-mozilla and reinstalled from packages and soon was blasting MP3's from a FAT32 partition ;-)




MPlayer needs to be recompiled as expected, The KDE sound system will likely need that to but otherwise I've observed no real breakages. Not that I've taken the time to test every single program!




Personal Opinions




If like me, your primary reason for using PC-BSD is a quick way of grabbing KDE -- you would be better off installing PC-BSD! As far as setting up a working desktop system, one can do that easy through FreeBSD. If one doesn't want to go into configuration details for 'extra's like PF or X11 using PC-BSD or DesktopBSD is a better idea anyway.





If all you want is PBI, export, compile, and install the necessary files from PC-BSDs SVN repository.





Kernel Configuration: KAI




Note to SATA hard drives out there, the ATA_STATIC_ID option effects device numbering. FreeBSD GENERIC kernel configuration uses it and detects my SATA drive as 'ad4', PC_BSD kernel configuration has it turned off and detects my drive as 'ad0' -- I only have one SATA II hard drive installed.




Changing the ATA_STATIC_ID kernel option means you will havve to make sure /etc/fstab is in working shape unless you want to see a mount root prompt.



#
# Custom FreeBSD 7.0 kernel based on PC-BSD 1.5 Kernel config for FreeBSD 6.3
#

cpu I686_CPU
ident KAI



#options SCHED_$BSD # 4BSD scheduler
options SCHED_ULE # ULE scheduler ;-)
options PREEMPTION # ENABLE KERNEL THREAD PREEMPTION
options INET # INTERNETWORKING
options INET6 # IPV6 COMMUNICATIONS PROTOCOLS
options SCTP # STREAM CONTROL TRANSMISSION PROTOCOL
options FFS # BERKELEY FAST FILESYSTEM
options SOFTUPDATES # ENABLE FFS SOFT UPDATES SUPPORT
options UFS_ACL # SUPPORT FOR ACCESS CONTROL LISTS
options UFS_DIRHASH # IMPROVE PERFORMANCE ON BIG DIRECTORIES
options UFS_GJOURNAL # ENABLE GJOURNAL-BASED UFS JOURNALING
options MD_ROOT # MD IS A POTENTIAL ROOT device
options NFSCLIENT # NETWORK FILESYSTEM CLIENT
options NFSSERVER # NETWORK FILESYSTEM SERVER
options NFS_ROOT # NFS USABLE AS /, REQUIRES NFSCLIENT
options MSDOSFS # MSDOS FILESYSTEM
options CD9660 # ISO 9660 FILESYSTEM
options PROCFS # PROCESS FILESYSTEM (REQUIRES PSEUDOFS)
options PSEUDOFS # PSEUDO-FILESYSTEM FRAMEWORK
options GEOM_PART_GPT # GUID PARTITION TABLES.
options GEOM_LABEL # PROVIDES LABELIZATION
options COMPAT_43TTY # BSD 4.3 TTY COMPAT [KEEP THIS!]
options COMPAT_FREEBSD4 # COMPATIBLE WITH FREEBSD4
options COMPAT_FREEBSD5 # COMPATIBLE WITH FREEBSD5
options COMPAT_FREEBSD6 # COMPATIBLE WITH FREEBSD6
options SCSI_DELAY=5000 # DELAY (IN MS) BEFORE PROBING SCSI
options KTRACE # KTRACE(1) SUPPORT
options SYSVSHM # SYSV-STYLE SHARED MEMORY
options SYSVMSG # SYSV-STYLE MESSAGE QUEUES
options SYSVSEM # SYSV-STYLE SEMAPHORES
options _KPOSIX_PRIORITY_SCHEDULING # POSIX P1003_1B REAL-TIME EXTENSIONS
options KBD_INSTALL_CDEV # INSTALL A CDEV ENTRY IN /DEV
options ADAPTIVE_GIANT # GIANT MUTEX IS ADAPTIVE.
options STOP_NMI # STOP CPUS USING NMI INSTEAD OF IPI
options AUDIT # SECURITY EVENT AUDITING

# TO MAKE AN SMP KERNEL, THE NEXT TWO LINES ARE NEEDED
options SMP # SYMMETRIC MULTIPROCESSOR KERNEL
device apic # I/O APIC

# CPU FREQUENCY CONTROL
device cpufreq

# BUS SUPPORT.
device eisa
device pci


# FLOPPY DRIVES
device fdc

# ATA AND ATAPI deviceS
device ata
device atadisk # ATA DISK DRIVES
device ataraid # ATA RAID DRIVES
device atapicd # ATAPI CDROM DRIVES
device atapifd # ATAPI FLOPPY DRIVES
device atapist # ATAPI TAPE DRIVES
options ATA_STATIC_ID # STATIC device NUMBERING
device atapicam # Atapi CAM support

# SCSI CONTROLLERS
device ahb # EISA AHA1742 FAMILY
device ahc # AHA2940 AND ONBOARD AIC7XXX deviceS
options AHC_REG_PRETTY_PRINT # PRINT REGISTER BITFIELDS IN DEBUG
# OUTPUT. ADDS ~128K TO DRIVER.
device ahd # AHA39320/29320 AND ONBOARD AIC79XX deviceS
options AHD_REG_PRETTY_PRINT # PRINT REGISTER BITFIELDS IN DEBUG
# OUTPUT. ADDS ~215K TO DRIVER.
device amd # AMD 53C974 (TEKRAM DC-390(T))
device isp # QLOGIC FAMILY
#device ispfw # FIRMWARE FOR QLOGIC HBAS- NORMALLY A MODULE
device mpt # LSI-LOGIC MPT-FUSION
#device ncr # NCR/SYMBIOS LOGIC
device sym # NCR/SYMBIOS LOGIC (NEWER CHIPSETS + THOSE OF `NCR')
device trm # TEKRAM DC395U/UW/F DC315U ADAPTERS

device adv # ADVANSYS SCSI ADAPTERS
device adw # ADVANSYS WIDE SCSI ADAPTERS
device aha # ADAPTEC 154X SCSI ADAPTERS
device aic # ADAPTEC 15[012]X SCSI ADAPTERS, AIC-6[23]60.
device bt # BUSLOGIC/MYLEX MULTIMASTER SCSI ADAPTERS

device ncv # NCR 53C500
device nsp # WORKBIT NINJA SCSI-3
device stg # TMC 18C30/18C50

# SCSI PERIPHERALS
device scbus # SCSI BUS (REQUIRED FOR SCSI)
device ch # SCSI MEDIA CHANGERS
device da # DIRECT ACCESS (DISKS)
device sa # SEQUENTIAL ACCESS (TAPE ETC)
device cd # CD
device pass # PASSTHROUGH device (DIRECT SCSI ACCESS)
device ses # SCSI ENVIRONMENTAL SERVICES (AND SAF-TE)

# RAID CONTROLLERS INTERFACED TO THE SCSI SUBSYSTEM
device amr # AMI MEGARAID
device arcmsr # ARECA SATA II RAID
device asr # DPT SMARTRAID V, VI AND ADAPTEC SCSI RAID
device ciss # COMPAQ SMART RAID 5*
device dpt # DPT SMARTCACHE III, IV - SEE NOTES FOR options
device hptmv # HIGHPOINT ROCKETRAID 182X
device hptrr # HIGHPOINT ROCKETRAID 17XX, 22XX, 23XX, 25XX
device iir # INTEL INTEGRATED RAID
device ips # IBM (ADAPTEC) SERVERAID
device mly # MYLEX ACCELERAID/EXTREMERAID
device twa # 3WARE 9000 SERIES PATA/SATA RAID

# RAID CONTROLLERS
device aac # ADAPTEC FSA RAID
device aacp # SCSI PASSTHROUGH FOR AAC (REQUIRES CAM)
device ida # COMPAQ SMART RAID
device mfi # LSI MEGARAID SAS
device mlx # MYLEX DAC960 FAMILY
device pst # PROMISE SUPERTRAK SX6000
device twe # 3WARE ATA RAID

# ATKBDC0 CONTROLS BOTH THE KEYBOARD AND THE PS/2 MOUSE
device atkbdc # AT KEYBOARD CONTROLLER
device atkbd # AT KEYBOARD
device psm # PS/2 MOUSE


device vga # VGA VIDEO CARD DRIVER

device splash # SPLASH SCREEN AND SCREEN SAVER SUPPORT

# SYSCONS IS THE DEFAULT CONSOLE DRIVER, RESEMBLING AN SCO CONSOLE
device sc

device agp # SUPPORT SEVERAL AGP CHIPSETS

# POWER MANAGEMENT SUPPORT (SEE NOTES FOR MORE options)
#device apm
# ADD SUSPEND/RESUME SUPPORT FOR THE I8254.
device pmtimer

# PCCARD (PCMCIA) SUPPORT
# PCMCIA AND CARDBUS BRIDGE SUPPORT
device cbb # CARDBUS (YENTA) BRIDGE
device pccard # PC CARD (16-BIT) BUS
device cardbus # CARDBUS (32-BIT) BUS

# SERIAL (COM) PORTS
device sio # 8250, 16[45]50 BASED SERIAL PORTS
device uart # GENERIC UART DRIVER

# PARALLEL PORT
device ppc
device ppbus # PARALLEL PORT BUS (REQUIRED)
device lpt # PRINTER
device plip # TCP/IP OVER PARALLEL
device ppi # PARALLEL PORT INTERFACE device
#device vpo # REQUIRES SCBUS AND DA

# IF YOU'VE GOT A "DUMB" SERIAL OR PARALLEL PCI CARD THAT IS
# SUPPORTED BY THE PUC(4) GLUE DRIVER, UNCOMMENT THE FOLLOWING
# LINE TO ENABLE IT (CONNECTS TO SIO, UART AND/OR PPC DRIVERS):
#device puc

# PCI ETHERNET NICS.
device de # DEC/INTEL DC21X4X (``TULIP'')
device em # INTEL PRO/1000 ADAPTER GIGABIT ETHERNET CARD
device ixgb # INTEL PRO/10GBE ETHERNET CARD
device le # AMD AM7900 LANCE AND AM79C9XX PCNET
device txp # 3COM 3CR990 (``TYPHOON'')
device vx # 3COM 3C590, 3C595 (``VORTEX'')

# PCI ETHERNET NICS THAT USE THE COMMON MII BUS CONTROLLER CODE.
# NOTE: BE SURE TO KEEP THE 'device MIIBUS' LINE IN ORDER TO USE THESE NICS!
device miibus # MII BUS SUPPORT
device bce # BROADCOM BCM5706/BCM5708 GIGABIT ETHERNET
device bfe # BROADCOM BCM440X 10/100 ETHERNET
device bge # BROADCOM BCM570XX GIGABIT ETHERNET
device dc # DEC/INTEL 21143 AND VARIOUS WORKALIKES
device fxp # INTEL ETHEREXPRESS PRO/100B (82557, 82558)
device lge # LEVEL 1 LXT1001 GIGABIT ETHERNET
device msk # MARVELL/SYSKONNECT YUKON II GIGABIT ETHERNET
device nfe # NVIDIA NFORCE MCP ON-BOARD ETHERNET
device nge # NATSEMI DP83820 GIGABIT ETHERNET
#device nve # NVIDIA NFORCE MCP ON-BOARD ETHERNET NETWORKING
device pcn # AMD AM79C97X PCI 10/100 (PRECEDENCE OVER 'LE')
device re # REALTEK 8139C+/8169/8169S/8110S
device rl # REALTEK 8129/8139
device sf # ADAPTEC AIC-6915 (``STARFIRE'')
device sis # SILICON INTEGRATED SYSTEMS SIS 900/SIS 7016
device sk # SYSKONNECT SK-984X & SK-982X GIGABIT ETHERNET
device ste # SUNDANCE ST201 (D-LINK DFE-550TX)
device stge # SUNDANCE/TAMARACK TC9021 GIGABIT ETHERNET
device ti # ALTEON NETWORKS TIGON I/II GIGABIT ETHERNET
device tl # TEXAS INSTRUMENTS THUNDERLAN
device tx # SMC ETHERPOWER II (83C170 ``EPIC'')
device vge # VIA VT612X GIGABIT ETHERNET
device vr # VIA RHINE, RHINE II
device wb # WINBOND W89C840F
device xl # 3COM 3C90X (``BOOMERANG'', ``CYCLONE'')

# ISA ETHERNET NICS. PCCARD NICS INCLUDED.
device cs # CRYSTAL SEMICONDUCTOR CS89X0 NIC
# 'device ED' REQUIRES 'device MIIBUS'
device ed # NE[12]000, SMC ULTRA, 3C503, DS8390 CARDS
device ex # INTEL ETHEREXPRESS PRO/10 AND PRO/10+
device ep # ETHERLINK III BASED CARDS
device fe # FUJITSU MB8696X BASED CARDS
device ie # ETHEREXPRESS 8/16, 3C507, STARLAN 10 ETC.
device sn # SMC'S 9000 SERIES OF ETHERNET CHIPS
device xe # XIRCOM PCCARD ETHERNET

# WIRELESS NIC CARDS
device wlan # 802.11 SUPPORT
device wlan_wep # 802.11 WEP SUPPORT
device wlan_ccmp # 802.11 CCMP SUPPORT
device wlan_tkip # 802.11 TKIP SUPPORT
device wlan_amrr # AMRR TRANSMIT RATE CONTROL ALGORITHM
device wlan_scan_ap # 802.11 AP MODE SCANNING
device wlan_scan_sta # 802.11 STA MODE SCANNING
device an # AIRONET 4500/4800 802.11 WIRELESS NICS.
device ath # ATHEROS PCI/CARDBUS NIC'S
device ath_hal # ATHEROS HAL (HARDWARE ACCESS LAYER)
device ath_rate_sample # SAMPLERATE TX RATE CONTROL FOR ATH
device awi # BAYSTACK 660 AND OTHERS
device ral # RALINK TECHNOLOGY RT2500 WIRELESS NICS.
device wi # WAVELAN/INTERSIL/SYMBOL 802.11 WIRELESS NICS.
#device wl # OLDER NON 802.11 WAVELAN WIRELESS NIC.

# PSEUDO deviceS.
device loop # NETWORK LOOPBACK
device random # ENTROPY device
device ether # ETHERNET SUPPORT
device sl # KERNEL SLIP
device ppp # KERNEL PPP
device tun # PACKET TUNNEL.
device pty # PSEUDO-TTYS (TELNET ETC)
device md # MEMORY "DISKS"
device gif # IPV6 AND IPV4 TUNNELING
device faith # IPV6-TO-IPV4 RELAYING (TRANSLATION)
device firmware # FIRMWARE ASSIST MODULE

# THE `BPF' device ENABLES THE BERKELEY PACKET FILTER.
# BE AWARE OF THE ADMINISTRATIVE CONSEQUENCES OF ENABLING THIS!
# NOTE THAT 'BPF' IS REQUIRED FOR DHCP.
device bpf # BERKELEY PACKET FILTER

# USB SUPPORT
device uhci # UHCI PCI->USB INTERFACE
device ohci # OHCI PCI->USB INTERFACE
device ehci # EHCI PCI->USB INTERFACE (USB 2.0)
device usb # USB BUS (REQUIRED)
#device udbp # USB DOUBLE BULK PIPE deviceS
device ugen # GENERIC
device uhid # "HUMAN INTERFACE deviceS"
device ukbd # KEYBOARD
device ulpt # PRINTER
device umass # DISKS/MASS STORAGE - REQUIRES SCBUS AND DA
device ums # MOUSE
device ural # RALINK TECHNOLOGY RT2500USB WIRELESS NICS
device rum # RALINK TECHNOLOGY RT2501USB WIRELESS NICS
device urio # DIAMOND RIO 500 MP3 PLAYER
device uscanner # SCANNERS
# USB ETHERNET, REQUIRES MIIBUS
device aue # ADMTEK USB ETHERNET
device axe # ASIX ELECTRONICS USB ETHERNET
device cdce # GENERIC USB OVER ETHERNET
device cue # CATC USB ETHERNET
device kue # KAWASAKI LSI USB ETHERNET
device rue # REALTEK RTL8150 USB ETHERNET

# FIREWIRE SUPPORT
device firewire # FIREWIRE BUS CODE
device sbp # SCSI OVER FIREWIRE (REQUIRES SCBUS AND DA)
device fwe # ETHERNET OVER FIREWIRE (NON-STANDARD!)
device fwip # IP OVER FIREWIRE (RFC 2734,3146)
device dcons # DUMB CONSOLE DRIVER
device dcons_crom # CONFIGURATION ROM FOR DCONS


#
# from PC-BSD conf
#
options LIBICONV
options LIBMCHAIN
options CD9660_ICONV
options MSDOSFS_ICONV
options NTFS
options NTFS_ICONV
options UDF
options UDF_ICONV
options GEOM_UZIP # read only compressed disks
# wifi
device wlan
device wlan_wep
device wlan_ccmp
device wlan_tkip
device an
device ath
device ath_hal
device ath_rate_sample
device awi
device ral
device wi
device iwi
device ipw
device firmware
options DEVICE_POLLING
device pf
device pflog
device pfsync
options ALTQ
options ALTQ_CBQ
options ALTQ_RED
options ALTQ_RIO
options ALTQ_HFSC
options ALTQ_CDNR
options ALTQ_PRIQ
options ALTQ_NOPCC



Como crear un modulo para el kernel de FreeBSD

Este articulo explica de forma simple, como se crea un modulo para el Kernel de FreeBSD.

La verdad, es que me parece que es muy simple de entender.

http://www.freesoftwaremagazine.com/articles/writing_a_kernel_module_for_freebsd


[Articulo]


FreeBSD 7.0 has already been released. If you are a real hacker, the best way to jump in and learn it is hacking together an introductory kernel module. In this article I’ll implement a very basic module that prints a message when it is loaded, and another when it is unloaded. I’ll also cover the mechanics of compiling our module using standard tools and rebuilding the stock FreeBSD kernel. Let’s do it!

Getting Started

There are some prerequisites for this article. I assume you have a little bit of C programming knowledge, though nothing too fancy. If I reference a pointer or a structure, I expect you to understand those concepts without much explanation. I also expect you to be familiar with UNIX-like operating systems and know your way around basic shell usage.

The first thing to do is make sure the development environment you’ll be working in includes everything and is configured properly. I’m going to assume you already have FreeBSD installed and running. If you don’t, and would like some guidance, you can read my article: Secure emails servers with FreeBSD. I’ll be doing a few things differently; so, I would recommend just using it as a resource for the installation, which is identical in both scenarios.

You will also need to make sure the sudo utility is installed and configured for your main user account. This is required to run as “root” the utilities kldload and kldunload. The FreeBSD port for sudo is in /usr/ports/security/sudo.

cd /usr/port/security/sudo
make install && make clean

Now su to root and run the visudo utility. Visudo uses the EDITOR environment variable to determine which text editor to use. If you don’t like the default one, override it with setenv EDITOR vim if you are using the default CSH, or export EDITOR=vim if you are using bash. Then simply re-run visudo.

su
visudo

The visudo utility does basic sanity checking on the syntax and makes sure no two people edit the sudoers file at the same time.

# Look for this line, copy it and change the "root" user to your main users name.
root ALL=(ALL) SETENV: ALL
yourabi ALL=(ALL) SETENV: ALL

Your first kernel

As I mentioned in my recent article Review of FreeBSD 7.0, the ULE scheduler brings a new level of performance and multi-processor scalability to FreeBSD. Though it is now considered stable and ready for prime-time, it will not be enabled by default until the 7.1 release. A good litmus test of your setup will be compiling a custom kernel with the ULE scheduler enabled.

If you are on an x86 based machine, the kernel is located in the /usr/src/sys/i386 directory. For amd64 machines, simply replace i386 with amd64, which becomes /usr/src/sys/amd64. The kernel configuration file is located in a directory called conf. Enter that directory and create your own custom kernel configuration file by copying the “generic” default configuration to one of our own naming.

cd /usr/src/sys/amd64/conf
cp GENERIC CUSTOM

Now it’s time to enable the new ULE scheduler. The new ULE scheduler brings improved performance and scalability compared to the legacy scheduler and also serves as a good demonstration of building and installing a custom kernel.

Open the “CUSTOM” file with your text editor of choice and find the line enabling the legacy 44BSD scheduler and replace it with ULE. In the stock kernel configuration file this should be around line 30 (at the time of this writing).

options     SCHED_4BSD  # 4BSD scheduler
# BECOMES #
options SCHED_ULE # ULE scheduler

Now build your new kernel and reboot so it takes effect. FreeBSD has an elegant, simple build system using the standard “make” utility. Simply change directories to the source tree and invoke the make file with the “buildkernel” and “installkernel” targets. If you call them without any parameters, the GENERIC (default) kernel will be built and installed. Since you want your custom kernel, pass in the KERNCONF flag with the name of the target kernel. In this case, it will be the name that you just copied the generic kernel to: CUSTOM.

cd /usr/src
make buildkernel KERNCONF="CUSTOM"
make installkernel KERNCONF="CUSTOM"



reboot

Congratulations! As the system boots up, it will run the new custom kernel with the ULE scheduler enabled. You have now verified that you are able to compile and install a kernel, so it’s time to take on your next task: writing a simple kernel module.

When running FreeBSD in VMWare make sure to lower the kernels timer frequency

Note: If you are running FreeBSD in VMWare there is one very important performance tweak to make to your system to follow this article. The kernel’s timer frequency needs to be lowered from ‘1000’ to ‘100’ ticks per second. Edit /boot/loader.conf with your favorite editor and add the following line.

echo kern.hz=100 >> /boot/loader.conf

Kernel Hello World

As you may have noticed, FreeBSD makes efficient use of the make utility for building and installing kernels (and the rest of the operating system). What you may not know yet, but will come as no surprise, is that the FreeBSD developers have also developed make files to ease part of the difficulty of kernel module development.


An in depth look at make files and the make utility are beyond the scope of this article. However, two points of immediate relevance are the bsd.kmod.mk make file and the ability to include other make files within each other.

The bsd.kmod.mk makefile resides in /usr/src/share/mk/bsd.kmod.mk and takes all of the pain out of building and linking kernel modules properly. As you are about to see, you simply have to set two variables:

  • the name of the kernel module itself via the “KMOD” variable;
  • the source files configured via the intuitive “SRCS” variable;

Then, all you have to do is include to build the module. This elegant setup lets you build your kernel module with only the following skeletal make file and a simple invocation of the “make” utility.

The Makefile for our introductory kernel module looks like this:

# Note: It is important to make sure you include the  makefile after declaring the KMOD and SRCS variables.

# Declare Name of kernel module
KMOD = hello_fsm

# Enumerate Source files for kernel module
SRCS = hello_fsm.c

# Include kernel module makefile
.include

Create a new directory called kernel, under your home directory. Copy and paste the text above into a file called Makefile. This will be your working base going forward.

Creating a module

Now that you have a clue about the build environment, it’s time to take a look at the actual code behind a FreeBSD kernel module and the mechanisms for inserting and removing a module from a running kernel.

A kernel module allows dynamic functionality to be added to a running kernel. When a kernel module is inserted, the “load” event is fired. When a kernel module is removed, the “unload” event is fired. The kernel module is responsible for implementing an event handler that handles these cases.

The running kernel will pass in the event in the form of a symbolic constant defined in the /usr/include/sys/module.h () header file. The two main events you are concerned with are MOD_LOAD and MOD_UNLOAD.

How does the running kernel know which function to call and pass an event type as a parameter to? The module is responsible for configuring that call-back as well by using the DECLARE_MODULE macro.

The DECLARE_MODULE macro is defined in the header on line 117. It takes four parameters in the following order:

  1. name. Defines the name.

  2. data. Specifies the name of the moduledata_t structure, which I’ve named hello_conf in my implementation. The moduledata_t type is defined at line 55 of . I’ll talk about this briefly.

  3. sub. Sets the subsystem interface, which defines the module type.

  4. order. Defines the modules initialization order within the defined subsystem

The moduledata structure contains the name defined as a char variable and the event handler routine defined as a modeventhand_t structure which is defined at line 50 of . Finally, the moduledata structure has void pointer for any extra data, which you won’t be using.

If your head is about to explode from the overview without any code to put in context, fear not. That is the sum of what you need to know to start writing your kernel module, and so with that, “once more into the breach dear friends”. Before you get started, make sure you are in the same kernel directory where you previously created the Makefile file. Fire up your text editor of choice and open a file called hello_fsm.c.

First include the header files required for the data types used. You’ve already seen and the other includes are supporting header files.

#include 
#include
#include
#include

Next, you are going to implement the event_handler function. This is what the kernel will call and pass either MOD_LOAD or MOD_UNLOAD to via the event parameter. If everything runs normally, it will return a value of 0 upon normal completion. However, you should handle the possibility that something will go wrong and if the event parameter is neither MOD_LOAD or MOD_UNLOAD, you will set e, your error tracking variable, to EOPNOTSUPP.

/* The function called at load/unload. */
static int event_handler(struct module *module, int event, void *arg) {
int e = 0; /* Error, 0 for normal return status */
switch (event) {
case MOD_LOAD:
uprintf("Hello Free Software Magazine Readers! \n");
break;
case MOD_UNLOAD:
uprintf("Bye Bye FSM reader, be sure to check http://freesoftwaremagazine.com !\n");
break;
default:
e = EOPNOTSUPP; /* Error, Operation Not Supported */
break;
}

return(e);
}

Next, you’re going to define the second parameter to the DECLARE_MODULE macro, which is of type moduledata_t. This is where you set the name of the module and expose the event_handler routine to be called when loaded and unloaded from the kernel.

/* The second argument of DECLARE_MODULE. */
static moduledata_t hello_conf = {
"hello_fsm", /* module name */
event_handler, /* event handler */
NULL /* extra data */
};

And finally, you’re going to make a call to the much talked about DECLARE_MODULE with the name of the module and the hello_conf structure.

DECLARE_MODULE(hello_fsm, hello_conf, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);

All that is left to do is build the module. Double check that you are in the same directory as the module’s makefile you saw earlier and run:

make

Loading and unloading the module

To load the module, you have two options: the kldload utility or the load make target via the makefile. You must use both options via the “sudo” utility as loading and unloading modules requires root privileges.

sudo kldload ./hello_fsm.ko
# or #
sudo make load

You should see the message “Hello Free Software Magazine Readers!” on your console. To view all loaded modules, use the kldstat utility with no arguments. kldstat does not require root privileges and you can verify that the module is indeed loaded.

 kldstat
Id Refs Address Size Name
1 8 0xc0400000 926ed4 kernel
2 1 0xc0d27000 6a1c4 acpi.ko
3 1 0xc317e000 22000 linux.ko
4 1 0xc4146000 2000 hello_fsm.ko

To unload the module, use kldunload or the unload target in the make file. You should see the message printed on the MOD_UNLOAD case, which is “Bye Bye FSM reader, be sure to check http://freesoftwaremagazine.com!”

sudo kldunload hello_fsm
or

sudo make unload

Conclusion

There you have it, a basic, skeletal kernel module. It prints a message when loaded and a separate message when being unloaded from the kernel. This article covered the mechanics of building, inserting, and removing the module. You know have the basic building blocks to take on more advanced projects: I would recommend looking at writing a character device writer as it is probably the next simplest device driver.

I hope this has been as much fun for you as it has been for me!

Resources

Books:

  • The Design and Implementation of the FreeBSD Operating System, by Marshall Kirk McKusick and George V. Neville-Neil

  • Designing BSD Rootkits, an Introduction to Kernel Hacking, by Joseph Kong

viernes, 1 de agosto de 2008

PHP 5.3 Alpha 1

PHP anunció la disponibilidad del release Alpha 1 de PHP 5.3.

Se trata del primer bosquejo de pruebas de lo que será la versión 5.3 de PHP, que si han seguido más o menos los distintos posts que al respecto se hicieron en distintos espacios de la red, es la que incluirá la mayoría de los nuevos features copados en los que viene trabajando el equipo de desarrollo últimamente. Podríamos decir que es PHP 6 sin el soporte para Unicode.

Entre los cambios más importantes se destacan:

martes, 22 de julio de 2008

Coloreando código para blogger o cualquier web

Wordpress tiene una herramienta para colorear código automaticamente, pero para los usuarios de blogger se nos hace algo fastidioso, asi que, que mejor que una herramienta on-line para hacerlo. Soportando muchos leguajes: ActionScript, Ada, Apache, Asm, Asp, Bash, C, C_Mac, Caddcl, cadlisp, Cpp, C# (C Sharp), CSS, D, Delphi, Diff, Div, Eiffiel, Gml, html 4 strict, Java, JavaScript, Lisp, Lua, Matlab, Mpasm, Nsis, Objp, Oobas, Oracle 8, Pascal, Perl, Php, php-brief, Python, Qbasic, Smarty, Sql, Visual Basic, Visual Basic.NET, Vhdl, Visual Fox Pro y Xml.


Aca un ejemplo: El código antes publicado para mostrar una imagen con letras:


  1. /*

  2. Code by Jonathan Ariel Muszkat

  3. muskys@gmail.com

  4. */
  5. // Obtenemos la imagen
  6. $im = imagecreatefromjpeg("imagen2.jpg");
  7. $frase = array('M','E','L','U',' ','Y',' ','J','O','N','Y',' ');
  8. // Iteramos entre las coordenadas X y Y
  9. $j = 0;
  10. $mostrar = "";
  11. for($y=0;$y
  12. for($x=0;$x
  13. // Obtenemos el valor del color
  14. $rgb = imagecolorat($im,$x,$y);
  15. // Convertimos a Hexadecimal
  16. $hex = sprintf("%06X", $rgb);
  17. // Imprimimos la letra con su color
  18. $mostrar .= "".$frase[$j]."";
  19. $j++;
  20. if($j == 12){
  21. $j = 0;
  22. }
  23. }
  24. $mostrar .= "
  25. ";
  26. }
  27. $mostrar .= '';
  28. imagedestroy($im);
  29. die($mostrar);
  30. ?>


Obviamente se puede usar en cualquier web, no solo blogger.

El recurso on-line se puede encontrar aqui: http://www.scourdesign.com/articulos/tutoriales/colorear/

jueves, 17 de julio de 2008

AL FIN UNA BUENA NOTICIA!

de Ajaxian » Front Page de Dion Almaer

Ah the age old IEPNGFix solution to the problem that we had with IE 5.5 / 6.0 not supporting alpha transparency. The first IEPNGFix solved the problem:

This script adds near-native PNG support with alpha opacity to IE 5.5 and 6. Now you can have full translucency and no more ugly grey borders! It requires only one line in your CSS file, and no changes to your website HTML. tags and background images are both supported.

Now we have a new version that adds the ability to use CSS1 compatible background position and repeat.

Pasar imagen a Texto (muy divertido)


/*
Code by Jonathan Ariel Muszkat
muskys@gmail.com
*/
// Obtenemos la imagen
$im = imagecreatefromjpeg("imagen2.jpg");
$frase = array('M','E','L','U',' ','Y',' ','J','O','N','Y',' ');
// Iteramos entre las coordenadas X y Y
$j = 0;
$mostrar = "";
for($y=0;$y for($x=0;$x // Obtenemos el valor del color
$rgb = imagecolorat($im,$x,$y);
// Convertimos a Hexadecimal
$hex = sprintf("%06X", $rgb);
// Imprimimos la letra con su color
$mostrar .= "".$frase[$j]."";
$j++;
if($j == 12){
$j = 0;
}
}
$mostrar .= "
";
}
$mostrar .= '';
imagedestroy($im);
die($mostrar);
?>




Version JPG





/*
Code by Jonathan Ariel Muszkat
muskys@gmail.com
*/
function genera_imagen() {
header("Content-type: image/jpg");
if (file_exists("generada3.jpg")) {
$img = file_get_contents ("generada3.jpg");
$im = imagecreatefromstring ($img);
header('Cache-Control: max-age=864000');
header("Expires: Mon, 26 Jul 2038 05:00:00 GMT");
header("Pragma: ");
header ("Content-Type: image/jpeg");
imagejpeg($im);
imagedestroy($im);
exit;
}

$im = imagecreatefromjpeg("test.jpg");
list ($realWid, $realHei) = getimagesize("test.jpg");
$im2 = imagecreatetruecolor($realWid, $realHei);
imagefill($im2, 0, 0, 0);
$frase = array('M','E','L','U',' ','T','E',' ','A','M','O',' ', 'J', 'O','N','Y');
$font = 'COUR.TTF';
$fontsize = 11;
$j = 0;

for($y=0;$y for($x=0;$x
// Obtenemos el valor del color
$rgb = imagecolorat($im,$x,$y);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$posy = $y + $fontsize;
imagettftext ($im2, $fontsize, 0, $x, $posy, $rgb, $font, $frase[$j]);
$j++;
if($j == count($frase)){
$j = 0;
}
}
}
//$blanco = imagecolorallocate($im2, 255, 255, 255);
//imagettftext ($im2, 20, 0, 0, 20, $blanco, $font, 'Code by Musky'); //Si le queremos poner un copyright
imagejpeg($im2, "generada3.jpg");
imagedestroy($im2);
imagedestroy($im);

}
genera_imagen();/*

Code by Jonathan Ariel Muszkat
muskys@gmail.com
*/


?>

martes, 15 de julio de 2008

Configuración de ISP

Leyendo Linuxeando, me entero en este post que How To Forge sacó una serie de guías para la configuración de un ISP (un servidor completo que ofrezca todos los servicios necesarios para un ISP y alojamiento web: servidor web Apache (con SSL), servidor de correo Postfix con SMTP-AUTH y TLS, servidor DNS con BIND, servidor FTP con Proftpd, servidor MySQL, Dovecot POP3/IMAP, Quota, Firewall, etc.).

Sacaron versiones para distintas distribuciones. Yo estoy esperando la de Slackware.
También hace un tiempo salió un documento de Implementación de servidores con GNU/Linux por Joel Barrios Dueñas.

Con respecto a otros sistemas operativos Unix, también está disponible esta guía para instalar un ISP en FreeBSD, pero por lo que estuve hablando con Cesar a esta guía le faltarían algunas cositas. Estaría bueno que Cesar publique su versión más completa y en castellano.

De más está decir que no pongo las manos en el fuego por NINGUNA de las guías nombradas, sino que esto es meramente para compartir información.

lunes, 14 de julio de 2008

SMF en Solaris

Estuve investigando un poco sobre SMF en Solaris y está bastante interesante, así que comparto lo que aprendí.

Solaris 10 incorpora SMF: Service Management Facility, que básicamente es un daemon que controla los servicios que corren en el sistema operativo. Su idea es reemplazar los scripts de /etc/init.d y /etc/rc.*.d, con una utilidad bastante más robusta y simple de configurar.

A partir de Solaris 10, entonces, vemos que muchos servicios que antes estaban en /etc/init.d ahora desaparecieron de allí y si revisamos el /etc/inittab vemos que una de las primeras cosas que hace es levantar el svc.startd que es el daemon que maneja los servicios de SMF. De hecho, dicen que ahora el boot es bastante más limpito, porque todos los mensajes de los servicios que se inician se van logueando en distintos lugares, y uno termina viendo algo así:

SunOS Release 5.10 Version Generic 64-bit
   Copyright 1983-2004 Sun Microsystems, Inc.  All rights reserved.
   Use is subject to license terms.
   Hostname: demobox
   NIS domain name is testlab.example.com
   checking ufs filesystems

   demobox console login:


En este link hay una Quickstart Guide muy interesante, donde muestra cómo se hacían las cosas en las versiones anteriores de Solaris y cómo deberían hacerse ahora con SMF: http://www.sun.com/bigadmin/content/selfheal/smf-quickstart.jsp

Subir y bajar el apache es tan sencillo como ejecutar los siguientes comandos:

Levantar:     svcadm enable network/http:apache2
Bajar:           svcadm disable network/http:apache2
Reiniciar:     svcadm restart network/http:apache2

Como podrán observar, los servicios se agrupan en unidades más "user-friendly" (o admin-friendly), en vez de ser archivos tirados en directorios (de hecho en Solaris siempre era más molesto que en Linux, porque el archivo debía estar indefectiblemente en /etc/init.d y con hard links en /etc/rc3.d - para el caso de servicios que levantaran en runlevel 3). Además se pueden configurar facilmente variables de entorno y otras cosas locas que se deben inicializar con el servicio.

Por otro lado, al haber un daemon constantemente corriendo, si el servicio no es deshabilitado por un "restarter" habilitado, el servicio se levanta automáticamente:

[root@BOCUNOCDWB04:~]# svcadm enable network/http:apache2
[root@BOCUNOCDWB04:~]# ps -ef |grep httpd
   root 23319     1   3 13:38:59 ?           0:01 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23328 23319   0 13:39:02 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
   root 23330 22786   0 13:39:04 pts/2       0:00 grep httpd
 nobody 23327 23319   0 13:39:02 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
   root 23322     1   0 13:39:01 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23326 23319   0 13:39:02 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23325 23319   0 13:39:02 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23324 23319   0 13:39:02 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
[root@BOCUNOCDWB04:~]# pkill httpd
[root@BOCUNOCDWB04:~]# ps -ef |grep httpd
   root 23357     1   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23360 23351   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
   root 23365 22786   0 13:39:22 pts/2       0:00 grep httpd
   root 23351     1   2 13:39:20 ?           0:01 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23359 23351   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23361 23351   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23362 23351   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
 nobody 23363 23351   0 13:39:22 ?           0:00 /usr/local/apache2/bin/httpd -k start -DSSL
[root@BOCUNOCDWB04:~]#

De la misma forma, si hay algún error al levantar el programa o el mismo se muere dejando algún error, el servicio es puesto en estado "maintenance", para poder consultar posteriormente por qué no está corriendo.

[root@BOCUNOCDWB04:~]# svcs -xv network/http:apache2
svc:/network/http:apache2 (Apache 2 HTTP server)
State: maintenance since Mon 14 Jul 2008 01:37:39 PM COT
Reason: Start method failed repeatedly, last exited with status 1.
  See: http://sun.com/msg/SMF-8000-KS
  See: man -M /usr/apache2/man -s 8 httpd
  See: /var/svc/log/network-http:apache2.log
Impact: This service is not running.
[root@BOCUNOCDWB04:~]#

Para configurar los servicios hay una consola a la que podemos acceder con svccfg.

[root@BOCUNOCDWB04:~]# svccfg
svc:> select network/http
svc:/network/http> select apache2
svc:/network/http:apache2> listprop
httpd                              application
httpd/stability                    astring  Evolving
httpd/ssl                          boolean  true
network                            dependency
network/entities                   fmri     svc:/milestone/network:default
network/grouping                   astring  require_all
network/restart_on                 astring  error
network/type                       astring  service
filesystem-local                   dependency
filesystem-local/entities          fmri     svc:/system/filesystem/local:default
filesystem-local/grouping          astring  require_all
filesystem-local/restart_on        astring  none
filesystem-local/type              astring  service
autofs                             dependency
autofs/entities                    fmri     svc:/system/filesystem/autofs:default
autofs/grouping                    astring  optional_all
autofs/restart_on                  astring  error
autofs/type                        astring  service
startd                             framework
startd/ignore_error                astring  core,signal
general                            framework
general/enabled                    boolean  true
start                              method
start/exec                         astring  "/lib/svc/method/http-apache2 start"
start/timeout_seconds              count    60
start/type                         astring  method
stop                               method
stop/exec                          astring  "/lib/svc/method/http-apache2 stop"
stop/timeout_seconds               count    60
stop/type                          astring  method
refresh                            method
refresh/exec                       astring  "/lib/svc/method/http-apache2 refresh"
refresh/timeout_seconds            count    60
refresh/type                       astring  method
restarter                          framework    NONPERSISTENT
restarter/transient_contract       count  restarter/logfile                  astring  /var/svc/log/network-http:apache2.log
restarter/contract                 count    299148
restarter/start_pid                count    23339
restarter/start_method_timestamp   time     1216060760.150109000
restarter/start_method_waitstatus  integer  0
restarter/auxiliary_state          astring  none
restarter/next_state               astring  none
restarter/state                    astring  online
restarter/state_timestamp          time     1216060760.155996000
restarter_actions                  framework    NONPERSISTENT
restarter_actions/restart          integer
restarter_actions/maint_off        integer
svc:/network/http:apache2>

La forma en que el daemon manejará los servicios se define en un script que tiene "métodos", que serán invocados por el daemon. Estos scripts están en /lib/svc/methods, y el daemon los llama por ejemplo de esta forma:

/lib/svc/methods/http-apache2 start

Adentro el método consulta algunas variables del servicio y lo levanta. El script es muy similar a los de /etc/init.d.

Con svcs se listan los servicios.
Con svcs -l se puede ver el estado actual de un determinado servicio. Además podes se puede ver el proceso principal y sus hijos:

 % svcs -p network/smtp:sendmail
    STATE          STIME    FMRI
    online         18:20:30 svc:/network/smtp:sendmail
     18:20:30      655 sendmail
     18:20:30      657 sendmail

Y con svcs -x se puede ver por qué un determinado servicio falló.

Tiene muchas más cosas locas. Yo creo que debe tener alguna forma de controlar servicios remotos, porque cada servicio tiene una URI que llaman FMRI (Fault Managed Resource Identifier), que puede ser algo así:

  • svc://localhost/system/system-log:default
  • svc:/system/system-log:default
  • system/system-log:default
Y en la primera opción justamente se define una location que en ese caso es localhost, pero supongo que uno podría poner una IP.

También hay otras cosas locas para el manejo de los runlevels del SO. Podés definir milestones que, si no entendí mal, serían como runlevels custom para los cuales vos podés definir qué servicios corren.

Más información sobre SMF en el System Administration Guide de Solaris: http://docs.sun.com/app/docs/doc/817-1985

Particularmente en estos dos capítulos:
http://docs.sun.com/app/docs/doc/817-1985/hbrunlevels-25516?a=view
http://docs.sun.com/app/docs/doc/817-1985/faauf?a=view

16/07/2008: Editado: Dejo un cheat-sheet de  SMF: http://www2.petervg.nl/quick_reference/SolarisSMF.pdf