03 mayo, 2023

Pseudocode for an Ethernet switch

How does an Ethernet switch work? I'll explain it as far as I can understand, using the clearest way I can imagine (code). Hopefully I got it right.


Prerrequisites

The switch has a number of interfaces or ports. There are cables connected to some of them, that come from computers or other switches or network equipment.

The switch receives and sends ethernet packets (or frames) through its ports.

Each packets typically includes a couple mac addresses. A mac address is a 12 digit hexadecimal number (6 bytes) that is used to identify the sender or recipient of a packet. There several kind:

  • Unicast: Every network card has a unique own address. Eg: a laptop could have 2 of them (one for LAN card, another for Wi-Fi). The 8th bit of this type is always 0.
  • Non-Unicast: 
    • Broadcast: The mac ff:ff:ff:ff:ff:ff. Used to send packets to all the hosts in a LAN.
    • Multicast: All macs that have 8th bit set to 1, but are not the broadcast mac. Used for multicast communication.

 Every packet has these fields.

  • Destination Mac Address: Identifies the recipient of the packet. It may be a host or a router, but it could also be multicast or broadcast.
  • Source Mac Address: Identifies who sent the packet. Typically a host/router in the LAN.
  • Ethernetype: Identifies the type of packet. Eg: An IP packet.
  • Payload: Other headers (like TCP) and finally data.

The switch has an internal "bridge table" or "mac table". Which is used to tell on which interface is every mac address that it knows. It's fields are:

  • Mac address
  • Interface
  • Timeout (after not seeing a packet with that mac address the entry is removed to save resources).

Pseudocode

# Start

p, i := Wait_for_packet()
; p is the packet
; i is the ingress interface

; get source and destination macs
d := parse_destination_mac(p)
s := parse_source_mac(p)


; Handle lookup table for source mac
ci := get_interface_from_lookup_table(s)
if ci is null
  add_to_lookup_table(s, i)
  ; adds the entry and sets up the timer
elif ci == i
  refresh_lookup_table(s, ci)
else
  ; shouldn't happen unless a host changed interface
  delete_lookup_entry(s, ci)
  add_to_lookup_table(s, i)
endif
  

; Analyze recipient and finally send packet
if mac_type(d) == unicast
   co := get_interface_from_lookup_table(d)
   if co is null
      ; when destination is not cached we flood
      send_packet_to_all_interfaces_except(p, i)
   else
      send_packet_to_interface(p, i)
   endif
else
   send_packet_to_all_interfaces_except(p, i)
endif

goto start

Note: This example is suposed to model a basic switch and does not cover advanced functionality like: VLAN, multicast groups, spanning tree.

22 diciembre, 2022

SOCAT cheat sheet

Remember that socat usually has 2 legs. Both are connected bidirectionally.

 
Listen/Passive Connect/Active
TCPv4 TCP4-LISTEN:8800,reuseaddr,fork TCP4:192.168.1.5:8000
OpenSSL OPENSSL-LISTEN:443,reuseaddr,pf=ip4,fork,cert=server.pem,cafile=client.crt,verify=0 OPENSSL:192.168.1.5:4443,pf=ip4,cert=server.pem,cafile=client.crt,verify=0,no-sni=0
Unix Socket UNIX-LISTEN:mysqld.sock,mode=777,reuseaddr,fork UNIX-CONNECT:mysqld.sock.orig
SOCKSv4 SOCKS4:socks-server.local:10.1.2.3:22,socksport=1080

(First IP is socks server, Second IP is destination server).
HTTP Proxy PROXY:aproxy.local:example.com:80,proxyport=8080
STDIO - / STDIN - / STDOUT / STDERR
Misc EXEC:/bin/bash

FILE:/dev/null

03 marzo, 2019

Navigate Google Earth like a Pro

Here I made a quick cheat sheet for Google Earth Navigation



Note that vertical movement is not possible afaik. The way I suggest is an approximation.

I'm, leaving the link to a doc with the same content HERE.

04 agosto, 2017

[Idea] ThunderMonkey: GreaseMonkey for Thunderbird

I thought it would be nice to have an extension like Greasemonkey for Thunderbird.
That is: allow to write and share little javascript snippets that make certain changes in the appearance of incoming email.

You can already do that using proper extensions, but it is a little overkill, especially for beginners. So for the same reason that user scripts are popular despite having proper browser extensions.

I'm preparing a mockup of the interface. It could be similar to Greasemonkey, have a script manager, and an embedded editor.

The script manager:


The script editor window:

The main difference with Greasemonkey is that now we cannot match against an URL, but instead we have to match against email headers.

The scripts should also be able somehow to access all mail headers and body to do additional filtering.

Btw, I'm already used to writing user scripts, but not extensions.
Any thoughts or help is welcome :)

12 agosto, 2012

Upgrade Parrot CK3000 Evolution with a Max232 chip

In order to make the CK3000 work well with Android phones you will need to upgrade it to version 5.25c. You could do get this done by a professional, or you could buy a rather expensive official cable. I'm making the cable myself with the help of other people who made a similar one first.

First of all read the original post http://peter.holcroft.net/ck3000/

This is a simple application of the Max232 chip i have:


I used the original data and power connectors for the upgrade. The data connector has a kind of appendix to which i connected the data wires (not very professional).

I also connected the required wire between pin 9 & 10 (not showing in this pic):

The actual setup on the protoboard.
I used a standard 5V AC/DC adapter.
The capacitors are 1uF 50V (10 cents each):

And now the software process. I used a laptop and a USB-to-serial adapter.

I started using an inverter (DC-to-AC adapter) and it faild almost always. Later i switched to a wall socket and it went better.


* Update process and symptoms:
- Select CK3000 Evolution.
- Select Serial update.
- Select 115200 baud.
- Wait for "XPRAM downloading". Progress bar should not move yet.
   - If progress bar moves there may be something wrong.
   - If it says something like "Cannot set baud rate" probably the wire between pin 9&10 is not ok.
   - If it says something like "Cannot open port" disconnect the usb device, click back and next.
- Power on the parrot. After 1 to 5 seconds progress bar will start moving. It will take about 10 seconds to finish.
   - If you get an error like "Cannot send data" there may be a bad cable.
   - If the bar loops over and over something is wrong. Better try again.
The rest of the process is relatively fast except the "Flash programming" which takes more than one minute.
It can randomly stall or throw the "Cannot send data" error at any time. If it happens try again.
* Myths:
- "If you put two CK3000 close to each other they update the firmware automatically". It didn't happen to me.
- "You can do a wireless update with a bluetooth virtual serial port". I wasn't able to create a serial bluetooth connection. Parrot officially only supports cabled upgrades for the CK3000.

26 julio, 2011

The CRC32 of this string is 4A1C449B

Pues si, estaba aburrido y se me ocurrió si sería posible insertar el hash de un texto dentro del propio texto.

Viabilidad
Como no estaba muy seguro primero analicé la viabilidad. Si asumimos un formato de texto fijo, en el que sólo varía la parte del hash, la probabilidad no es baja.

Para un hash n bits, la probabilidad de acertar a la primera es:
1/(2^n)

Por tanto, la probabilidad que exista un resultado válido en todo el espacio es:


Por tanto es probable encontrar algún hash con estas características, y si no apareciera probaríamos con otra cadena base distinta.

Optimización
Lo siguiente que hice fue tomar un código de ejemplo de código de CRC32 basado en tabla de 8 bits, y precomputar una tabla de 24 bits (que debe ocupar unos 96MB en memoria).
Este código es capaz de calcular las 2^32 posibilidades en unos pocos minutos.

Habría estado bien hacer algún análisis que permitiera alguna optimización específica para este problema, pero no llego hasta ahí.

Resultado
Tras 2 minutos obtenemos:
"The CRC32 of this string is 4A1C449B"

Y poco más que decir, se puede verificar (es importante no añadir saltos de línea ni espacios al final) aquí:

Con un poco más de trabajo podemos obtener:
"I killed 56e9dee4 cows and all I got was..."

25 junio, 2010

No ajustes tu televisor, pero esto NO es 3D

«No ajustes tu televisor, no intentes activar el 3D, porque esto no es 3D»

El efecto que se ve en el anuncio consigue su objetivo, pero realmente no es 3D. Si fuera 3D habría un desfase horizontal en algunas de las imágenes, pero en ningún caso lo habría en vertical como se aprecia a lo largo de todo el anuncio.


03 abril, 2010

Multicargador para moviles (Mobile multicharger)

Uno de los últimos cacharros que me he comprado es un aparato muy versátil, un multicargador para teléfonos móviles.

Algunas de las cosas que permite hacer son:

  • Cargar pilas alimentandose desde el PC, y posteriormente cargar el movil con ellas.
  • Cargar el movil con el sol.
  • Comprar pilas alcalinas y cargar el movil con ellas.
Las posibilidades son muchas, basta mirar el esquema:
Y lo mejor de todo es que hay aparatos de estos desde 15€.

No es un gadget para llevar en el bolsillo, pero sí para ir de campo (si es que no queremos desconectarnos).

12 enero, 2010

La pila 802.11 para el sistema operativo

Como estaba aburrido he decidido hacer un diagrama de la pila IEEE802.11 desde el punto de vista del sistema operativo (Linux).


Notas:
  • En el caso de las tarjetas de tipo Software MAC, el driver se apoya en el la pila mac80211 del kernel para la conversión a 802.3 (ethernet) y las tramas de gestión.
  • El modo monitor o rfmon no es lo mismo que el modo promiscuo, si entendemos por modo promiscuo la recepción (e inyección) de tramas a nivel 802.3. El modo monitor exige recibir (e inyectar) tramas completas con la cabecera original 802.11 (y opcionalmente otras cabeceras auxiliares como radiotap o prism).

11 agosto, 2009

SlideType Keyboard: deslizar para escribir en Android

Los teclados virtuales en pantalla de los teléfonos tienen varios problemas:

  • Los teclados QWERTY tienen las teclas muy pequeñas.
  • Otros teclados requieren pulsar las teclas varias veces o dependen de diccionarios, que no van bien.
Una solución (sin entrar en temas de multitouch o Chord Typing) es requerir algo más que pulsar las teclas, en este caso deslizar en una dirección (arriba, izquierda, etc).

Por ejemplo, si apretamos el dedo sobre la tecla etiquetada "2ABC", lo movemos a la izquierda y lo soltamos escribiremos la letra A. Si hubieramos movido hacia arriba hubiera sido la letra B, y a la derecha la C.


Demo en Javascript: http://www.latinsud.com/pub/slideType/



Download con QR-Code:

Visita el blog de SlideType Keyboard (inglés):