Full text
Neighbor Discovery Proxy-Gateway for 6LoWPAN-based Wireless Sensor Networks Proyecto Fin de Carrera Ingeniería Informática Luis Maqueda Ara [email protected] Febrero 2012 Director: Gerald Q. “Chip” Maguire Jr. School of Information and Communication Technology Royal Institute of Technology (KTH) Estocolmo, Suecia Ponente: Eduardo Mena Dpto. de Informática e Ingeniería de Sistemas Escuela de Ingeniería y Arquitectura (EINA) Universidad de Zaragoza
Resumen El propósito de este trabajo es el estudio de métodos para la interconexión de redes personales inalámbricas de área local de bajo consumo (Low-power Personal Area Networks, LoWPANs) y redes de computadores tradicionales. En particular, este proyecto analiza los protocolos de red involucrados así como las posibles formas de interoperabilidad entre ellos, teniendo como meta la integración de redes inalámbricas de sensores IEEE 802.15.4 basadas en 6LoWPAN (una capa de adaptación que hace posible el transporte de paquetes IPv6 sobre IEEE 802.15.4) en redes Ethernet ya existentes, sin necesidad de cambios en la infraestructura de red. Dicha integración permitiría el desarrollo y expansión de aplicaciones de usuario utilizando la tradicional pila de protocolos TCP/IP en sistemas compuestos por dispositivos empotrados de bajo coste y bajo consumo. Además, dado que el método aquí presentado no requiere introducir cambios en la infraestructura existente, no se deriva ningún coste de la integración en sí (salvo por el coste del dispositivo a cargo de la interconexión de las redes), lo que implica que esta integración se pueda llevar a cabo de manera eficiente y a un coste reducido respecto a otras alternativas. Tras el estudio inicial, se diseña, implementa y evalúa un prototipo basado en un sistema empotrado que lleva a cabo las tareas necesarias para la integración descrita en el párrafo anterior, cumpliendo con los objetivos propuestos de manera eficiente y transparente para todas las partes implicadas. Este documento es un resumen en castellano de la memoria que lleva el mismo título y que fue realizada en el marco de un programa de intercambio como proyecto de fin de máster en The Royal Institute of Technology (KTH), Estocolmo. Dicha memoria se encuentra en el Apéndice A de este documento con el fin de proporcionar una aproximación más detallada en los aspectos clave que se hallan recogidos en este resumen. Algunos de los protocolos involucrados en este trabajo se hallan todavía en fase de desarrollo o han sido recientemente aceptados como estándares (aunque aún no han sido plenamente adoptados por parte de la industria). Debido a esto y al carácter innovador de las técnicas presentadas en este proyecto, un Internet-Draft describiéndolas fue presentado en la reunión número 80 del Internet Engineering Task Force (IETF): Guidelines for the Operation of a 6LoWPAN-ND Proxy Gateway (draft-maqueda-6lowpan-pgw) [20]. En el Apéndice B se encuentra una copia de dicho Internet-Draft. i
Agradecimientos Gracias en primer lugar a mi supervisor Gerald Q. “Chip” Maguire Jr., no solo por haberme guiado en el desarrollo de este proyecto, sino también por haberme animado a adentrarme en un campo nuevo y fascinante de la ingeniería. Gracias a todos aquellos profesores que por su motivación y compromiso han hecho de aprender un placer, entre ellos mi ponente Eduardo Mena Nieto, por su solicitud, diligencia y meticulosidad al resolver mis dudas y revisar mi trabajo en la distancia. Por otro lado, quisiera expresar mi agradecimiento a las personas que he conocido durante mi estancia en Estocolmo, donde ha sido realizado este proyecto, por haberme apoyado y animado en todo momento, hasta el punto de convertirse en mi familia lejos de casa. También quisiera dar las gracias a todos los compañeros y amigos con los que he coincidido durante mis estudios en Zaragoza y que han estado a mi lado durante todos estos años en las clases, las prácticas de laboratorio, o las sesiones de estudio en la biblioteca. Entre estos últimos, no puedo pasar por alto hacer una mención especial a Pablo Castillo, un amigo excelente y mejor persona, que siempre estará en mi memoria. Además de a mis compañeros, he de dar las gracias también a mis amigos de toda la vida, por su disponibilidad tanto en los buenos como en los malos momentos. Por último, pero no menos importante, doy las gracias a mi familia, tanto por su incondicional apoyo y afecto, como por haber contribuido a dar forma a la persona que soy hoy en día. iii
Índice general Índice general v Índice de figuras vii 1 Introducción 1 1.1 Motivación ............................. 1 1.2 Descripción del entorno de aplicación ............... 2 1.3 Objetivos .............................. 2 1.4 Ámbito tecnológico del proyecto .................. 3 1.5 Estructura de esta memoria .................... 3 2 Tecnología utilizada 5 2.1 Ethernet ............................... 6 2.2 IEEE 802.15.4 ............................ 6 2.3 Capa de adaptación 6LoWPAN .................. 7 2.4 IPv6 ................................. 8 2.5 El protocolo Neighbor Discovery ................. 9 2.5.1 Neighbor Discovery for IP version 6 (IPv6) ....... 9 2.5.2 Neighbor Discovery Optimization for LLNs ....... 10 3 Planteamiento del problema 13 3.1 Capa de enlace ........................... 13 3.2 Pseudo-capa de adaptación .................... 13 3.3 Capa de red ............................. 14 4 Diseño del sistema 15 4.1 Solución alternativa ........................ 15 4.2 Capa de enlace ........................... 17 4.3 Pseudo-capa de adaptación .................... 17 4.4 Capa de red ............................. 18 5 Implementación 21 5.1 Programación de la plataforma hardware ............. 21 v
vi ÍNDICE GENERAL 5.2 Herramientas de desarrollo y depuración ............. 21 5.3 Sistema ............................... 22 5.3.1 Capa de abstracción del hardware ............ 23 5.3.2 Capa de enlace ....................... 24 5.3.3 Pseudo-capa de adaptación ................ 24 5.3.4 Módulo 6LP-GW ...................... 24 6 Evaluación 27 6.1 Métodos de evaluación del sistema ................ 27 6.2 Evaluación de resultados ...................... 28 7 Conclusiones 31 7.1 Metas del proyecto ......................... 31 7.2 Principales problemas encontrados ................ 32 7.3 Cronograma del proyecto ..................... 32 7.4 Trabajo futuro ........................... 33 Bibliografía 37 Apéndice A: KTH Master’s Thesis Report 41 Apéndice B: draft-maqueda-6lowpan-pgw 191
Índice de figuras 2.1 Comparación entre las pilas de protocolos .............. 5 2.2 Estructura de paquete Ethernet .................... 6 2.3 Trama de datos IEEE 802.15.4 .................... 6 2.4 Capa de adaptación 6LoWPAN .................... 7 2.5 Cabecera IPv6 ............................. 9 4.1 6LBR vs. 6LP-GW ........................... 16 4.2 Papel del 6LP-GW en la red ..................... 19 5.1 Estructura del sistema ......................... 23 5.2 Arquitectura del Módulo 6LP-GW .................. 25 6.1 Test de rendimiento IEEE 802.15.4 - Ethernet ............ 28 6.2 Test de rendimiento Ethernet - IEEE 802.15.4 ............ 29 6.3 Comparación de tiempos de procesamiento ............. 30 7.1 Cronograma del proyecto ....................... 33 vii
Capítulo 2 Tecnología utilizada Como ya se mencionó en el capítulo anterior, el escenario de este proyecto se compone de dos segmentos de red. En cada uno de ellos participan diferentes protocolos de red a distintos niveles de la pilas de protocolos TCP/IP. La Figura 2.1 ilustra la posición de la pila TCP/IP que ocupan estos protocolos en cada uno los segmentos de red. Como puede observarse en dicha Figura, la pila situada en el lado izquierdo corresponde al segmento Ethernet, mientras que la situada a la derecha corresponde al segmento IEEE 802.15.4. Nótese que la pila correspondiente al segmento IEEE 802.15.4 tiene una capa más que la del segmento Ethernet: la capa de adaptación 6LoWPAN. Este capítulo describe a grandes rasgos los principales protocolos de red involucrados en este proyecto. En el Capítulo 2, Background, del Apéndice A pueden encontrarse más detalles acerca de estos y otros protocolos de red. IPv6 IPv6 6LoWPAN IEEE 802.15.4Ethenet UDP/TCP UDP/TCP Aplicación Aplicación Aplicación Transporte Internet Adaptación Enlace Segmento Ethernet Segmento IEEE 802.15.4 Figura 2.1: Comparación entre las pilas de protocolos de red 5
6CAPÍTULO 2. TECNOLOGÍA UTILIZADA 2.1 Ethernet Ethernet es un protocolo de comunicación de la capa de enlace para redes de área local. Fue desarrollado originalmente por Xerox, aunque posteriormente se incluyo en el estándar IEEE 802.3 [4]. En particular, IEEE 802.3 define las capas física y de control de acceso al medio (Media Access Control, MAC) de una Ethernet cableada. Dicho protocolo MAC se define originalmente como Acceso Múltiple por Detección de Portadora con Detección de Colisiones (CSMA/CD), aunque en la actualidad las nuevas implementaciones operan en modo full-duplex (lo que hace innecesario el uso de CSMA/CD). La Figura 2.2 ilustra un paquete Ethernet encapsulado en una trama MAC IEEE 802.3.. octets: 6 6 2 46 to 1500 0 to 46 4 ETHERNET data link-layer Destination Address Source Address Length/ Type Data Payload Padding CRC octets: 7 1 . . .. . .Variable MAC packet Preamble SFD MAC Client Data Padding CRC Extension Figura 2.2: El protocolo de enlace Ethernet encapsulado en el campo MAC Client Data de una trama IEEE 802.3 2.2 IEEE 802.15.4 El estándar IEEE 802.15.4 [2] especifica las capas física y de control de acceso al medio (Medium Access Control, MAC) para redes inalámbricas de área personal con tasas bajas de transmisión de datos (Low-Rate Wireless Personal Area Networks, LR-WPANs). Aunque las LR-WPANs entran dentro del ámbito de las redes inalámbricas de área personal, pueden sobrepasar el espacio de operación considerado como personal; una LR-WPANs es una red de comunicación inalámbrica de bajo coste optimizada para su uso en aplicaciones con consumo energético limitado y requerimientos de tasas de transferencia relajados. La Figura 2.3 ilustra el formato de trama de IEEE 802.15.4. octets: 2 1 4 to 20 n2 MAC layer FCF Sequence Number Addressing fields Data Payload FCS octets: 4 1 1 . . .9 to 127 . . . PHY layer Preamble Sequence SFD Frame Length MPDU Figura 2.3: Trama de datos IEEE 802.15.4
2.3. CAPA DE ADAPTACIÓN 6LOWPAN 7 2.3 Capa de adaptación 6LoWPAN 6LoWPAN es una capa intermedia que hace posible el transporte de paquetes IPv6 sobre tramas IEEE 802.15.4. El término 6LoWPAN es un acrónimo derivado de IPv6 over Low-power Wireless Personal Area Networks (IPv6 sobre redes inalámbricas de área personal de bajo consumo). Sin embargo, de manera análoga a las LR-WPANs, su uso con frecuencia va más allá del ámbito personal. El RFC 4919 describe [19] describe una visión general de 6LoWPAN, plantea el problema a tratar y especifica las metas a alcanzar mediante el uso del estándar. El estándar de 6LoWPAN para el transporte de IPv6 sobre redes IEEE 802.15.4 se define en el documento RFC 4944 [22]. La Figura 2.4 muestra de manera esquemática un paquete IPv6 encapsulado en una trama IEEE 802.15.4 mediante el uso de la capa de adaptación 6LoWPAN. IPv6 layer . . .IPv6 packet . . . 6LoWPAN layer . . .6LoWPAN packet . . . MAC layer IEEE 802.15.4 frame Figura 2.4: Capa de adaptación 6LoWPAN Las razones por las que esta capa de adaptación es necesaria son varias. Por un lado, la asignación automática de direcciones IPv6 (Stateless Address Autoconfiguration, definida en el estándar de Internet RFC 4862 [30]) es dependiente la la capa subyacente. En particular, el estándar RFC 4862 especifica que, tanto la longitud exacta, como la manera en la que se genere la parte baja de las direcciones IPv6, denominada identificador de interfaz (Interface Identifier, IID) deben ser especificadas en el documento que defina la transmisión de paquetes IPv6 sobre una capa de enlace determinada. Por tanto, de manera análoga a cómo el documento RFC 2464, Transmission of IPv6 Packets over Ethernet Networks [11] especifica como deben generarse los IIDs cuando la capa de nivel de enlace es Ethernet, el RFC 4944 especifica la formación de IIDs para la capa de enlace IEEE 802.15.4. Por otro lado, los requerimientos que IPv6 impone a los protocolos de la capa de enlace en cuanto al tamaño mínimo de unidad máxima de transferencia (Maximum Transfer Unit, MTU) no son satisfechos por el estándar IEEE 802.15.4. El estándar que define IPv6 (RFC 2460) especifica que una capa de nivel de enlace que transporte IPv6 debe proporcionar un MTU de, como mínimo, 1280 bytes. Esta cifra excede con creces el tamaño máximo de trama de IEEE 802.15.4, el cual es de 127 bytes. De estos 127 bytes, el tamaño
8CAPÍTULO 2. TECNOLOGÍA UTILIZADA máximo que puede ocupar la cabecera IEEE 802.15.4 es de 25 bytes (ver Sección 2.2). Además, si se utilizan los mecanismos opcionales de seguridad que proporciona IEEE 802.15.4, la cabecera puede ocupar 21 bytes adicionales, lo cual deja tan solo 81 bytes disponibles para el transporte de un paquete IPv6. Teniendo en cuenta que la cabecera de un paquete IPv6 tiene una longitud fija de 40 bytes, el tamaño final disponible para la capa de transporte sería de 41 bytes. Por tanto, incluso en el caso en el que obviáramos el no cumplimiento del requerimiento de MTU mínimo, nos hallaríamos en un escenario en el que el protocolo de aplicación podría transportar una cantidad muy pequeña de información y el uso de IPv6 sobre IEEE 802.15.4 sería altamente ineficiente (en tiempo y consumo energético) debido a la sobrecarga producida por la transmisión de cabeceras de las capas inferiores. Para hacer posible el cumplimiento del requerimiento de MTU mínimo, 6LoWPAN proporciona un mecanismo de fragmentación y reensamblaje que permite descomponer los paquetes IPv6 en fragmentos mas pequeños para que puedan ser transportados por la capa de enlace de manera transparente a IPv6. Sin embargo, el proceso de fragmentación y reensamblaje es costoso. Además, se asume generalmente que las aplicaciones a utilizar en entornos 6LoWPAN producirán una cantidad limitada de datos. Por estos motivos y con el fin de limitar el uso de fragmentación en la medida de lo posible, 6LoWPAN define además un mecanismo de compresión y descompresión para paquetes IPv6. Este mecanismo permite comprimir la cabecera IPv6 de 40 a tan solo 2 bytes (en el mejor de los casos), además de especificar también métodos adicionales para la compresión del protocolo de la capa de transporte UDP [25]. Es importante mencionar que, aunque el estándar RFC 4944 define un mecanismo de compresión independiente del contexto, dicho mecanismo ha sido hecho obsoleto por el mecanismo dependiente del contexto especificado por el estándar RFC 6282 [17]. Por otro lado, existen medidas todavía en desarrollo para la compresión genérica de cabeceras de protocolos a ser transportados por IPv6-6LoWPAN, como las definidas en [7]. 2.4 IPv6 El protocolo IPv6 se define en el estándar de Internet RFC 2460 [12]. Fue definido en 1998 como sucesor de IPv4, con el fin de superar una serie de limitaciones que éste planteaba, siendo la principal de estas limitaciones la previsión de que las direcciones IPv4 acabarían por agotarse tarde o temprano. Los principales cambios de IPv6 respecto a su predecesor son un espacio de direcciones mucho mayor, un formato de cabecera más simplificado y de longitud fija (el de IPv4 tiene longitud variable), un mejor soporte para cabeceras de extensión (extension headers) y opciones, permitiendo un direccionamiento más eficiente y mayor flexibilidad para la incorporación de nuevas opciones, capacidad para etiquetado de flujo (flow labelling), que permite solicitar un
2.5. EL PROTOCOLO NEIGHBOR DISCOVERY 9 tratamiento especial por parte de los routers, y capacidades de autenticación y privacidad. La Figura 2.5 ilustra el formato de cabecera de IPv6. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Version Traffic Class Flow Label Payload Length Next Header Hop Limit Source Address Destination Address Figura 2.5: Cabecera IPv6 2.5 El protocolo Neighbor Discovery El protocolo Neighbor Discovery (ND) es un protocolo de nivel de red que emplea mensajes de ICMPv6 (Internet Control Message Protocol for IPv6) [10]. ND es a menudo considerado como parte del protocolo IPv6 (aunque se transporta directamente sobre éste), ya que sus sus principales objetivos son llevar a cabo funciones para la configuración automática y mantenimiento de redes locales que utilizan IPv6. 2.5.1 Neighbor Discovery for IP version 6 (IPv6) El protocolo Neighbor Discovery se define originalmente en el estándar de Internet RFC 4861 Neighbor Discovery for IP version 6 (IPv6) [23]. En lo que resta de esta memoria nos referiremos al protocolo definido por este estándar como IPv6-ND. Las funciones que lleva a cabo este protocolo son: llevar a cabo el descubrimiento de routers, prefijos y parámetros de red, la autoconfiguración de direcciones (a través de los procedimientos especificados en los documentos RFC 4862 [30] y RFC 3315 [14]), resolución de direcciones de la capa de enlace (Address Resoluction), los procedimientos para determinación de siguiente salto (Next-hop Determination), detección de vecinos inaccesibles (Neighbor Unreachability Detection, NUD), detección de direcciones duplicadas (Duplicate Address Detection, DAD) y redirección (Redirect).
10 CAPÍTULO 2. TECNOLOGÍA UTILIZADA 2.5.2 Neighbor Discovery Optimization for Low-power and Lossy Networks IPv6-ND fue diseñado originalmente para redes convencionales IPv6. Este hecho, junto con su fuerte relación con la capa de nivel de enlace, hacen que varias de sus características sean inapropiadas para el uso del protocolo en redes inalámbricas de sensores (Wireless Sensor Networks, WSN) basadas en la capa de enlace IEEE 802.15.4. Las características a las que nos referimos son las siguientes: •Uso abundante de multicast. Esta característica tiene dos inconvenientes en redes 6LoWPAN. La primera es que a nivel de enlace no existe la posibilidad de transmisión multicast con alcance limitado a la red local; toda transmisión multicast es, de hecho, broadcast. La segunda es el elevado consumo energético que acarrea la transmisión de mensajes multicast, tanto en el emisor (en el caso probable de utilizar transmisiones basadas en métodos de duty cycling) como en los receptores (en cualquier caso, ya que todos son obligados a recibir y procesar un mensaje que acabará siendo descartado por la mayoría). •Suposiciones erróneas sobre ciertas propiedades de la capa de enlace. Mientras que en una red Ethernet se asume que todos los nodos están al alcance de todos los nodos durante todo el tiempo, las LoWPANs constituyen generalmente enlaces no transitivos (esto es, en los que no todos los nodos son capaces de comunicarse con todos los demás). Como solución a estos problemas y con intención de dar soporte a ciertas funcionalidades requeridas en redes 6LoWPAN, el grupo de trabajo de 6LoWPAN del IETF ha definido una versión del protocolo Neighbor Discovery optimizada para redes de bajo consumo en las que se asume una tasa de error superior a la habitual en redes convencionales (Low-power and Lossy Networks, LLNs). Esta versión del protocolo Neighbor Discovery (a la que nos referiremos como 6LoWPAN-ND en el resto de esta memoria) se define en el Internet Draft I-D.ietf-6lowpan-nd, cuyo título completo es Neighbor Discovery Optimization for Low Power and Lossy Networks (6LoWPAN) [29]. Los principales objetivos de las diferencias que introduce respecto al protocolo original, IPv6-ND, se pueden agrupar en dos categorías. Por un lado, la optimización del protocolo para dispositivos limitados en cuanto a consumo energético, que a menudo utilizarán capas de enlace no transitivas. Por otro lado, la provisión de soporte para ciertas características requeridas para redes basadas en 6LoWPAN, como es la propagación de contextos para habilitar la compresión de cabeceras basada en contexto definida en el estándar de Internet RFC 6282 [17].
2.5. EL PROTOCOLO NEIGHBOR DISCOVERY 11 Las diferencias principales de 6LoWPAN-ND respecto al protocolo original, IPv6-ND, son: •Interacciones host-router iniciadas siempre por el host. Esta característica permite que el protocolo siga funcionando aunque los hosts permanezcan dormidos la mayor parte del tiempo para ahorrar batería. •Eliminación de resolución de direcciones basada en multicast. La resolución de direcciones solo es necesaria para el caso de direcciones globales y se realiza a través del router mediante la nueva funcionalidad de registro de direcciones. Esta característica reduce el uso de multicast y reduce el número de transmisiones entre hosts, lo que da lugar a un doble ahorro energético. •Eliminación de mensajes Redirect, ya que su uso es problemático en enlaces no transitivos. •Incorporación de la nueva funcionalidad de registro de direcciones. Esta funcionalidad tiene como fin llevar a cabo tres funciones: DAD, NUD y resolución de direcciones. •A título opcional, se incluyen las siguientes funcionalidades: –Una nueva opción (6LoWPAN Context Option, 6CO) para la diseminación de contextos para la compresión de cabeceras basada en contexto. –Distribución multihop de prefijos y contextos de compresión mediante la nueva opción Authoritative Border Router Option (ABRO). –Mecanismo de DAD basado en multihop para los casos en que sea necesario. Para habilitar este mecanismo se introducen los nuevos tipos de mensaje ICMPv6 Duplicate Address Request, (DAR) y Duplicat Address Confirmation (DAC). Dada la importancia de estos protocolos, así como de las diferencias entre ellos, se recomienda especialmente la lectura de la Sección 2.9 del Apéndice A.
Capítulo 3 Planteamiento del problema Este capítulo introduce los puntos en los que se encuentran diferencias e incompatibilidades entre las pilas de protocolos en cada uno de los segmentos de nuestro escenario. Dichos puntos conflictivos se estructuran en base a los diferentes niveles de la pila de protocolos TCP/IP. 3.1 Capa de enlace En nuestro escenario cohabitan como protocolos de capa de enlace Ethernet/IEEE 802.3 y IEEE 802.15.4. Las Figuras 2.2 y2.3 muestran los formatos de trama de cada uno de estos protocolos. Para que la transmisión de un mensaje entre nodos de distintos segmentos pueda llevarse a cabo, es necesario desencapsular el contenido de la trama de origen y posteriormente encapsularlo en una trama MAC del protocolo correspondiente al segmento de destino. Este proceso, sin embargo, plantea dos problemas: 1. Las direcciones MAC de cada uno de los segmentos tienen longitudes diferentes. Mientras que Ethernet utiliza direcciones MAC de 48 bits, IEEE 802.15.4 puede utilizar direcciones cortas de 16 bits o direcciones largas de 64 bits. 2. Dado que el envío de paquetes desde un segmento a otro ha de ser un proceso transparente (los nodos involucrados no están al corriente siquiera de que haya más de un segmento de red), no es posible determinar a priori en que segmento reside el nodo destinatario de un mensaje dado. Las soluciones a estos dos problemas de nivel de capa de enlace se describirán en la Sección 4.2. 3.2 Pseudo-capa de adaptación La pseudo-capa de adaptación 6LoWPAN se encuentra solamente en el segmento de red correspondiente a IEEE 802.15.4. El problema que plantea este hecho es que un nodo del segmento Ethernet no implementa 6LoWPAN y, por tanto, no es capaz de encapsular paquetes IPv6 de manera que puedan ser procesados por nodos del segmento IEEE 802.15.4. Del mismo modo, los paquetes IPv6 enviados por nodos del segmento IEEE 802.15.4 son encapsulados en paquetes 6LoWPAN que los nodos del segmento Ethernet no pueden procesar. 13
Capítulo 5 Implementación Este capítulo describe los aspectos más relevantes de la implementación del 6LP-GW, así como los medios utilizados para su realización. Todos estos elementos se describen con mayor detalle en el Capítulo 4, Applying the Method, del Apéndice A. 5.1 Programación de la plataforma hardware Todo el software implementado para el desarrollo de este proyecto esta concebido para ser utilizado en un dispositivo empotrado diseñado e implementado como parte de otro proyecto de fin de máster [32]. El microprocesador utilizado por dicho dispositivo es un MSP430 de Texas Instruments de arquitectura RISC. Para la implementación del sistema en este microcontrolador se ha utilizado ANSI C como lenguaje de programación. Aunque el software ha sido diseñado teniendo en cuenta la arquitectura y el microcontrolador objetivos, todo el sistema ha sido implementado de manera que, a excepción de los drivers directamente vinculados al hardware específico, sea posible adaptarlo a cualquier otra plataforma. Como soporte al lenguaje de programación, se han utilizado las librerías del sistema operativo Contiki. Contiki es un sistema operativo open source escrito en C para dispositivos empotrados. Entre otras cosas, estas librerías ofrecen implementaciones de los principales protocolos de red utilizados, como son 6LoWPAN, IPv6 o IPv6-ND, además de ofrecer un mecanismo de abstracción que permite estructurar el programa en diferentes hilos de ejecución o protothreads [15]. Sin embargo hay que tener en cuenta que la implementación de 6LoWPAN disponible en Contiki no incluye el protocolo 6LoWPAN-ND ni, como es natural, la parte del software que ha de ser específico para el hardware utilizado [32]. Las secciones 2.10.2 y 4.1 del Apéndice A ofrecen una explicación más detallada sobre Contiki. 5.2 Herramientas de desarrollo y depuración Las principales herramientas de desarrollo y depuración utilizadas en este proyecto han sido el entorno de desarrollo integrado Code Composer Studio™y el analizador de protocolos de red Wireshark. En cuanto al primero, es un software propietario de Texas Instruments basado en Eclipse que incluye las herramientas de compilación y depuración necesarias para el microcontrolador MSP430. Aunque en primera instancia se optó por la alternativa open source que era la utilización del toolchain de gcc disponible para MSP430, finalmente 21
22 CAPÍTULO 5. IMPLEMENTACIÓN hubo que descartar esa opción debido a problemas de compatibilidad con la versión del microcontrolador utilizado (MSP430F5435). Por otro lado, Wireshark es un software open source ampliamente conocido y de gran utilidad para el análisis de protocolos de red. Además, en su versión de desarrollo 1.5.0 incluye disectores para los protocolos 6LoWPAN y 6LoWPAN-ND. Para poder analizar el trafico de la red, se utilizó un switch HP con capacidad de motitorización de puertos, lo que permitía hacer un volcado a un puerto Ethernet de todo el tráfico que atravesase el switch. Ese switch se colocó entre el router IPv6 de la red y el 6LP-GW. para poder analizar el tráfico del segmento Ethernet. Para el análisis del tráfico del segmento IEEE 802.15.4, se implemento un packet sniffer [32] un dispositivo igual al empleado para el 6LP-GW, cuya función era volcar por su interfaz Ethernet todo el tráfico capturado por su interfaz radio. Este dispositivo fue conectado a otro de los puertos del switch, haciendo así posible la monitorización del tráfico de ambos segmentos de la red. 5.3 Sistema El sistema está compuesto por diferentes bloques lógicos. Además de la implementación de los mecanismos de proxy-gateway mencionados repetidas veces a lo largo de esta memoria, el software implementado incluye además un host IPv6 “residente” en la misma plataforma. Dicho host está conectado lógicamente a la interfaz Ethernet, por lo que desde el punto de vista de los mecanismos de proxy-gateway es un nodo Ethernet más en la red. Dicho host “local” implementa además una doble pila IPv4/IPv6. El motivo para incluir este elemento en el sistema, así como para dotarlo de una pila dual IPv4/IPv6, es proporcionar los mecanismos para la implementación de futuras funcionalidades. Dichas funcionalidades podrían variar desde mecanismos de monitorización de la red (teniendo en cuenta la posición estratégica del 6LP-GW en la misma), hasta mecanismos que posibiliten el uso de tunneling para hacer posible su utilización incluso en redes que todavía no soportan IPv6. La Figura 5.1 muestra la estructura del sistema implementado. Como puede observarse en dicha figura, el área rodeada por un borde blanco en la parte superior de la figura constituye la parte del sistema correspondiente al host local. El área ovalada del centro corresponde a la lógica encargada de las funciones de proxy-gateway necesarias para la comunicación entre los dos segmentos de red. Este módulo, como veremos en la Sección 5.3.4, se subdivide a su vez en 3 bloques lógicos con estructura jerárquica, cada uno encargado de una tarea diferente. Finalmente, los bloques inferiores del sistema representan las diferentes capas de red a través de las cuales los paquetes son enviados y recibidos.
5.3. SISTEMA 23 IEEE 802.15.4 MAC IEEE 802.3 MAC 6LoWPAN 6LP-GW Radio HAL Ethernet HAL ARP IPv4 ND TCP IPv6 UDP TCP UDP DHCP PHY PHY Application layer Transport layer Network layer 6LP-GW pseudo-layer Adaptation layer Link layer Physical layer IPv6 host 6LP-GW Figura 5.1: Estructura del sistema 5.3.1 Capa de abstracción del hardware En la parte inferior del sistema se encuentra la parte del software que es directamente dependiente del hardware, la capa de abstracción del hardware (Hardware Abstraction Layer, HAL). Los principales bloques funcionales de este bloque de la aplicación son los drivers de los controladores IEEE 802.15.4 y Ethernet y el reloj del sistema. El controlador Ethernet es un ENC28J60 de Microchip, mientras que el controlador de la radio IEEE 802.15.4 es un CC2520 de Texas Instruments. En ambos casos, los drivers de estos controladores han sido implementados de acuerdo a las especificaciones de los fabricantes incluidas en sus respectivas hojas de especificaciones. En el caso del reloj del sistema (necesario para monitorización de tiempo en diversos componentes de la aplicación), se implementa el driver para el módulo Timer A del MSP430. Dicho driver utiliza una de las interrupciones de reloj del microcontrolador para contabilizar el número de tics del reloj del
24 CAPÍTULO 5. IMPLEMENTACIÓN sistema. Como la frecuencia de estos tics es un valor conocido, este driver hace posible contabilizar el tiempo de manera razonablemente precisa. 5.3.2 Capa de enlace A nivel de capa de enlace se encuentra, por un lado, la capa de enlace Ethernet y, por otro la capa de enlace IEEE 802.15.4. La función de estos módulos es encapsular/desencapsular paquetes IPv6/IPv4 en el caso de Ethernet o 6LoPWAN en el caso de IEEE 802.15.4. Además, para el caso de IPv4, el módulo de capa de enlace Ethernet también lleva a cabo las funciones del protocolo de resolución de direcciones ARP (Address Resoultion Protocol) [24] para resolución de direcciones Ethernet de hosts IPv4. 5.3.3 Pseudo-capa de adaptación Las funciones a realizar en esta capa son principalmente la compresión/descompresión de paquetes IPv6 mediante la utilización del mecanismo de compresión basado en contexto descrito en el documento RFC 6282 [17]. Aunque Contiki proporciona mecanismos para llevar a cabo estas funciones, dichos mecanismos presentan ciertas limitaciones: por un lado, Contiki no implementa el protocolo 6LoWPAN-ND, por lo que no dispone de los mecanismos para la diseminación y asignación dinámica de contextos de compresión (los contextos de compresión a utilizar deben ser introducidos manualmente en tiempo de compilación). Por otro lado, la compresión de cabeceras incluida en Contiki sólo soporta contextos de longitud fija de 64 bits, mientras que el estándar RFC 6282 permite contextos de hasta 128 bits (la dirección IPv6 completa). Dado que ha sido implementada la funcionalidad opcional de 6LoWPAN-ND para la diseminación de contextos de compresión, estas dos limitaciones impuestas por Contiki han sido eliminadas mediante la modificación de las partes del sistema que así lo requerían, permitiendo hacer un uso completo de la compresión basada en contexto. 5.3.4 Módulo 6LP-GW Este módulo es el que realiza las tareas principales del sistema. Estas tareas son las relativas al “paso” de paquetes desde un segmento a otro (packet forwarding) y las tareas de proxy entre los dos protocolos ND. Estas tareas de proxy incluyen también las funciones de 6LBR relativas a 6LoWPAN-ND que no son cubiertas por el router convencional de la red, o las tareas de IPv6-ND que no están incluidas en 6LoWPAN-ND (y por tanto deben ser realizadas por el 6LP-GW en nombre de los nodos 6LoWPAN). Por tanto, el módulo 6LP-GW se compone de tres submódulos: el módulo “Forwarding”, el módulo “Proxy”, y el módulo “ND”. La Figura 5.2 esquematiza la relación jerárquica entre estos tres submódulos dentro del módulo 6LP-GW, y muestra el orden
5.3. SISTEMA 25 (indicado por los números en las flechas) en el que las operaciones de cada uno de los módulos son ejecutadas en caso de recepción de un paquete de ND. Como puede observarse, el módulo Forwarding aparece dos veces, ya que es necesario para procesar la recepción y el envío de los paquetes. Proxy module Forwarding module ND module Incoming ND packet Forwarding module (1) (2) (3) (4) (5) (6) Figura 5.2: Arquitectura del Módulo 6LP-GW El módulo Forwarding esta a cargo de determinar cual es el segmento destino de un paquete dado. Para ello, como se explicó en la Sección 4.2, se implementa un sencillo mecanismo basado en bridging (sin implementar el algoritmo Spanning Tree Protocol, STP [1] ni ninguna de sus variantes). Además, este módulo se encarga de la traducción de direcciones de la capa de enlace entre Ethernet e IEEE 802.15.4. El motivo de que este módulo que lleva a cabo funciones de la capa de enlace se encuentre desvinculado de los módulos de la capa de enlace (Sección 5.3.2 de este capítulo) es el hecho de que en la mayoría de los casos, no es posible determinar el destino real de un paquete del protocolo ND hasta que ha sido descomprimido (en el caso de un paquete 6LoWPAN) y procesado por el módulo Proxy. El módulo ND agrupa todas las tareas y estructuras de datos relativas a los protocolos ND de cada uno de los segmentos. Estas tareas incluyen aquellas que deben ser realizadas por un 6LBR, tal como se especifica en 6LoWPAN-ND, como son el mantenimiento de la caché de vecinos (Neighbor Cache, NC) o de la tabla de contextos, además de la generación y procesado de paquetes ND. Por otro lado, este módulo también implementa las funciones necesarias para llevar a cabo las tareas de IPv6-ND no recogidas en
26 CAPÍTULO 5. IMPLEMENTACIÓN 6LoWPAN-ND y que, por tanto, han de ser llevadas a cabo por el 6LP-GW en representación de los 6LNs. El módulo Proxy es el submódulo principal del módulo 6LP-GW. Su función es llevar a cabo las tareas descritas en el Capítulo 4, utilizando para ello los mecanismos proporcionados por los módulos Forwarding y ND.
Capítulo 6 Evaluación Este capítulo describe las pruebas de funcionamiento a las que ha sido sometido el sistema, así como los resultados obtenidos en la ejecución de las mismas. El Capítulo 5, Analysis, del Apéndice A recoge una explicación más detallada sobre la evaluación del sistema que se explica a continuación. 6.1 Métodos de evaluación del sistema Con el fin de evaluar los resultados del sistema implementado (6LP-GW) se utilizarán dos tipos de pruebas cuyos fines son, respectivamente, verificar el correcto funcionamiento de la aplicación y su rendimiento. Para evaluar el correcto funcionamiento del sistema, esto es, que cumple las tareas para las que ha sido diseñado de acuerdo a lo esperado, se realizará una serie de 44 casos de prueba (test cases). Los casos de prueba consistirán en, partiendo de un estado conocido del sistema, proporcionar una entrada también conocida y contrastar el resultado obtenido respecto al resultado teórico esperado. La Sección 5.1.1 del Apéndice A detalla los pormenores de cada uno de estos 44 casos de prueba. La evaluación de rendimiento tiene como propósito probar que el sistema es capaz de realizar sus tareas en un tiempo razonable. Para ello se utilizará un método que consiste en el envío de pares de paquetes idénticos con la mínima separación posible en el tiempo entre el envío del primero y el segundo. Dichas series de paquetes serán enviados desde uno de los segmentos que interconecta el 6LP-GW al otro. De esta manera, suponiendo que los paquetes parten del origen con una separación en el tiempo cercana a 0, es posible determinar el tiempo aproximado de procesamiento del segundo paquete como la separación en el tiempo con la que ambos paquetes llegan a su destino. Esta prueba se realizará con paquetes UDP con cargas (payloads) de todos los tamaños entre 1 y 93 bytes (la longitud máxima de payload que puede alojarse en un paquete UDP en nuestro escenario). Para cada uno de los tamaños de payload se tomarán 100 medidas, eliminando de ellas la menor y la mayor y calculando el tiempo de procesamiento como la media aritmética de las 98 restantes medidas. Este test se realizará para paquetes originados en el segmento Ethernet y destinados al segmento IEEE 802.15.4 y se repetirá para el caso inverso. 27
28 CAPÍTULO 6. EVALUACIÓN 6.2 Evaluación de resultados Los resultados obtenidos en el test de corrección del sistema tras someterlo a la batería de casos de prueba fueron positivos en el 100% de los casos. Esto significa que los resultados fueron los esperados para cada uno de los casos de prueba realizados. Aunque es materialmente imposible diseñar un caso de prueba para cada una de las posibles situaciones que pueden ocurrir en la práctica, dichos resultados son un indicio razonable de la corrección del sistema. Por otro lado, los tiempos de procesamiento obtenidos como resultado en los tests de rendimiento, considerando todas las mediciones efectuadas, varían entre 1.761 ms y 6.756 ms, con una media absoluta de 4.104 ms. Las gráficas 6.1 y6.2 muestran los tiempos de procesamiento para paquetes originados en el segmento IEEE 802.15.4 y Ethernet respectivamente. 1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 9093 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6Processing time vs. payload size Payload length (bytes) Processing time (milliseconds) Time Avg. Figura 6.1: Test de rendimiento IEEE 802.15.4 - Ethernet en función del tamaño de payload. Como estos resultados muestran, los tiempos de procesamiento de paquetes atravesando el 6LP-GW desde el segmento Ethernet al segmento IEEE 802.15.4 son ligeramente superiores que los relativos al sentido inverso. Los motivos de
6.2. EVALUACIÓN DE RESULTADOS 29 1 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 9093 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 6.5 7Processing time vs. payload size Payload length (bytes) Processing time (milliseconds) Time Avg. Figura 6.2: Test de rendimiento Ethernet - IEEE 802.15.4 en función del tamaño de payload. este hecho están directamente vinculados al hardware del controlador de cada una de las interfaces. Una explicación más detallada sobre estos motivos puede encontrarse en la Sección 5.2.2 del Apéndice A. La Figura 6.3 muestra la relación entre los tiempos de procesamiento de paquetes en cada uno de los sentidos. A partir de las mediciones realizadas, es posible calcular el coste marginal medio de procesamiento de un byte de payload adicional como la media de las diferencias en los tiempos de procesamiento de paquetes de longitudes consecutivas: tiempobyte =P93 i=2 (xi−xi−1) 93 Realizando los cálculos para cada uno de los dos sentidos de transmisión y, posteriormente, la media entre ellos, el coste marginal de transmitir un byte adicional de payload es de 0.039 ms.
36 CAPÍTULO 7. CONCLUSIONES enlaces de ese tamaño). Es necesario notar, sin embargo, que para desarrollar dicho punto de acceso, sería necesaria la implementación de mecanismos de control de bucles como los mencionados anteriormente en esta sección.
Bibliografía [1] IEEE Standard for Information Technology- Telecommunications and Information Exchange Between Systems- Local and Metropolitan Area Networks- Common Specifications Part 3: Media Access Control (MAC) Bridges. ANSI/IEEE Std 802.1D, 1998 Edition, pages 58 – 107, 1998. [2] IEEE Standard for Information Technology- Telecommunications and Information Exchange Between Systems- Local and Metropolitan Area Networks- Specific Requirements Part 15.4: Wireless Medium Access Control (MAC) and Physical Layer (PHY) Specifications for Low-Rate Wireless Personal Area Networks (WPANs). IEEE Std 802.15.4-2006 (Revision of IEEE Std 802.15.4-2003), pages 0_1 –305, 2006. [3] IEEE Standard for Information technology—Telecommunications and information exchange between systems—Local and metropolitan area networks—Specific requirements Part 11: Wireless LAN Medium Access Control (MAC) and Physical Layer (PHY) Specifications. ANSI/IEEE Std 802.11, 2007 Edition, 2007. [4] IEEE Standard for Information Technology- Telecommunications and Information Exchange Between Systems- Local and Metropolitan Area Networks- Specific Requirements Part 3: Carrier Sense Multiple Access With Collision Detection (CSMA/CD) Access Method and Physical Layer Specifications - Section One. IEEE Std 802.3-2008 (Revision of IEEE Std 802.3-2005), pages c1 –597, 26 2008. [5] Guidelines For 64-bit Global Identifier (EUI-64) Registration Authority. IEEE Standards Assocation, April 2010. [6] J. Arkko, J. Kempf, B. Zill, and P. Nikander. SEcure Neighbor Discovery (SEND). RFC 3971, Internet Engineering Task Force, March 2005. [7] C. Bormann. 6LoWPAN Generic Compression of Headers and Header-like Payloads. Internet-Draft draft-bormann-6lowpan-ghc-03, Internet Engineering Task Force, October 2011. Work in progress. [8] R. Braden. Requirements for Internet Hosts - Application and Support. RFC 1123, Internet Engineering Task Force, October 1989. [9] R. Braden. Requirements for Internet Hosts - Communication Layers. RFC 1122, Internet Engineering Task Force, October 1989. [10] A. Conta, S. Deering, and M. Gupta. Internet Control Message Protocol (ICMPv6) for the Internet Protocol Version 6 (IPv6) Specification. RFC 4443, Internet Engineering Task Force, March 2006. 37
38 BIBLIOGRAFÍA [11] M. Crawford. Transmission of IPv6 Packets over Ethernet Networks. RFC 2464, Internet Engineering Task Force, December 1998. [12] S. Deering and R. Hinden. Internet Protocol, Version 6 (IPv6) Specification. RFC 2460, Internet Engineering Task Force, December 1998. [13] T. Dierks and E. Rescorla. The Transport Layer Security (TLS) Protocol Version 1.2. RFC 5246, Internet Engineering Task Force, August 2008. [14] R. Droms, J. Bound, B. Volz, T. Lemon, C. Perkins, and M. Carney. Dynamic Host Configuration Protocol for IPv6 (DHCPv6). RFC 3315, Internet Engineering Task Force, July 2003. [15] Adam Dunkels, Oliver Schmidt, Thiemo Voigt, and Muneeb Ali. Protothreads: Simplifying event-driven programming of memory-constrained embedded systems. Proceedings of the Fourth ACM Conference on Embedded Networked Sensor Systems (SenSys 2006), nov 2006. [16] R. Hinden and S. Deering. IP Version 6 Addressing Architecture. RFC 4291, Internet Engineering Task Force, February 2006. [17] J. Hui and P. Thubert. Compression Format for IPv6 Datagrams over IEEE 802.15.4-Based Networks. RFC 6282, Internet Engineering Task Force, September 2011. [18] S. Kent and K. Seo. Security Architecture for the Internet Protocol. RFC 4301, Internet Engineering Task Force, December 2005. [19] N. Kushalnagar, G. Montenegro, and C. Schumacher. IPv6 over Low- Power Wireless Personal Area Networks (6LoWPANs): Overview, Assumptions, Problem Statement, and Goals. RFC 4919, Internet Engineering Task Force, August 2007. [20] Luis Maqueda. Guidelines for the operation of Neighbor Discovery for a 6LoWPAN Proxy-Gateway. upcoming ietf draft, 2011. Work in progress. [21] Friedemann Mattern and Christian Floerkemeier. From the Internet of Computers to the Internet of Things, volume 6462 of LNCS, pages 242– 259. Springer, 2010. [22] G. Montenegro, N. Kushalnagar, J. Hui, and D. Culler. Transmission of IPv6 Packets over IEEE 802.15.4 Networks. RFC 4944, Internet Engineering Task Force, September 2007. [23] T. Narten, E. Nordmark, W. Simpson, and H. Soliman. Neighbor Discovery for IP version 6 (IPv6). RFC 4861, Internet Engineering Task Force, September 2007.
BIBLIOGRAFÍA 39 [24] D. Plummer. Ethernet Address Resolution Protocol: Or Converting Network Protocol Addresses to 48.bit Ethernet Address for Transmission on Ethernet Hardware. RFC 0826, Internet Engineering Task Force, November 1982. [25] J. Postel. User Datagram Protocol. RFC 0768, Internet Engineering Task Force, August 1980. [26] J. Postel. Internet Protocol. RFC 0791, Internet Engineering Task Force, September 1981. [27] E. Rescorla and N. NagendraModadugu. Datagram Transport Layer Security version 1.2. Internet-Draft draft-ietf-tls-rfc4347-bis-06, Internet Engineering Task Force, July 2011. Work in progress. [28] B. Sarikaya, F. Xia, and G. Zaverucha. Lightweight Secure Neighbor Discovery for Low-power and LossyNetworks. Internet-Draft draft-sarikaya- 6lowpan-cgand-02, Internet Engineering Task Force, October 2011. Work in progress. [29] Z. Shelby, S. Chakrabarti, and E. Nordmark. Neighbor Discovery Optimization for Low Power and Lossy Networks (6LoWPAN). Internet-Draft draft-ietf-6lowpan-nd-18, Internet Engineering Task Force, October 2011. Work in progress. [30] S. Thomson, T. Narten, and T. Jinmei. IPv6 Stateless Address Autoconfiguration. RFC 4862, Internet Engineering Task Force, September 2007. [31] T. TimWinter, P. Thubert, A. Brandt, T. Clausen, J. Hui, R. Kelsey, P. Levis, K. Pister, R. Struik, and J. Vasseur. RPL: IPv6 Routing Protocol for Low power and Lossy Networks. Internet-Draft draft-ietf-roll- rpl-19, Internet Engineering Task Force, March 2011. Work in progress. [32] Joaquín Juan Toledo. Wireless Sensor Architecture for a Home Event Management System. Master’s thesis, 2012. Work in progress (completion expected in Spring 2012).
Apéndice A: KTH Master’s Thesis Report 41
Degree project in Communication Systems Second level, 30.0 HEC Stockholm, Sweden LUIS MAQUEDA ARA Design, Implementation, analysis, and evaluation Neighbor Discovery Proxy-Gateway for 6LoWPAN-based Wireless Sensor Networks KTH Information and Communication Technology
Neighbor Discovery Proxy-Gateway for 6LoWPAN-based Wireless Sensor Networks Design, Implementation, analysis, and evaluation Luis Maqueda Ara [email protected] December 21, 2011 Draft Supervisor: Gerald Q. Maguire Jr. School of Information and Communication Technology KTH Royal Institute of Technology Stockholm, Sweden
Abstract The IETF 6LoWPAN working group has defined a number of optimizations to adapt the traditional IPv6 Neighbor Discovery protocol to non-transitive wireless links. While these optimizations result in a more efficient use of the resources of hosts within a 6LoWPAN network, they introduce a number of impediments for communication between nodes in traditional IPv6 networks and nodes in 6LoWPAN networks. This document describes how to overcome these obstacles by providing the necessary proxy mechanisms, leading to a transparent, seamless, and cost-effective integration of 6LoWPAN nodes into existing IPv6 network infrastructures. In particular, this document details the requirements, specification, and implementation of an embedded device responsible for such integration: a 6LoWPAN Neighbor Discovery Proxy- Gateway (6LP-GW). Moreover, this report demonstrates that integrating 6LoWPAN nodes into existing IPv6 networks by means of a 6LP-GW as described here is both feasible and convenient in most situations. This convenience can be observed from both the network and the end-user perspectives: From the network’s point of view, the solution proposed here integrates 6LoWPAN into an existing IPv6 network. Hence, 6LoPWAN nodes and traditional IPv6 devices can coexist within the same IPv6 subnet, sharing the same network prefix. Furthermore, enabling such integration and coexistence is simple and inexpensive in contrast to other solutions. The main reason for this simplicity is that the 6LP-GW is completely transparent from both the network layer and the neighbor discovery protocol’s perspective: while each type of node still takes advantage of its own specific neighbor discovery protocol’s features, all of them share the same IPv6 subnet and no node in the network is able to determine the nature of its neighbors (simply on the basis of the neighbor discovery protocol). Each of the above advantages leads to an immediate benefit from the endusers’ perspective: the integration of the 6LoWPAN network into the existing infrastructure, frees the user from having to acquire an expensive (and so far rare) border router. Instead, the end-user simply buys a 6LP-GW which, as previously mentioned, is inexpensive compared to the former; the 6LP-GW broadens the existing IPv6 router’s functionality (in contrast to a 6LBR which would replace it). In addition, it is important to mention that using a 6LP-GW could not be simpler; once attached to an IPv6 router’s LAN port, no further intervention is required. As result, the solution proposed here undoubtedly eases and speeds up the deployment process of 6LoWPAN, enabling immediate use by even the most inexperienced user. i
viii CONTENTS 2.9.1 Neighbor Discovery for IPv6 ............... 19 2.9.1.1 IPv6 Neighbor Discovery messages ....... 19 2.9.1.2 IPv6-ND Protocol Overview .......... 20 2.9.2 Neighbor Discovery Optimization for LLNs ....... 22 2.9.2.1 6LoWPAN Neighbor Discovery messages . . . 22 2.9.2.2 6LoWPAN-ND Protocol Overview ....... 22 2.9.3 IPv6-ND vs. 6LoWPAN-ND ............... 24 2.9.3.1 Differences .................... 24 2.9.3.2 Incompatibilities ................. 25 2.10 What have others already done? ................. 26 2.10.1 Neighbor Discovery proxies ................ 26 2.10.2 The Contiki Operating System .............. 29 2.10.2.1 Contiki’s protothreads .............. 29 2.10.2.2 Contiki’s kernel ................. 30 3 Method 35 3.1 Assumptions and application scenario .............. 35 3.1.1 Assumptions ........................ 35 3.1.2 Application scenario .................... 36 3.2 Proxy Operation Specification ................... 37 3.2.1 Proxy Operation overview ................. 38 3.2.2 Conceptual datastructures and Initialization ....... 38 3.2.3 Packet Forwarding ..................... 39 3.2.4 Proxy operation ...................... 41 3.2.4.1 Processing Neighbor Solicitation Messages . . 41 3.2.4.2 Processing Neighbor Advertisement messages . 48 3.2.4.3 Processing Router Solicitation messages . . . . 50 3.2.4.4 Processing Router Advertisement messages . . 52 3.2.4.5 Processing a Redirect .............. 56 3.2.4.6 Non-proxy Features ............... 57 4 Applying the Method 59 4.1 What Contiki’s provides and does not provide .......... 59 4.1.1 What Contiki provides ................... 59 4.1.2 What Contiki requires ................... 62 4.1.3 What Contiki does not provide .............. 67 4.2 Application Overview ....................... 69 4.2.1 Hardware Abstraction Layer ............... 71 4.2.1.1 The Clock library implementation ....... 71 4.2.1.2 Ethernet Controller Driver ........... 73 4.2.1.3 Radio Transceiver Controller Driver ...... 74 4.2.1.4 Other Drivers .................. 74 4.2.2 MAC layer ......................... 75 4.2.2.1 IEEE 802.3 MAC layer ............. 75
CONTENTS ix 4.2.2.2 IEEE 802.15.4 MAC layer ............ 76 4.2.3 6LoWPAN Adaptation layer ............... 76 4.2.4 The 6LP-GW pseudo-layer ................ 77 4.2.5 Network Layer ....................... 78 4.2.6 Application Layer ..................... 79 5 Analysis 81 5.1 Method for Evaluation ....................... 81 5.1.1 Use cases test ........................ 81 5.1.2 Processing time and throughput measurement ...... 91 5.2 Analysis of metric results ..................... 92 5.2.1 Use cases .......................... 92 5.2.2 Processing time and throughput ............. 92 6 Conclusions 97 6.1 Conclusions ............................. 97 6.1.1 Goals ............................ 97 6.1.2 Insights and suggestions for further work ........ 98 6.2 Future work .............................100 6.2.1 What has been left undone? ................100 6.2.1.1 Loop Avoidance .................100 6.2.1.2 6LoWPAN Fragmentation ...........101 6.2.1.3 Advanced Context Creation and Management 101 6.2.1.4 Radio Duty Cycling Mechanisms ........102 6.2.1.5 Power over Ethernet ...............102 6.2.1.6 Security ......................103 6.2.2 Next obvious things to be done ..............103 References 105 Appendix A: 6LoWPAN-ND Host implementation 111 Appendix B: Traffic captures 115 Appendix C: Source code 121 Appendix D: Hardware Specification 123
List of Figures 2.1 The TCP/IP stack ........................... 6 2.2 Ethernet data link layer protocol encapsulated into a the MAC Client Data field of a IEEE 802.3 MAC packet ........... 7 2.3 IEEE 802.15.4 data frame ....................... 10 2.4 IPv4 datagram header ......................... 12 2.5 IPv6 datagram header ......................... 13 2.6 6LoWPAN Intermediate layer ..................... 15 2.7 6LoWPN IPHC base header ...................... 17 2.8 Backbone Routers scenario ...................... 27 2.9 6LBR vs. 6LP-GW ........................... 28 2.10 Code comparison between state machine implementations (1). . . . 31 2.11 Code comparison between state machine implementations (2). . . . 32 3.1 The 6LP-GW .............................. 37 3.2 The 6LP-GW Forwarding mechanism ................ 40 3.3 EUI-48 Encapsulated in EUI-64 .................... 40 3.4 NS message processing. ........................ 42 3.5 NS with ARO processing diagram. .................. 44 3.6 DAD performed on behalf of 6LoWPAN nodes. ........... 46 3.7 NA message processing. ........................ 49 3.8 RS message processing. ........................ 51 3.9 RA message processing. ........................ 52 4.1 A typical Contiki-based application. ................. 63 4.2 The Contiki network stack ....................... 66 4.3 The 6LP-GW application diagram .................. 70 4.4 The 6LP-GW module architecture .................. 79 5.1 Radio to Ethernet performance test. ................. 93 5.2 Ethernet to radio performance test. .................. 94 5.3 Comparison of measured times .................... 95 B.1 6LH bootstrapping capture ......................115 xi
xii List of Figures B.2 PIO option in IPv6-ND RA ......................116 B.3 PIO option in 6LoWPAN-ND RA ..................116 B.4 6CO option in 6LoWPAN-ND RA ..................117 B.5 6LH Registration renewal .......................117 B.6 NA including ARO option .......................118 B.7 NCD performing NUD on a 6LH ...................118 B.8 NCD performing Ping on a 6LH ...................118 D.1 Hogaza v1.2 Schematics. ........................124 D.2 CC2591EM 3.0 Schematics. ......................125 D.3 ENC28J60-H Schematics. .......................126
List of Tables 2.1 IEEE 802.15.4 physical layers ..................... 9 2.2 IPv6-ND message types. ........................ 21 2.3 6LoWPAN-ND message types. .................... 23 2.4 Differences between 6LoWPAN-ND and IPv6-ND .......... 25 xiii
List of Acronyms and Abbreviations This document requires readers to be familiar with terms and concepts described in RFC 4861 [34], RFC 4862 [47], RFC 4919 [30], RFC 4944 [33], draft-ietf-6lowpan-nd [43], and RFC 6282 [27]. For clarity we summarize some of these terms and give a short description of them before presenting them in next sections. 6CO 6LoWPAN Context option (I-D.ietf-6lowpan-nd) 6LBR 6LoWPAN Border Router (I-D.ietf-6lowpan-nd) 6LH 6LoWPAN Host, in contrast with a 6R (I-D.ietf-6lowpan-nd) 6LoWPAN-ND Neighbor Discovery optimization for LLNs (I-D.ietf-6lowpan-nd) 6LR 6LoWPAN Router. 6LRs have only one interface and therefore they are not Border Routers 6R 6LoWPAN Router, either a 6LR or 6LBR ABRO Authoritative Border Router option (I-D.ietf-6lowpan-nd) ACK Acknowledgement AES Advanced Encryption Standard API Application Programming Interface ARO Address Registration option (I-D.ietf-6lowpan-nd) ARP Address Resolution Protocol (RFC 826) BOOTP Bootstrap Protocol (RFC 1531) CRC Cyclic Redundancy Check DAC Duplicate Address Confirmation message (I-D.ietf-6lowpan-nd) DAD Duplicate Address Detection (RFC 4861) DAR Duplicate Address Request message (I-D.ietf-6lowpan-nd) DHCP Dynamic Host Configuration Protocol (RFC 2131) DNS Domain Name Server DTLS Datagram Transport Layer Security ECN Explicit Congestion Notification (A Protocol for Packet Network Interconnection) xv
xvi LIST OF ACRONYMS AND ABBREVIATIONS EUI-64 IEEE’s 64-bit Extended Unique Identifier (EUI-64) FCF Frame Control Field (IEEE 802.15.4) FCS Frame Check Sequence (IEEE 802.15.4) FFD Full-Function Device (IEEE 802.15.4) GTS Guaranteed Time Slot HAL Hardware Abstraction Layer IEEE Institute of Electrical and Electronic Engineers IETF Internet Engineering Task Force IHL Internet Header Length (A Protocol for Packet Network Interconnection) IID Interface Identifier (RFC 4291) IKE Internet Key Exchange (RFC 2409) IPHC IPv6 Header compression (RFC 6282) IPv4 Internet Protocol version 4 (RFC 791) IPv6 Internet Protocol version 6 (RFC 2460) IPv6-ND Neighbor Discovery for IPv6 protocol (RFC 4861) LLN Low-power and Lossy Network LoWPAN Low power Wireless Personal Area Network LRU Least Recently Used LR-WPAN Low-Rate Wireless Personal Area Network (IEEE 802.15.4) MAC Medium Access Control (IEEE 802.3) MPDU MAC Protocol Data Unit (IEEE 802.15.4) MTU Maximum Transfer Unit NA Neighbor Advertisement message (RFC 4861) NC Neighbor Cache (RFC 4861)
xvii NCD Non-Constrained Device. Any device not having strong restrictions in terms of availability of resources ( for example, a personal computer) NCE Neighbor Cache Entry (RFC 4861) ND Neighbor Discovery protocol, either 6LoWPAN-ND or IPv6-ND NS Neighbor Solicitation message (RFC 4861) NUD Neighbor Unreachability Detection (RFC 4861) OSI International Standards Organization’s Open System Interconnect PAN Personal Area Network PIO Prefix Information option (RFC 4861) RA Router Advertisement message (RFC 4861) RFC Request For Comments RFD Reduced-Function Device (IEEE 802.15.4) RFID Radio-Frequency Identification Router Either a RR or 6R RPL IPv6 Routing Protocol for Low power and Lossy Networks RR Regular IPv6 router, in contrast with a 6R RS Router Solicitation message (RFC 4861) RSSI Received Signal Strength Indication RSTP Rapid Spanning-Tree Protocol (IEEE 802.1D) RX Reception SEND Secure Neighbor Discovery (RFC 3971) SFD Start of Frame Delimiter SLLAO Source Link-Layer Address option (RFC 4861)
6CHAPTER 2. BACKGROUND Application Layer Transport Layer Internet Layer Link Layer Physical Layer Figure 2.1: The TCP/IP stack, including the Physical Layer (dashed) 2.2 IEEE 802.3 IEEE 802.3 [5] is a IEEE working group and a set of standards rather than a single standard. There are several versions and amendments, with IEEE 802.3- 2008 being the latest revision. IEEE 802.3-2008 defines the physical layer and data link layer’s media access control (MAC) of a wired Ethernet. As for the physical layer, this family of standards supports several types of media, such as different types of coaxial cable, shielded and unshielded twisted pair, and Fiber-Optics. The supported transmission data rates range from 10 Mbit/s to 100 Gbit/s. Some media support half or full-duplex transmission. The MAC protocol specified in IEEE standard 802.3 is Carrier Sense Multiple Access with Collision Detection (CSMA/CD). This MAC protocol was utilized in the experimental Ethernet developed at Xerox Palo Alto Research Center. However, new implementations operating in full-duplex mode no longer utilize CSMA/CD —since in full-duplex mode for a point- to-point link there is no probability of collisions. This MAC layer consists of the channel-access portion of the link layer used by Ethernet, but does not define a logical link control protocol (generally implementations use the IEEE 802.2 logical link layer). Consequently, the standard defines the mapping between IEEE 802.3 MAC service interface primitives. As result, Ethernet’s data link-layer protocol can be encapsulated within the MAC Client Data field of IEEE 802.3 packets (the common set of service interface primitives enables bridging between IEEE 802 MAC/PHY protocols). Figure 2.2 illustrates this Ethernet data link-layer into IEEE 802.3 MAC Client Data field encapsulation.
2.2. IEEE 802.3 7 Note that when used with IEEE 802.2 there is an additional header before the Length/Type field. octets: 6 6 2 46 to 1500 0 to 46 4 ETHERNET data link-layer Destination Address Source Address Length/ Type Data Payload Padding CRC octets: 7 1 . . .. . .Variable MAC packet Preamble SFD MAC Client Data Padding CRC Extension Figure 2.2: Ethernet data link layer protocol encapsulated into a the MAC Client Data field of a IEEE 802.3 MAC packet Preamble Used for synchronization between sender and receiver. SFD Start of Frame Delimiter. Indicates the end of the preamble and the start of the packet data. It has constant value of 0xAB (17110). Destination Address 48-bit IEEE 802.3 MAC address of the destination of the frame. Source Address 48-bit IEEE 802.3 MAC address of the originator of the frame. Type/Length This field can have two different meanings. If its value is greater than 1500, then it indicates the type of upper-layer packet being transported. If the field value is less than or equal to 1500, it indicates the length of the payload. Data Payload The data being transmitted. Padding Optional Padding. This is required if the total Ethernet frame length is less than 64 bytes. CRC Cyclic redundancy check for integrity verification. Extension Optional field included only in half-duplex operation when the frame is shorter than the CSMA/CD slot time.
8CHAPTER 2. BACKGROUND 2.3 IEEE 802.15.4 The IEEE 802.15.4 standard [4] specifies the physical and media access control (MAC) for low-rate wireless personal area networks (LR-WPANs). Although LR-WPANs fall within the wireless personal area networks (WPANs) family of standards, they may extend the personal operating space; an LR-WPAN is a simple, low-cost wireless communication network optimized for use in applications with limited power and limited throughput requirements. LR-WPANs aim for low power consumption and low cost, whilst maintaining a reliable data transfer, short-range communication link, and simple and flexible protocol. 2.3.1 IEEE 802.15.4 Topologies The IEEE 802.15.4 standard defines two different device types: full-function devices (FFDs) and reduced-function devices (RFDs). FFDs can participate in the Personal Area Network (PAN) as a PAN coordinator, as a coordinator, or as a device. Even though a network may consist of just RFDs, the presence of at least one FFD acting as a PAN coordinator is recommended. An LR-WPAN may operate in either peer-to-peer or star topologies. In a star topology, all the communication between devices must pass through the central node, which is the PAN coordinator. The PAN coordinator is thus responsible for initiating, routing, and terminating the communication in the network. On the other hand, in a peer-to-peer network, communication between any two nodes is possible as long they are in range; this topology offers greater flexibility, allowing all sorts of mesh formations, but at the cost of increased node power consumption. Peer-to-peer topologies require a PAN coordinator; however they are also likely to require a suitable routing protocol in case multihop is needed (i.e. if two nodes are not in range). This routing protocol should be provided by the upper layers and hence is beyond the scope of the IEEE 802.15.4 standard. 2.3.2 IEEE 802.15.4 Physical Layer Since its release in 2003, different amendments have been defined adding new possible physical layers and/or extending the capabilities of the previously defined ones. At the time of writing this document (June 2011), the different unlicensed frequency bands and modulations, together with the supported data rates defined by the IEEE 802.15.4 physical layer are shown in Table 2.1.
2.3. IEEE 802.15.4 9 2.3.3 IEEE 802.15.4 Medium Access Control (MAC) The MAC layer is responsible for the following tasks: •Beacon management •PAN association and disassociation. •Employing the CSMA-CA mechanism for channel access. •Handling and maintaining the Guaranteed Time Slot (GTS) mechanism. •Frame validation •Acknowledged frame delivery •Supporting device security. Table 2.1: IEEE 802.15.4 physical layers, sorted by release date Physical layer (MHz) Frequency Band (MHz) Modulation Bit rate (kb/s) Description 868/915 868 –868.6BPSK 20 BPSK: Binary phase-shift keying 902 –928 40 868/915 868 –868.6ASK 250 ASK: Amplitude-shift keying 902 –928 250 868/915 868 –868.6O-QPSK 100 O-QPSK: Offset quadrature phase-shift keying 902 –928 250 2450 2,400 –2,483.5O-QPSK 250 UWB 250 –750 BPM-BPSK 851, 110, BPM: Burst phase modulation UWB: Ultra-wide band 3,244 –4,742 6,810 and 5,944 –10,234 27,240 2,450 (CSS) 2,400 – 2,483.5 DQPSK 1,000 CSS: Chirp spread spectrum DQPSK: differential quadrature phase-shift keying 250 780 779 –787 O-QPSK 250 780 779 –787 MPSK 250 MPSK: M-order phase-shift keying 950 950 –956 GFSK 100 GFSK: Gaussian frequency-shift keying 950 950 –956 BPSK 20
10 CHAPTER 2. BACKGROUND In star-topologies, the IEEE 802.15.4 MAC layer provides a beacon-based synchronization mechanism for data transmission and reception between devices and the PAN coordinator, which permits nodes to only listen to the channel at regular intervals, allowing for power saving. In peer-to-peer topologies, however, this synchronization mechanism is not provided by the standard and, if required by specific applications, needs to be implement at upper layers. The MAC layer defines four different types of frames: beacon frames, acknowledgement frames, MAC command frames, and data frames. Beacon frames are used in the synchronization mechanism. Acknowledgement frames, whose use is optional, are used to acknowledge transmissions. MAC command frames carry protocol commands, such as “Association request”, or “Data request”. Finally, data frames are used for all transfers of data. Figure 2.3 illustrates the structure of a data frame. octets: 2 1 4 to 20 n2 MAC layer FCF Sequence Number Addressing fields Data Payload FCS octets: 4 1 1 . . .9 to 127 . . . PHY layer Preamble Sequence SFD Frame Length MPDU Figure 2.3: IEEE 802.15.4 data frame Preamble Sequence Used to obtain chip and symbol synchronization with an incoming message. It is composed of 32 binary zeros. SFD Start of Frame Delimiter. Indicates the end of the preamble and the start of the packet data. It has constant value of 0xE5 (22910). Frame Length Length of the MAC protocol data unit (MPDU). FCF Frame Control Field. Contains information defining the frame type, addressing modes, and other control flags. Sequence Number Used to match acknowledgement frames to data or MAC command frames Addressing Fields The IEEE 802.15.4 standard supports short (16 bit) and long (64 bit) address. In addition, if the source and destination PAN identifiers are the same, one of them can be elided. Hence, this field containing the source and destination addresses as well as the source
2.4. INTERNET PROTOCOL 11 and destination PAN identifier, has variable length, and it is to be interpreted according to the FCF. Data Payload The data being transmitted. FCS Frame Check Sequence for data integrity verification. 2.4 Internet Protocol The Internet Protocol (IP) is the principal Internet Layer protocol. It is a connectionless, best-effort, unreliable internetworking protocol which provides the necessary functions to deliver a packet from a source to a destination (both identified by fixed length addresses) over a system composed of an arbitrary number of networks. It also provides mechanisms for packet fragmentation and reassembly, if necessary. The Internet Protocol was first defined by Vint Cerf and Robert Kahn in an IEEE journal paper entitled “A Protocol for Packet Network Interconnection” [12]. The protocol was later revised and updated up to its fourth version (IPv4), which is defined in RFC 791 [39], and became the first widely deployed version of IP. 2.4.1 IPv4 Internet Protocol version 4 (IPv4) is defined in RFC 791 [39] (replacing its previous definition in RFC 760 [38]). It uses 32-bit addresses, which limits the total number of IPv4 addresses to 232. Tts header has variable length (due to the options field), as illustrated in Figure 2.4 and described below. These two features (address length are variable length), together with the need for Flow Labelling capability constitute the main shortcomings/limitations of the protocol, and hence the reasons that have made necessary the definition of its next version (version 6). These features are explained in more detail in Section 2.4.2. Version Internet Protocol version. It has a value of 4 for IPv4. IHL Internet Header Length in multiples of 4 bytes. It is required since the header may contain a variable number of options. Type of Service The Type of Service (ToS) field provides an indication of the parameters of the quality of service desired. It is used to specify the treatment of the datagram during its transmission. RFC 2474 [35] redefines this field as the “Differentiated Services field” (DS field)
12 CHAPTER 2. BACKGROUND 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Version IHL Type of Service ECN Total Length Identification Flags Fragment Offset Time to Live Protocol Header Checksum Source Address Destination Address Options Padding Figure 2.4: IPv4 datagram header. Light grey coloured fields are optional. due to the limited practical use of the Type of Service field and the need for a new field by new real-time protocols. ECN Explicit Congestion Notification (formerly part of ToS). Total Length The total length of the packet, including the variablelength header. This field is needed to calculate the payload length, and imposes a maximum total packet length of 216 −1= 65,535 bytes. Identification Numeric identifier used to uniquely identify a set of fragments belonging to the same packet. Flags Used for fragmentation control, indicating whether a fragment is the last fragment or not of a packet, or if fragmentation is allowed for a packet. Fragment Offset Specifies the offset of a fragment relative to the beginning of the original packet. This field is required for packet reassembly. Time to Live Sets a maximum packet lifetime, to prevent packets from persisting in the network due to, for example, routing loops. Protocol Indicates the protocol of the packet encapsulated by the IP header and transported in the IP payload. Header Checksum 16-bit checksum field, used for header error-checking. Source Address 32-bit IP address of the source of the datagram Destination Address 32-bit IP address of the destination of the datagram
2.4. INTERNET PROTOCOL 13 Options Optional field. It can contain a list of different options, but it must always be terminated with an “End of Options” option. Padding Since the number of options is variable and the length of each option is also variable, and the header length field (IHL) is expressed in 32-bit multiples, padding is needed to ensure that the header contains an integral number of 32-bit words. 2.4.2 IPv6 The IP protocol version 6 (IPv6) is defined in RFC 2460 [15] (replacing its previous definition in RFC 1883 [14]). It was defined in 1998 in order to succeed IPv4, with the goal of overcoming a number of IPv4 shortcomings, especially, for dealing with the anticipated IPv4 address exhaustion. The primary changes from IPv4 to IPv6 are an increased address space, which is 128 bits (allowing for up to 2128 — about 3.4×1038) different IPv6 addresses), a simplified header format, with includes a fixed header-length and improved support for extension headers and options (allowing for more efficient packet forwarding and greater flexibility for introducing new options), flow labelling capability (with which the sender is allowed to request special handling by routers), and authentication and privacy capabilities. The IPv6 header format is described below and illustrated in figure 2.5. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 Version Traffic Class Flow Label Payload Length Next Header Hop Limit Source Address Destination Address Figure 2.5: IPv6 datagram header Version Internet Protocol version. It has a value of 6 for IPv6.
14 CHAPTER 2. BACKGROUND Traffic Class Identifies different priorities. Flow Label Used by the source to label sequences of packets for which it requires special handling by routers, such as a non-default quality of service or “real-time” service. This field replaces the “Type of Service” field in IPv4. Payload Length Length of the IPv6 packet payload, not including the length of the header (40-bytes fixed length). Note that extension headers, if present, are considered part of the payload. Next Header Identifies the type of header immediately following the IPv6 header. This next header may indicate any upper-layer protocol or an IPv6 extension header. Hop Limit Packet lifetime. Used to prevents packets from indefinitely persisting in the network. It is specified as a number of hops (in contrast to the “Time to Live” IPv4 field, which is specified in seconds, requiring nodes to perform difficult time computations), which is decremented at every node where the packet is forwarded. Source Address 128-bit IP address of the source of the datagram Destination Address 128-bit IP address of the destination of the datagram 2.5 The Internet of the Things The Internet of Things [32] is a paradigm which aims to provide everyday objects with a unique address, enabling their integration into the Internet. These objects are expected to provide contextual information and/or perform certain actions, according to their own interpretation of context and/or the orders received from remote hosts. This fact makes IPv6 (especially, its extremely large address space) a perfectly suited protocol for its use in the identification and communication between these objects and the rest of the Internet. It is important to note that these objects do not require special capabilities: since a unique bar code or unique identifier in a radio-frequency identification (RFID) tag is sufficient to provide a unique identifier to an object, enabling every object to be identified and hence, integrated into the the Internet. However, the more processing capabilities the object has, the wider its communication capabilities will be; while some of these objects may have a read-only RFID tag (which may inform others of the object’s location
2.6. 6LOWPAN 15 when passing RFID readers located in known places), other “things” might implement a fully-compliant IPv6 protocol stack, becoming “first-class Internet citizens” capable of sending and receiving information to and from the Internet, just as any other network attached computer might. Between these two extremes, a vast range of possibilities exists, in which each object is required to implement only the minimum features necessary for its specific application. Therefore, the Internet of Things concept provides for a large set of applications such as home automation, security, monitoring, smart metering, and management among others, providing the means to transform their environments into a smart, context-aware entity with the ability to sense and act. Consequently, these applications target many different markets, from individuals or families to industry. 2.6 6LoWPAN 6LoWPAN is an intermediate layer that allows the transport of IPv6 (see Section 2.4.2) packets over IEEE 802.15.4 (see Section 2.3) frames. Although the term 6LoWPAN stands for IPv6 over Low-power Wireless Personal Area Networks, it may extend the personal operating space, similar to LR-WPANs. RFC 4919 [30] describes an overview, assumptions, problem statement, and goals, while RFC 4944 [33] defines the standard itself. Figure 2.6 depicts how an IPv6 packet is encapsulated into a IEEE 802.15.4 frame using the 6LoWPAN adaptation layer. The IPv6 standard defines certain requirements for the link-layers over which it is to be transported. However, the IEEE 802.15.4 MAC layer does not fulfil these requirements in certain points. Hence, the 6LoWPAN specification defines not only the frame format for the transmission of IPv6 packets over IEEE 802.15.4, but also the mechanisms to obtain a unique IPv6 address from either, 16-bit or 64-bit IEEE 802.15.4 MAC addresses (using Stateless Address Autoconfiguration—defined in RFC 4862 [47]), and to overcome the limitations of IEEE 802.15.4 [4]. IPv6 layer . . .IPv6 packet . . . 6LoWPAN layer . . .6LoWPAN packet . . . MAC layer IEEE 802.15.4 frame Figure 2.6: 6LoWPAN Intermediate layer
22 CHAPTER 2. BACKGROUND 2.9.2 Neighbor Discovery Optimization for LLNs The Neighbor Discovery Optimization for Low power, Lossy Networks (6LoWPAN-ND) is a set of modifications of IPv6-ND rather than a new protocol. These modifications were introduced in I-D.ietf-6lowpan-nd [43]. The main goal of these modifications is to optimize Neighbor Discovery for power-constrained devices that may utilize non-transitive links. A secondary goal is to provide support for certain features required in 6LoWPAN networks, such as the context propagation feature to enable the use of context-based IPv6 Header Compression [27]. 2.9.2.1 6LoWPAN Neighbor Discovery messages The message types in 6LoWPAN-ND remain the same, with the following exceptions: •3 new options are introduced: Address Registration option (ARO), 6LoWPAN Context Information option (6CO), and Authoritative Border Router option (ABRO). ARO is mandatory, while 6CO and ABRO are optional. •2 new optional message types are introduced: Duplicate Address Request (DAR) and Duplicate Address Confirmation (DAC). •Redirect messages are not used in route-over topologies. Table 2.3 shows the message types and options used in 6LoWPAN-ND. 2.9.2.2 6LoWPAN-ND Protocol Overview During interface initialization, hosts send up to MAX_RTR_SOLICITATIONS (3 by default) RS messages in order to discover routers. In response, routers send RAs which may include, in addition to other options such as the Prefix Information option (PIO), one or more 6LoWPAN Context options (6COs), and an Authoritative Border Router option (ABRO). Note that both RS and RA must also carry a Source Link-Layer Address option (SLLAO) [43]. If IEEE’s 64-bit Extended Unique Identifier (EUI-64) based addresses are used, DAD is not required. Otherwise, DAD is performed via the new Address Registration feature and, optionally, using the new multihop DAD by means of DAR and DAC messages. The Address Registration feature is performed by sending NS and NA messages carrying the new ARO option, i.e., a host sends a unicast NS with the ARO option to the router(s). The ARO contains the EUI-64 of the sending interface, in order to uniquely identify it, and a registration lifetime. A router that receives such a NS message, tries to register the address in its Neighbor Cache (NC). If there is no other node using the same IPv6
2.9. NEIGHBOR DISCOVERY 23 Table 2.3: 6LoWPAN-ND message types. New message types and options in red. Message type Possible options 6LoWPAN-ND message purpose RFC 4861[34] I-D.ietf-6lowpan-nd [43] Neighbor Solicitation (NS) SLLAO, ARO Address Registration, Neighbor Unreachability Detection §4.3 §4.1 Neighbor Advertisement (NA) TLLAO, ARO Response to NS, New information propagation §4.4 §4.1 Router Solicitation (RS) SLLAO Prompt routers to generate Router Advertisement messages §4.1 - Router Advertisement (RA) SLLAO, MTU, PIO, 6CO, ABRO Prefix, context and link-parameter dissemination §4.2 §4.2; §4.3 Duplicate Address Request (DAR) -Perform multihop duplicate address detection §4.5 §4.4 Duplicate Address Confirmation (DAC) -Response to DAR §4.5 §4.4 address in the NC, then the registration succeeds and the router creates a new Neighbor Cache Entry (NCE) which will remain valid until the lifetime expires. In contrast, if this IPv6 address was in use by another node (with a different EUI-64) or if there is no space in the NC for the new entry, then the registration fails. In both cases a NA containing the same ARO option will be
24 CHAPTER 2. BACKGROUND sent in response, along with the corresponding status value. The status value informs the node trying to register its address of the result of its registration attempt. If the optional multihop DAD feature is implemented, then this last step may take a bit longer as a 6LoWPAN Router (6LR) that receives a NS including an ARO from an IPv6 source address not in its NC, will send a DAR message to the 6LoWPAN Border Router (6LBR). If the 6LR receives a positive DAC in response to its DAR, it will send back a NA with the corresponding ARO and status value to the node that originated the NS. Hosts (and 6LRs) need to periodically refresh their NCEs in the routers by re-sending a NS with an ARO specifying a new lifetime. Note that this registration attempt also confirms that the destination routers are still reachable and therefore is used also for Neighbor Unreachability Detection (NUD). In 6LoWPAN-ND, hosts do not perform address resolution. Thus, when a host wants to send a packet, this packet is always sent via a router. The router will determine whether the destination node is reachable or not, according to its NC. This means that the router is the only direct neighbor for each host. 2.9.3 IPv6-ND vs. 6LoWPAN-ND This section describes the differences in the IPv6-ND operations that the 6LoWPAN-ND optimizations introduce and highlights the differences with the greatest impact in terms of compatibility between the two protocols. 2.9.3.1 Differences The optimizations introduced by I-D.ietf-6lowpan-nd [43] are enumerated below and the differences with respect to IPv6-ND are described in Table 2.4. 1. Host-initiated interactions to allow for sleeping hosts. 2. Elimination of multicast-based address resolution for hosts. 3. A host address registration feature using a new option in unicast Neighbor Solicitation and Neighbor Advertisement messages. 4. A new Neighbor Discovery option to distribute 6LoWPAN header compression context to hosts. 5. Optional multihop distribution of prefix and 6LoWPAN header compression context. 6. Optional multihop duplicate address detection using two new ICMPv6 message types.
2.9. NEIGHBOR DISCOVERY 25 Table 2.4: 6LoWPAN-ND optimizations and differences regarding IPv6-ND. # 6LoWPAN-ND optimization IPv6-ND behavior 6LoWPAN-ND behavior 1 Host-initiated interactions to allow for sleeping hosts Routers send periodic RAs and hosts send multicast NS between them RAs sent mainly in response to RSs; NSs are not sent between hosts 2 Elimination of multicast-based address resolution for hosts Hosts multicast NSs to perform address resolution All communication between hosts is via routers 3 New host address registration feature using a new option in unicast NSs and NAs DAD, NUD, and Address Resolution performed as specified in [34] and [47] The address registration feature provides support for DAD, NUD, and Address Resolution. 4 New Neighbor Discovery option to distribute context information Not used Context information is disseminated by 6CO options in RAs 5 Optional multihop distribution of prefix and context information Not used Enhances the distribution of prefix and enables dissemination of context information 6 Optional multihop duplicate address detection DAD performed as specified in [47] Provides support for non-EUI-64 based addresses in route-over topologies 2.9.3.2 Incompatibilities Some of the differences mentioned in section 2.9.3.1 require special attention due to the incompatibilities they introduce. An attempt to internetwork 6LoWPAN and IPv6 networks (each of them running their corresponding ND protocol) without handling these incompatibilities in a proper way would result, at best, in a misuse of the ND protocol while, in most cases, this communication would be impossible. Of these differences, #1, #2, and #3 are the most significant. In IPv6-ND address resolution is performed by (multicasting) NS and NA messages. In contrast, address resolution is not performed by 6LoWPAN hosts (although routers may do address resolution). 6LoWPAN hosts do not even join the
26 CHAPTER 2. BACKGROUND Solicited-node multicast address; instead, they register with routers by means of the address registration feature (#3). When a host needs to send a packet, the packet is delivered via a 6LoWPAN Router (6R) that is aware of the target’s link-layer address due to this node’s current registration. Moreover, non-constrained devices (NCDs) trying to deliver a packet to a neighboring 6LoWPAN host would first multicast a NS message to the destination’s Solicited-Node multicast address for Address Resolution. As 6LoWPAN hosts do not join the Solicited-Node multicast group, they will not be listening to this address, hence the NS will not be answered, therefore the NCD would assume that the destination is unreachable. Furthermore, DAD is also performed in IPv6-ND by sending a Neighbor Solicitation message to the Solicited-node multicast address (as described in Section 2.9.1). However, no host in the 6LoWPAN network will respond to a message sent to this multicast address and thus, a NCD would never detect whether another 6LoWPAN host has the same IPv6 address it is trying to use. In contrast, I-D.ietf-6lowpan-nd states that either DAD is not needed (if EUI-64 based IPv6 addresses are used) or multihop DAD is used (if there are non-EUI-64 based addresses in a route-over topology). Note that this assumes that the EUI-64 based IPv6 address will be unique. Section 3.2 examines some of the other assumptions that I-D.ietf-6lowpan-nd makes. 2.10 What have others already done? This section describes a number of related works. This related work is divided into to neighbor discovery proxies and background material about Contiki (as this open source software will be used in the developments reported in this thesis). 2.10.1 Neighbor Discovery proxies The concept of Neighbor Discovery proxies is not original; previous work has described some specifications of ND proxies. The proxy operations described in this thesis were highly influenced by two specific documents: “Neighbor Discovery Proxies” (RFC 4389) [46] and “6LoWPAN Backbone Router” (draft-thubert-6lowpan-backbone-router) [48]. RFC 4389 describes the required proxy operations for some special cases when bridging different types of media requires network-layer support. Although our case also involves bridging two different types of media and such bridging requires network-layer support (mainly link-layer address translation in ND messages), the reasons that make the use of a proxy necessary in our scenario are significantly different that those described in RFC 4389. Specifically, the use of a proxy is necessary in our case because each interface of the 6LP-GW is attached to a network segment that utilizes a different
2.10. WHAT HAVE OTHERS ALREADY DONE? 27 ND protocol and, more importantly, these protocols are incompatible. In contrast, the Neighbor Discovery Proxies specified in RFC 4389 considers the same Neighbor Discovery protocol on all interfaces. The Internet Draft “6LoWPAN Backbone Router” describes a situation very similar to ours. In particular, the scenario depicted in this internet draft consists of several small 6LoWPAN LLNs connected to a transit link (Ethernet) by means of a backbone router per LLN. Such backbone routers perform Neighbor Discovery proxying between the 6LoWPAN networks and the Ethernet transit link. Figure 2.8 illustrates the scenario presented in draft-thubert-6lowpan-backbone-router. Plant Network Gateway Transit Link Backbone router Backbone router Backbone router LLN LLNLLN Figure 2.8: Backbone Routers scenario While some of the proxy mechanisms described in “6LoWPAN Backbone Router” are similar to the ones described in this thesis (see Section 3.2), others differ significantly or are out of the scope of one or the other document. The most important difference between the 6LoWPAN backbone router and the 6LP-GW is that the former performs network-layer routing between its two interfaces, whilst the latter neither routes packets nor performs internetlayer forwarding, but rather operates as a bridge (although it requires networklayer support in certain situations). Moreover, while a 6LoWPAN backbone router defines an IPv6 subnet, the 6LP-GW does not, but rather it is the port of the IPv6 router (which the 6LP-GW connects to) that defines the subnet.
28 CHAPTER 2. BACKGROUND Figure 2.9 illustrates this difference. 6LBR 6LoWPAN - IPv6 subnet NCD - IPv6 subnet Internet IPv6 Router Internet IPv6 subnet 6LP-GW 6LoWPAN nodes NCD nodes Figure 2.9: 6LBR vs. 6LP-GW. The figure illustrates the differences in the topology derived from the use of a 6LBR (left) or a 6LP-GW (right). Note that the use of a 6LBR necessarily causes the creation of a new IPv6 subnet, while all the nodes in the network in which the 6LP-GW operate share the same network prefix. Furthermore, 6LoWPAN backbone routers are required to operate as a “distributed database of all the LLN nodes”, while the 6LP-GW maintains a strictly local database of the LLNs within the 6LoWPAN it is connected to. The reason for this is that there is no requirement that the 6LP-GW acts as a mobility anchor. These differences have their roots in the different problems each device addresses; while a “6LoWPAN Backbone Router” aims to provide scalable support for mobility of 6LNs between LLNs without requiring them to register with each LLN’s 6LBR, the 6LP-GW proposed in this thesis aims to integrate 6LoWPAN LLNs into existing IPv6 infrastructures without requiring a single change in the existing network infrastructure. This allows the end-user to literally “attach” a 6LoWPAN LLN to her/his existing IPv6 router. In contrast the “6LoWPAN Backbone Router” approach cannot be used in some settings, for example most home IPv6 routers preclude intra-LAN routing. In conclusion, while the solution proposed in “6LoWPAN Backbone Router” targets mobility and scalability in large installations (such as in office
2.10. WHAT HAVE OTHERS ALREADY DONE? 29 buildings and/or industrial plants) without considering the problem of home routers, the implementation proposed here (using the 6LP-GW) aims for rapid deployment of 6LoWPAN networks at low cost, which involves allowing reutilization of existing home routers, but leaves mobility issues out of scope. Section 6.2, however, provides guidelines for enabling the same mobility support as provided by draft-thubert-6lowpan-backbone-router while still not requiring intra-LAN routing (and hence allowing the use of home routers). It should also be noted that 6LP-GWs can also be attached to multiport Ethernet switches, enabling their use in settings with such switches. A Power over Ethernet version of the Ethernet interface of the current hardware prototype platform in which the 6LP-GW is implemented (Hogaza board v1.2 [50]) is being designed in a companion Bachelor’s thesis project [22]. 2.10.2 The Contiki Operating System Contiki is an open source lightweight platform-independent operating system for embedded platforms written in the C programming language. Although it lacks certain features expected to be present in any operating system (for example, it does not provide hardware management functions), it provides a powerful and richly-featured framework for embedded system development. Among its main features, Contiki provides a memory-efficient abstraction mechanism for multitasking-like process development called protothreads [21] controlled by a simple event-driven kernel, different libraries for memory allocation and management, message-passing-based interprocess communication, and fully-compliant and lightweight IPv4 and IPv6 communication stacks, including a 6LoWPAN implementation. 2.10.2.1 Contiki’s protothreads Protothreads [21] are a programming abstraction that provides a functionlevel conditional blocking wait statement: PT_WAIT_UNTIL(). Conceptually, PT_WAIT_UNTIL() blocks the executing function —protothread— until a condition (passed as parameter) evaluates to true. This relatively simple abstraction allows programmers to structure their entire application as a set of independent processes, rather than a large monolithic one, thus improving scalability, maintainability, and manageability of the code. Protothreads are intended to simplify event driven programming, which usually consist of a state machine. Such a state machine is traditionally implemented by a large infinite loop with a conditional switch statement inside it. Figures 2.10 and 2.11 (on pages 31 and 32 respectively) illustrate two different implementations of state machines, comparing the traditional loop-switch and protothreads approaches. Protothreads are built on top of an underlying mechanism called local continuations. Local continuations can be seen simply as a means to store
30 CHAPTER 2. BACKGROUND the state of a protothread. Local continuations can perform two operations: set and resume. A set operation stores the current position at which it is invoked, whereas a resume operation causes the program to jump to the point previously stored in the local continuation (the point at which the set operation was invoked). Hence, we can consider protothreads as C functions which utilize local continuations to alter their normal execution flow. When the execution reaches a PT_WAIT_UNTIL() statement, a set operation is performed. If the condition passed as parameter of the PT_WAIT_UNTIL() is met, then the function continues executing; otherwise, the control is returned to the caller function (i.e., the program jumps to the end of the function). The return value which is produced in this case, informs the caller function that the protothread has not finished, but rather that it is waiting for something. The next time the protothread is invoked, a resume operation is performed, causing the program to jump to the previously stored position and to reevaluate condition. Note that the use of protothreads requires the presence of a scheduler function, which can be as simple as an infinite loop in which all the protothreaded functions are called sequentially. In addition to the PT_WAIT_UNTIL() statement, [21] also defines other useful local-continuation- based mechanisms, such as the PT_YIELD(). The PT_YIELD() statement performs a single unconditional blocking wait, which causes the protothread to unconditionally return the control to the caller. The next time the protothread is executed, it will continue its execution from the point where PT_YIELD() was invoked. Regarding the C implementation, protothreads are implemented by means of macros that expand to a set of instructions which perform the operations of local continuations (set and resume) and, optionally, evaluate conditions [21]. Local continuations can be implemented in two different ways: using the Labels as Values GCC compiler extension (which allows storing labels in variables) together with goto statements, or relying on standard C switch statements together with the standard __LINE__ macro (which expands to the number of the line at which __LINE__ is used). The former leads to slightly better results in terms of code size and speed, but it depends on the availability of the GCC compiler for a certain architecture, while the latter can be utilized together with any standard C compiler. 2.10.2.2 Contiki’s kernel In order to explain how the Contiki kernel works, we introduce the Contiki process concept. Contiki’s protothreads are wrapped within the process structure (C struct). This process structure stores a protothread’s context information, such as the process name, a pointer to the protothreaded function, the protothread itself (containing its local continuation), the process state, and
2.10. WHAT HAVE OTHERS ALREADY DONE? 31 state : { GREEN , AMBER , RED } void semaphore () { state = GREEN // set initial state light ( GREEN ) timer_set ( GREEN_TIMER ) while (1) { switch ( state ) { case ( GREEN ): if ( timer_expired ( GREEN_TIMER ) || pedestrian_button_pressed()) { state = AMBER light ( AMBER ) timer_set ( AMBER_TIMER ) } case ( AMBER ): if ( timer_expired ( AMBER_TIMER )) { state = RED light ( RED ) timer_set ( RED_TIMER ) } case ( RED ): if ( timer_expired ( RED_TIMER )) { state = GREEN light ( GREEN ) timer_set ( GREEN_TIMER ) } } } } State machine implemented using a traditional loop-switch mechanism. pt_semaphore: PT_BEGIN while (1) { light ( GREEN ) timer_set ( GREEN_TIMER ) PT_WAIT_UNTIL ( timer_expired ( GREEN_TIMER ) || pedestrian_button_pressed()) light ( AMBER ) timer_set ( AMBER_TIMER ) PT_WAIT_UNTIL ( timer_expired ( AMBER_TIMER )) light ( RED ) timer_set ( RED_TIMER ) PT_WAIT_UNTIL ( timer_expired ( RED_TIMER )) } PT_END State machine implemented using the protothreads abstraction mechanism. Figure 2.10: Example of the same state machine implemented using traditional loop-switch statements (left) and Contiki protothreads (right), both in pseudocode. This state machine represents the operation that controls the state transitions in a hypothetical street semaphore provided with a button that can be pressed by pedestrians to trigger a transition from green-light state to amber first and, eventually red-light state (for the cars that are flowing perpendicular to the pedestrian. a boolean variable which indicates whether the process has requested a poll from the kernel. This kernel is event-driven, which means that the process to be called next is chosen depending on whether a process has any pending event. This approach implies that, a process whose protothread has performed a PT_WAIT_UNTIL(condition) or PT_YIELD() statement, will not continue its execution unless another process posts an event addressed to it or if it has actively requested to be polled by the kernel before executing the blocking statement. This approach does not take advantage of the variety of returning values implemented by the protothreads mechanism [21] and requires the programmer to ensure that no process will enter a permanent sleep state, but it ensures that processes are not unnecessarily checked repeatedly if they
38 CHAPTER 3. METHOD 3.2.1 Proxy Operation overview The 6LP-GW together with the RR will be seen from the 6LoWPAN side as a 6LBR. In contrast, from the IPv6 side, it is impossible to distinguish between NCDs and 6LoWPAN nodes. Regarding forwarding, the 6LP-GW has to both keep track of which node is in each segment and apply the required link-layer address translation between IEEE 802.15.4 and Ethernet addresses. Note that the 6LP-GW is invisible for any of the link segments it internetworks, meaning that it does not need to have either an IPv6 address or a MAC address for the purpose of acting as a proxy or gateway. However, the device considered here has both IPv6 and MAC addresses associated with its Ethernet interface. These addresses could be used for management and/or monitoring of the device (including loading new software into it, node association, etc.) or the network (number of nodes, traffic, etc.), but this functionality lies outside the scope of this thesis. In addition, some ND options carry link-layer addresses (mainly SLLAO and TLLAO). Packets containing these option require extra processing in order to translate from 48-bit MAC addresses into 64-bit MAC addresses and viceversa, depending on which segment these packets originate from. Moreover, 6LoWPAN features such as decompression and compression are performed by the 6LP-GW on incoming and outgoing packets when appropriate. Therefore, to enable the operations described here, every packet reaching the 6LP-GW, regardless of the segment where it originated, shall be processed as required, applying the corresponding compression/decompression operations. Note also that the proxy mechanisms described below consider only the case of packets traversing from one segment to the other. The 6LP-GW does not forward unicast packets directed to the same segment they came from. In all cases, validity checks of the incoming ND messages will be performed as specified in the corresponding ND specification. The specific way to process a ND message will depend on which segment it originates from and will be explain in later sections. 3.2.2 Conceptual datastructures and Initialization In addition to the data structures required for the forwarding mechanism, the 6LP-GW needs to maintain a Neighbor Cache (NC) just as if it were a 6LR (or 6LBR). The maintenance procedures for this cache extend those described in I-D.ietf-6lowpan-nd [43]. This means that the 6LP-GW has to create/refresh entries when receiving Neighbor Solicitation messages (NS) and it must also remove Neighbor Cache Entries (NCEs) when their registration lifetime expires. Receiving an ARO with zero lifetime will cause the 6LP-GW to immediately delete the corresponding NCE.
3.2. PROXY OPERATION SPECIFICATION 39 In addition to the information expected to be contained in every NCE, this specification requires the inclusion of the following elements: an ARO- pending flag, an awaiting-RA flag, and a Duplicate Address Detection (DAD) timer. The meanings of these variables will be explained later in this section. Furthermore, as context-based header compression is used, the 6LP-GW also needs to perform context information maintenance and dissemination just as if it were a 6LBR. At bootstrapping, the 6LP-GW initializes all the data structures needed to create and maintain both a NC and the Context information table. 3.2.3 Packet Forwarding The 6LP-GW’s main purpose is to forward IPv6 packets originated in one segment to the other segment. Since its operation is transparent from both segments’ standpoint, the 6LP-GW has to promiscuously listen to the physical media. Therefore, it needs a suitable forwarding mechanism in order to determine whether a packet’s destination lies on a different segment than the one where it originated (and, hence, must be forwarded) or its destination is on the same segment it was sent from (so the 6LP-GW simply drops the packet). The mechanism chosen for this operation is a very simple approach to bridging [1]: The 6LP-GW maintains a bridge table in which each entry is a pair <MAC address, interface>. For every incoming packet, it checks whether the source MAC address is stored in the bridge table; if it is not, the pair <source MAC address, incoming interface> is added to the bridge table. Next, it checks the destination MAC address: if it is a multicast address, or a unicast address not having a matching entry in the bridge table, it is forwarded to every interface, but the incoming interface; if it is a unicast address and there is a corresponding entry in the bridge table, then the packet is forwarded to the interface associated with it. For maintenance of this table, a least recently used (LRU) policy is applied in order to replace old entries by new ones when the table is full. This behaviour is illustrated in Figure 3.2.
40 CHAPTER 3. METHOD Packet arrives Is source address in bridge table? Yes No Add pair (source, interface) to the bridge table Is destination address in bridge table? Yes No Forward to every interface except the incoming interface Forward to the interface associated to destination address Is destination address unicast? Yes No Incoming packet Figure 3.2: The 6LP-GW Forwarding mechanism In addition, an appropriate MAC translation mechanism has to be applied when required, since IEEE 802.15.4 MAC addresses are 64 bits long while IEEE 802.3 MAC addresses are 48 bits long. The IEEE standard document “Guidelines for 64-bit Global Identifier (EUI-64™) Registration Authority” [6] defines a simple and convenient EUI-48 to EUI-64 mapping which perfectly addresses this application’s needs. This mechanism consists of inserting the constant value 0xFFFE16 between the company identifier (i.e., the 3 left-most bytes of the EUI-48) and the manufacturer-selected extension identifier (i.e., the 3 right most bytes of the EUI-48). Figure 3.3 illustrates how an EUI-48 is encapsulated into an EUI-64 MAC address. field: Company identifier . . .Extension identifier EUI-48 A BB CC 11 22 33 ⇓ field: Company identifier . . .EUI label . . .Extension identifier EUI-64 A BB CC FF FE 11 22 33 Figure 3.3: EUI-48 Encapsulated in EUI-64
3.2. PROXY OPERATION SPECIFICATION 41 As for the particular case of the 6LP-GW, every MAC address is considered to be 64-bits long. Ethernet MAC addresses are converted into their corresponding 64-bit MAC address as soon as an Ethernet packet arrives at the 6LP-GW and, only in the very final step of sending a packet out from the 6LP-GW, it is checked whether the segment where the packet is to be sent operates with 48 or 64-bit addresses. On the other hand, all the IEEE 802.15.4 MAC addresses used in our experimental deployment have their fifth and fourth least significant bytes being 0xFFFE. Although this approach simplifies the link-layer address translation procedure, it must be noted that the IEEE registration authority forbids this practice (64-bit values of the form ccccccFFFEeeeeee are never assigned). An approach suitable for a commercial product could use a simple table in order to keep track of the IEEE 802.15.4 addresses in the network and remove/insert the fifth and fourth least significant bytes of addresses in the outgoing/incoming packets directed to or arriving from the Ethernet segment. However, this and other approaches are outside the scope of this thesis. Applying the link-layer address translation mechanism described above means that further processing (bridging, proxy operation, host operation, etc.) does not require taking into account the link-layer address length nor its origin; all addresses are 64-bit long and all of them have their fifth and fourth least significant bytes being 0xFFFE. 3.2.4 Proxy operation This section describes in detail the ND-proxy’s conceptual operation performed by the 6LP-GW. All the operations described in this section are applied only to ND packets arriving at the 6LP-GW; non-ND packets will be forwarded as described in Section 3.2.3. 3.2.4.1 Processing Neighbor Solicitation Messages The Neighbor Solicitation messages that reach the 6LP-GW may have been originated for different purposes. The appropriate way to process them depends on this purpose and it will differ depending on their origin and their structure. Figure 3.4 shows the different types of Neighbor Solicitation messages that may arrive at the 6LP-GW. Neighbor Solicitation originating in IEEE 802.15.4 segment As Figure 3.4 shows, we distinguish three different types of possible NS messages that can arrive from the IEEE 802.15.4 segment: multicast NS and unicast NS (with/without ARO).
42 CHAPTER 3. METHOD IEEE 802.3 IEEE 802.15.4 Unicast NS Unicast NS (no ARO) Multicast NS Unicast NA Unicast NA 6LP-GW Unicast NS Multicast NS Unicast NS Multicast NS Multicast NS Unicast NS (ARO) Multcast NA Figure 3.4: NS message processing. Incoming NS messages are connected by arrows to the Neighbor Discovery messages that may be generated in response. The dashed arrows represent conditional responses. Multicast NS A multicast NS originated in the IEEE 802.15.4 can only have the purpose of performing address resolution. As per Section 2.9.2 6LoWPAN hosts (6Hs) do not perform address resolution, but 6LoWPAN Routers (6Rs) may optionally do so. However, these multicast NS messages have the sole purpose of discovering the link-layer address of other 6Rs. As no 6R is present in the IEEE 802.3 segment apart from the one that is formed by the RR together with the 6LP-GW (as previously said, they are together seen from the IEEE 802.15.4 segment as a 6LBR), hence the 6LP-GW will proceed as follows: upon reception of a multicast NS message originating in the IEEE 802.15.4 segment, the 6LP-GW will examime its target address; if it matches the RR’s IPv6 address, the packet will be forwarded unchanged (apart from the appropriate MAC translation); otherwise the packet will be discarded. Unicast NS not containing an ARO option As defined in RFC 4861, unicast NS without ARO messages are sent as probes to test for reachability. 6Hs do not maintain Neighbor Cache Entries (NCEs) for other hosts, but only for 6Rs. Therefore it is unlikely that any 6H sends a unicast NS to any node other than a 6R. However, we should keep in mind that the 6LP-GW together with the RR will be seen from the 6LoWPAN link as a 6LBR and thus, this 6LBR has to respond to such NS messages. Regarding 6Rs, nothing in I-D.ietf-6lowpan-nd precludes 6R’s from sending this type of message to any other node in the network. Therefore, a unicast NS message
3.2. PROXY OPERATION SPECIFICATION 43 not containing an ARO option must be forwarded to the IEEE 802.3 interface unchanged (apart from the appropriate MAC translation). Unicast NS containing an ARO option Unicast NS messages containing an ARO option are sent fot two purposes: (1) as part of the 6LoWPAN-ND registration procedure and (2) to perform NUD (to determine the reachability of the router to which they are sent). As these messages are only sent to 6Rs, and the 6LP-GW together with the RR is seen as a 6LBR, it is likely that the 6LP-GW will receive such messages having as their destination IPv6 address the RR’s IPv6 address. Therefore, the 6LP-GW performs the normal operations of a 6R when receiving this type of message directed to the RR, i.e., the NS message must be processed as specified in section 6.5 of I-D.ietf-6lowpan-nd in terms of validity and the NC maintenance procedure, but with some differences as will be explained below. Should the IPv6 destination address of a NS message including an ARO not match the RR’s IPv6 address, then the packet will be discarded. If, for some reason, the RR’s IPv6 address is unknown when the NS arrives, then the packet will also be discarded. On the other hand, RFC 4861 requires every node in the IPv6 network to perform duplicate address detection (DAD). Therefore, performing DAD on behalf of 6LoWPAN nodes that are to be integrated into the IPv6 link is necessary in order to comply with the specification. On the other hand, 6LoWPAN-ND only requires performing DAD when non-EUI-64-based IPv6 addresses are being used in the network. As previously stated in Section 3.1.1, the 6LoWPAN nodes present in our scenario will only make use of EUI-64- based IPv6 addresses (either “real” EUI-64 or EUI-48 encapsulated into EUI- 64), hence nodes in the IEEE 802.3 segment need not perform DAD in the IEEE 802.15.4 segment. For the above reasons, the 6LP-GW must perform not only the registration procedure, but also DAD (in the IPv6-ND way on the IEEE 802.3 interface) and NUD when receiving a unicast NS with an ARO option. Both operations (DAD and NUD) are performed on behalf of the 6LoWPAN node that is trying to register its address. In order to perform DAD, the 6LP-GW must send a NS, formatted as explained in Section 2.9.1.2, to the Solicited-node multicast address corresponding to the source address of the incoming NS. For NUD, the NS message originated in the IEEE 802.15.4 segment should be forwarded to the IEEE 802.3 segment so a subsequent NA response will confirm the reachability of the router. Unfortunately, DAD is an expensive process as it takes a long time to wait for messages that are not going to receive responses [51] and it can not be performed in parallel with NUD due to the risk of duplicate addresses. As waiting for both to complete sequentially may delay the autoconfiguration
44 CHAPTER 3. METHOD process excessively, we choose to perform DAD only upon registration and then, NUD upon re-registration. Figure 3.5 describes the complete address registration procedure and Section 3.2.4.1 details how DAD is performed. Unicast NS with valid ARO and SLLAO NCE exists? Space in NC? No Same EUI-64? Yes Yes No Yes Respond NA including ARO status = 2 Create NCE ARO-pending flag = 1 NCE state = TENTATIVE Send multicast NS for DAD in the IEEE 802.3 segment Start DAD counter Refresh Lifetime ARO-pending flag= 1 Forward NS to IEEE 802.3 segment No Respond NA including ARO status = 1 (duplicate) Figure 3.5: NS with ARO processing diagram. Considering all of the above, upon receipt of a valid NS message destined for the RR and containing valid ARO and SLLAO options, the 6LP-GW shall behave as described below (see Figure 3.5). The 6LP-GW searches its NC for a NCE with same IPv6 address as the IPv6 source address of the incoming NS message; if no matching NCE is found, then the 6LP-GW creates a new NCE for the node being registered. If there is no space left in the NC, then the registration fails and the 6LP-GW generates a NA including an ARO with status = 2, as specified in section 6.5.2 of I-D.ietf-6lowpan-nd [43]. If there is space available in the NC, then a new entry is created with a state value of TENTATIVE and its ARO-pending flag is set to 1. In this final case a NA is not generated in response, but rather the 6LP-GW performs Duplicate Address Detection (DAD) on the IEEE 802.3 segment on behalf of the node that is issuing its registration. This procedure is performed similar to the procedure described in section 5.4 of RFC 4862. The DAD process is detailed in Section 3.2.4.1. If there is a matching NCE whose EUI-64 value differs from the EUI-64 present in the ARO, then the address is a duplicate and the 6LP-GW must generate and send a NA message including an ARO with status = 1 (duplicate), as specified in section 6.5.2 of I-D.ietf-6lowpan-nd. If, instead, the EUI-64 is the same as present in the ARO, then this is the case of a
3.2. PROXY OPERATION SPECIFICATION 45 re-registration and therefore, the ARO-pending flag must be set to 1, the registration lifetime must be refreshed with the contents of the ARO option, and the received NS message is forwarded to the IEEE 802.3 segment in order to perform NUD (note that the NA message produced in response will need to be intercepted later as the RR is not able to handle ARO options – see Section 3.2.4.2). Note that in certain situations of the above procedure, the 6LP-GW responds to NSs on behalf of the RR. Therefore, for every such packet being generated in the 6LP-GW on behalf of the RR, the Router flag must be 1 and the IPv6 source address must be the IPv6 address of the RR attached to the 6LP-GW. This address already should be known due to the previous RS and RA exchange. It is also important to note that TENTATIVE entries should be timed out TENTATIVE_NCE_LIFETIME seconds after their creation in order to leave space in the NC for other hosts, as specified in I-D.ietf-6lowpan-nd [43]. Performing DAD on behalf of IEEE 802.15.4 nodes DAD is performed as specified in RFC 4862 and we assume the existence of the variables RetransTimer and DupAddrDetectTransmits, defined in RFC 4861 and RFC 4862 respectively. The 6LP-GW must maintain a DAD timer for each NCE in the NC. A DAD timer will be started when the corresponding NS is sent. If no NA is received in response after RetransTimer milliseconds, then the 6LP-PGW will either send another NS or end the DAD process, depending on the value of DupAddrDetectTransmits. If the DAD process completes successfully, then the 6LP-GW changes the state of the corresponding NCE to REGISTERED, and the ARO-pending flag to 0. In addition, the information contained in the NCE is used to generate and send a NA message including an ARO option with status = 0 (success) to the node that originated the registration. If DAD fails, then a similar NA including an ARO option with status = 1 (duplicate) must be generated and sent to the node (in the IEEE 802.15.4 segment) that originated the registration. This message must be sent as specified in section 6.5.2 of I-D-ietf-6lowpan-nd (i.e., to the link-local IPv6 address formed from the Interface Identifier (IID) derived from the EUI-64 in the NCE, due to a possible risk of link-layer address collision). After sending the message, the NCE can be deleted. Neighbor Solicitation originating in IEEE 802.3 segment As stated in RFC 4861 and RFC 4862 and as illustrated in Figure 3.4, both unicast and multicast NS messages originating in the IEEE 802.3 segment
46 CHAPTER 3. METHOD Send multicast NS for DAD in the IEEE 802.3 segment Start DAD timer DAD timer expired? NA in response to DAD? DAD failed DAD succeeded Yes No Yes No Send NA including ARO status = 1 (duplicate) Delete NCE Send NA including ARO status = 0 NCE state = REGISTERED ARO-pending flag = 0 Figure 3.6: DAD performed on behalf of 6LoWPAN nodes. The diagram illustrates the process assuming DupAddrDetectTransmits = 1. may arrive at the 6LP-GW. These messages can be sent with three different purposes: Address Resolution, NUD, and DAD. For Address Resolution and DAD, the NS messages are sent to the Solicited-node multicast address of the recipient while, for NUD, they are unicast. As previously mentioned, 6Hs would respond to the unicast NS messages, but they do not join the Solicited-node multicast address and, therefore, they will not respond to these multicast NS messages. In contrast, 6Rs must join the Solicited-node multicast address and thus they must respond to both unicast and multicast NS messages. We should note here that the 6LP-GW is aware of every node that is currently reachable in the IEEE 802.15.4 segment due to the 6LoWPAN-ND registration process. Unicast NS Unicast NS messages are sent for reachability detection (NUD). These messages could be forwarded unchanged (except for the appropriate MAC translation) to the IEEE 802.15.4 segment in order that the target nodes could
3.2. PROXY OPERATION SPECIFICATION 47 respond to the NS with a NA. However, as 6LoWPAN nodes are registered with the 6LP-GW, the information contained in its NC is a priori sufficient to generate the response, thus wireless nodes save energy as they neither need to receive nor send the NS and NA messages, respectively (see the dashed lines coming out of the blue unicast NS arrow in Figure 3.4 on page 42). It is important to note that 6LoWPAN nodes are only required to register non-link-local addresses with routers. Thus, when receiving a unicast NS, the 6LP-GW will behave as follows: •If the incoming NS’s target address is not a link-local address, the 6LP-GW will search its NC for a matching entry in the REGISTERED state. If found, a NA message shall be generated and sent in response to the NS as specified in section 7.2.4 of RFC 4861, using the matching NCE’s address as the source address of the message. •If the incoming NS’s destination address is a link-local address, the 6LP-GW will generate a link-local (EUI-64-based) IPv6 address for every different EUI-64 (contained in REGISTERED NCEs) stored in its NC. If one of these EUI-64 generated addresses matches the target of the NS, then the 6LP-GW will respond with a NA to the NS as specified in section 7.2.4 of RFC 4861, using the generated link-local address as the source address of the NA. In all cases, according to section 5.4.3 of RFC 4862, the 6LP-GW will not generate a response if the matching address is in the TENTATIVE state. On the other hand, when sending out NAs on behalf of 6LNs, the following considerations must be taken into account: •The Router flag must be set to the corresponding NCE isRouter flag value. •The Solicited flag must be set to 1, since the NA is responding to a NS message. •The Override flag must be set to 1, as recommended for this case in Section 4.3 of RFC 4861. Multicast NS Multicast NS messages are sent to perform either Address Resolution or DAD. These messages invoke responses from 6Rs, but not by 6Hs (since as noted earlier 6Hs do not join the Solicted-node multicast group). The 6LP-GW may be aware of which entries in its NC correspond to 6Rs due to previously intercepted RA or NA (having its Router flag set) messages and thus, the 6LP-GW could choose to forward these multicast NS messages only to these
54 CHAPTER 3. METHOD RFC 4861, RA messages are always sent from the link-local (FE80::) address, which simplifies the task of managing the RR’s addresses. However, there could be more than one RR present in the network. This would require extra management of the RR’s address, but such management is out of scope of this thesis project. Having provided all the above considerations, the processing of RA messages originating in the IEEE 802.3 occurs as follows: Upon arrival of a RA message, the 6LP-GW will retrieve both the RR’s IPv6 and MAC addresses from the RA’s IPv6 and Ethernet headers respectively, then store then for further use. Next, it will check the ICMPv6 options or the RA as described here: •If no SLLAO option is present in the RA, the 6LP-GW will append the corresponding SLLAO according to the previously retrieved RR’s MAC address. •If a PIO option is included, the 6LP-GW will clear its ‘L’ (on-link) flag, if it is set. •For every context in use in the context table, the 6LP-GW shall append a 6CO option. Note that inclusion of a new SLLAO and/or 6CO option(s), as well as the modification of the ‘L’ flag of the PIO option calls for recomputation of ICMPv6 checksum, as described in section 2.3 of RFC 4443 [13]. Finally, in order to minimize the amount of unnecessary multicast traffic in the IEEE 802.15.4 segment, the 6LP-GW will forward the RA as follows: If the packet’s destination address is unicast, then the 6LP-GW will examine its NC searching for this address. If a matching NCE having its awaiting-RA flag set is found (regardless of its state), then the RA will be forwarded to its destination and the 6LP-GW will clear the awaiting-RA flag in the corresponding NCE. If no matching NCE is found, or if the matching NCE has its awaiting-RA flag set to zero, the RA will be silently discarded. In contrast, if the RA’s destination address is the all nodes multicast address, then, for every NCE having its awaiting-RA flag set to 1, the 6LP-GW will replace the RA’s destination (multicast) IPv6 and MAC addresses by these belonging to the NCE and send the packet out to through the IEEE 802.15.4 interface, clearing the awaiting-RA flag afterwards. If no NCE having its awaiting-RA flag set is found, the packet shall be silently discarded. Additionally, the 6LP-GW uses a boolean variable indicating whether there is any NCE with its awaiting-RA flag set or not throughout the whole NC, which discharges the 6LP-GW from performing all the previous tasks (except for the RR’s addresses retrieval) if the RA to be processed is meant to be discarded.
3.2. PROXY OPERATION SPECIFICATION 55 Context management and dissemination As previously said, the 6LP-GW must take responsibility for all the 6LoWPAN-ND-related tasks assigned to a 6LBR. Despite context management and dissemination being an optional feature, it falls among the 6LBR tasks which the 6LP-GW implements. This section explains how context management and dissemination is performed in this implementation. Although the approach taken here may seem simplistic, it is sufficient to demonstrate the ability of the 6LP-GW to successfully handle 6LoWPAN contexts. Section 3.2.4.4 explains how contexts are disseminated all over the 6LoWPAN network using RA messages. Thus, the only remaining aspects regarding this issue are context creation and management. As for context creation, the current implementation of the 6LP-GW only considers PIO-based context creation. This means that, when receiving a RA containing a PIO option, the 6LP-GW will search its context table for a context having the same prefix as contained in the PIO option. If no matching context is found, that will result in a new context. Newly created contexts must be assigned a numeric context identifier ranging from 0 to 15. Since use of context identifier 0 saves 1 octet in the IPHC header (see Section 2.6.2), this is the first context identifier that will be assigned to a context. Subsequent contexts, if any, shall use subsequent context identifiers. The reason to create a context from the network prefix is simple: it would be present in every packet involved in the communication with nodes external to the local network. This simple approach could be improved by utilizing more advanced context creation techniques, but such techniques are outside the scope of this thesis project. Section 6.2, however, provides some advice about this topic. Regarding context maintenance, this implementation mainly follows the proceedings described in I-D.ietf-6lowpan-nd, with some specific extensions, but always compliant to the Internet Draft. New contexts are created in uncompress-only state, so that new contexts can arrive to every node in the network before anyone uses them for compression. After a certain (manually configurable) time, the context moves to its normal state, in which it can be used for compression and uncompression. In this state, every prefix/es contained in PIO options of RAs arriving to the 6LP-GW, will refresh the lifetime/s of the corresponding entry/entries in the context table. Should a context lifetime expire, then this context will move to the expired state. In the expired state, contexts are announced again as uncompress-only, so that nodes receiving 6COs with these contexts update their context tables and stop using them for compression. If a RA containing a prefix in its PIO that corresponds to a expired context arrives at the 6LP-GW, the context’s lifetime refreshes and its state reverts to normal again. Otherwise, after a period of twice Default Router Lifetime seconds (announced in RA messages) the context is deleted. When a new context is created or when a context’s state changes, then the next RA arriving to the 6LP-GW from the IEEE 802.3
56 CHAPTER 3. METHOD will be forwarded to the all-nodes multicast address [25] in the IEEE.802.15.4 segment, even if the original RA’s destination address was not the all-nodes multicast address. 3.2.4.5 Processing a Redirect Redirect messages are sent by routers to inform hosts of a better next-hop. They can be sent when a router receives a packet destined to some host which could be reached at less cost by choosing another router as next-hop, or directly (if the destination host is known to be in same network (link-local) as the sender. Redirect originating in IEEE 802.15.4 segment According to I-D.ietf-6lowpan-nd, redirects are not used by 6LoWPAN-ND in route-over topologies, (although they may be used in mesh-under topologies). As the topology under consideration in this thesis project is assumed to be a route-over topology, these messages, if any, will be discarded as they are of no use. We should note here that, since the use of Redirects is not mandatory in other topologies either, the approach is still valid even if no assumptions regarding topology were made. Redirect originating in IEEE 802.3 segment As noted earlier, Redirect messages can be sent by a router to inform a sending node of a better next-hop to the destination. This better next-hop may be another router on the path to the destination, or the destination itself, if it happens to be a neighbor. However, the mechanisms to determine the “best” next-hop differ in the two ND protocols under consideration. According to RFC 4861, the originator of a unicast packet performs a longest prefix match to determine whether the destination is on-link or not. I-D.ietf-6lowpan-nd simplifies this process as follows: if the destination address is a link-local address (FE80::), then the destination is on link. Otherwise, the destination is off-link. In both cases, if the destination is determined to be off-link, the packet is sent via a router (selected as specified in RFC 4861, section 6.3.6). As a reader may infer, when a 6LN sends a packet to the global address of a neighboring NCD on the IEEE 802.3 segment, the 6LN’s next-hop determination algorithm will determine that the destination is off-link (even if both, sender and destination share the same prefix). Thus, the packet will be sent from the 6LN to the NCD via the RR. The RR, according to RFC 4861, will determine that the source and destination of such a packet are neighbors and hence, besides forwarding it to its destination, it might well send a Redirect message to inform the originator (the 6LN) that the destination could be reached directly in one single hop. Since that is not true
3.2. PROXY OPERATION SPECIFICATION 57 in our particular case, and in addition, 6LNs are unable to process Redirects, these messages shall also be discarded. 3.2.4.6 Non-proxy Features ND Option Filtering RFC 4861 states that any node that happens to receive an unrecognised option in a ND message, should simply ignore such an option and continue processing the next one. This fact allows the 6LP-GW to forward packets from one segment to the other not caring about possible options that could be misinterpreted or cause the whole packet to be discarded. However, in terms of power consumption, every single byte transferred counts. This power consumption affects every node involved in the communication (both senders and recipients) being particularly critical in battery-powered nodes. For this reason, this implementation will filter out some ND options, contained mainly in RA messages, that could be considered irrelevant for 6LoWPAN networks. Examples of options that can be filtered out are the Recursive Domain Name Server (DNS) Option (defined in RFC 6106 [28]) or the Flags Expansion Option (defined in RFC 5175 [23]). Note that SLLAO, MTU, and PIO options should not be filtered out. The 6LP-GW implementation described here will remove all the options in RA messages originating in the IEEE 802.3 segment that are to be forwarded to the IEEE 802.15.4, except for SLLAO, MTU, and PIO options. It is also possible to filter out irrelevant options of messages originating in the IEEE 802.15.4 segment and directed to the IEEE 802.3 interface, such as the ARO, 6CO, and ABRO. However, this filtering is of minor interest since it would occur in an Ethernet link where the devices involved are likely to be plugged into the power mains.
Chapter 4 Applying the Method This chapter describes the implementation details of the application specified in the previous chapter (Chapter 3). Since Contiki was utilized in the implementation being described, Section 4.1 provides a comprehensive overview about what was already done and what is ready to use out of the box, what was already done but required certain modifications, and what was not done at all. Moreover, this chapter provides an overview of the whole application, followed by a thorough explanation of each of the different functional modules that comprise it. 4.1 What Contiki’s provides and does not provide This section describes the parts of the 6LP-GW application that are part of the Contiki core and distinguishes these from those parts that have been completely or partially developed as part of this thesis project. 4.1.1 What Contiki provides As explained in Chapter 2, Section 2.10.2, Contiki furnishes a richly-featured development toolbox. In addition to the kernel and the protothreads implementation (described in Section 2.10.2), Contiki provides full IPv4 and IPv6 stacks, a standard-compliant 6LoWPAN implementation, and a large set of libraries. Of these elements, we make use of the IPv4 and IPv6 stacks, the Transport Layer application interface, 6LoWPAN, and several other modules and libraries. How we have used this existing code is described below. IPv4 stack The IPv4 stack runs as any other Contiki protothread and supports both TCP and UDP protocols. It includes ICMP (part of which is used), ARP, and DHCP implementations. While UDP, TCP, and ICMP are implemented as part of the IPv4 module, DHCP and ARP are implemented as separate modules. DHCP is implemented as a protothread and in order to use it together with the rest of the Contiki code, it needs to be wrapped within a Contiki process (see Section 2.10.2.2). In contrast, ARP is implemented as a set of functions, which must be called manually when performing certain Ethernet-related operations. 59
60 CHAPTER 4. APPLYING THE METHOD IPv6 stack The IPv6 stack also runs as a Contiki protothread and supports both TCP and UDP. In addition, it includes complete ICMPv6 and Neighbor Discovery for IPv6 (RFC 4861 [34]) implementations. Transport Layer application interface Contiki defines a lightweight socket-like application programming interface (API) for application-level communication. Like the Unix socket API, this API allows the creation of TCP and UDP connections which maintain the association that usually defines a socket, i.e., source address and local port and, in case of TCP, destination address and remote port. This API also supports most common Unix socket operations, such as creating/eliminating connections (socket()), listening for incoming connection requests (TCP listen()), sending connection requests (TCP connect()), binding connections to ports (bind()), and sending and receiving packets (send() and recv() in case of TCP, and sendto() and recvfrom() in case of UDP). 6LoWPAN The 6LoWPAN implementation currently supports only 64-bit “long” addresses. It supports fragmentation and different compression mechanisms. The supported compression mechanisms are stateless HC1 compression (defined in RFC 4944 [33]), and stateful IPHC compression (defined in RFC 6282 [27]), which obsoletes the former. However, the IPHC compression implementation has some limitations which will be described in Section 4.1.3. In addition, Contiki also includes several IEEE 802.15.4 MAC layers, which provide support for encapsulating 6LoWPAN packets into IEEE 802.15.4 frames among other features. Other modules and libraries •Contiki provides several libraries for time measurement. The most basic one is the Timer library, which provides simple and lightweight function for timer management and provides the base on top of which other timer libraries are built. This library implements the following functions: timer_set Sets a timer to a time interval. timer_reset Resets a timer. The former expiration time of the timer becomes its new starting point, which allows the timer to remain stable over time.
4.1. WHAT CONTIKI’S PROVIDES AND DOES NOT PROVIDE 61 timer_restart Restarts a timer. The new starting point of the timer is the current time (in contrast to timer_reset). timer_expired Evaluates whether a timer has already expired or not. timer_remaining Returns the time remaining until expiration of a timer. Together with the Timer library which measures the time in system tics, Contiki provides the Seconds timer library, which in contrast to the Timer library, implements timers having a second as their timing unit. However, neither the Timer library nor the Seconds timer library provide any mechanism to inform the process setting the timer about any timers’ expiration. Therefore, any process using these timers has to actively poll the timer by means of the timer_expired function or its equivalent in the Seconds timer library,stimer_expired, in order to determine whether a timer has expired or not. For this reason, Contiki provides the Event timer library. This library, as mentioned Section 2.10.2.2, implements an active process (the etimer process) that periodically checks all the Event timers and posts an event (PROCESS_EVENT_TIMER) to the process who set the timer when such timer expires. A similar utility is provided by the Callback timer library. This library also runs an active process (the ctimer process) that periodically checks the Callback timers. Similar to the Event timer library, the Callback timer library allows setting timers that do not need to be actively polled, but with the difference that the callback timer library is independent of the process that specifies the callback timer. This means that instead of posting an event to the process who set a timer, the Callback timer library will call a callback function (provided when the timer was set) when the timer expires. The Callback timer library is useful for certain situations where utilizing a process to verify a timer would simply be overkill. Finally, the last timer library provided by Contiki is the Real-time task scheduling library. Unlike the rest of the timers, this library does not rely on the Timer library nor is it dependent upon any process to check for timer expirations. Instead, it relies on the hardware-specific real time module (if any) present in wide variety of micro-controllers. This library, similar to the Callback timer library allows scheduling a task (function) to be executed at a specified time in the future.
62 CHAPTER 4. APPLYING THE METHOD We should note, however, that the implementation described in this thesis does not make use of the Callback timer library nor the Real-time task scheduling library; they are described here only for completeness. 4.1.2 What Contiki requires This section explains the elements required by Contiki in general, while Section 4.2.1 explains these elements in detail for the implementation described in this thesis. Since Contiki is platform-independent software, no platform-specific code is provided. Instead, a number of platform-specific functions, constants, and data-type definitions must be provided so that Contiki can make use of the platform’s resources. This set of platform-specific code includes elements that can be considered drivers for the hardware components needed by the runtime system, which together constitute a“Contiki port” (as it is called by the by the Contiki community). On the other hand, no implementation would be complete without (at least) one application. The Contiki’s protothreads library together with the transport layer application interface provide a rich set of functions that allow implementation of any kind of applications. However, since strictly speaking this does not pose a Contiki requirement, we will leave the implementation of applications for the moment. Figure 4.1 illustrates a typical Contiki application highlighting its platformspecific requirements. Contiki Clock library The key element of a Contiki port is the Clock library, which is used by the timer libraries. This code must thus be initialized before any other Contiki module that uses timers. This module is highly platform-specific and needs to be implemented specifically for each Contiki port. Contiki provides a set of function declarations whose definition needs to be implemented for this module to work. In addition, the module requires the definition of the constant CLOCK_CONF_SECOND, which specifies the duration of a second in terms of system ticks, and the definition of the clock_time_t data type, which holds values that are based upon the number of system ticks since system start up. The Clock library elements that need to be provided are: CLOCK_CONF_SECOND This constant represents one (1) second measured in system ticks. The meaning of a system tick is explained below. clock_time_t This data type definition sets the type of the variable that will hold the number of system ticks since system start up. Note that in order to be able to compare two
4.1. WHAT CONTIKI’S PROVIDES AND DOES NOT PROVIDE 63 Clock library Timer librarySTimer library PT Contiki kernel LC MAC Process Internet App Internet App App ETimer library CTimer library 6LoWPAN uIPv6/v4 HAL Figure 4.1: A typical Contiki-based application. Grey boxes represent implementation-specific modules. The dashed box containing the text “6LoWPAN” mean that the 6LoWPAN layer may be present or not. Arrows show the dependency direction. As the figure illustrates, some timer libraries and the uIP module makes use of the Contiki protothreads library; applications on top of the stack make use of the Contiki protothreads library along with the uIP transport layer application interface and (optionally) timers; and both the Contiki timer library and the Contiki’s uIP implementation rely on hardware-specific modules. times when there has been a wrap around of this variable in between the two samples, the maximum interval within which two times can be compared is restricted to MAX_VALUE_OF(clock_time_t) / 2. Thus, a too-short data type would cause the maximum possible interval between two times being compared to be too small. In addition, a too-big data type (depending on the
70 CHAPTER 4. APPLYING THE METHOD of the 6LP-GW; thus the local-host will see any other 6LN or NCD in the network as regular Ethernet hosts. Note however that this relationship between the local-host and the 6LP-GW only applies to the local-host’s IPv6 communication; all incoming and outgoing local-host’s IPv4 traffic simply bypasses the 6LP-GW logic (as shown with the rightmost arrow linking the units labelled “IEEE 802.3 MAC” and “ARP”). The following sections describe in detail each of the functional units in a bottom-up fashion. IEEE 802.15.4 MAC IEEE 802.3 MAC 6LoWPAN 6LP-GW Radio HAL Ethernet HAL ARP IPv4 ND TCP IPv6 UDP TCP UDP DHCP PHY PHY Application layer Transport layer Network layer 6LP-GW pseudo-layer Adaptation layer Link layer Physical layer IPv6 host 6LP-GW Figure 4.3: The 6LP-GW application diagram. The area surrounded by a white border in the upper part constitutes the local-host logic; the oval area in the center part of the diagram represents the 6LP-GW logic in; and the lower part of the diagram illustrates the lower level layers through which packets are delivered or sent to its corresponding destination. Note that the Ethernet-related functional units are common to both the 6LP-GW and the local-host.
4.2. APPLICATION OVERVIEW 71 4.2.1 Hardware Abstraction Layer The hardware abstraction layer (HAL) is the logic that “abstracts” the hardware specific details, thus hiding these details from the rest of the application. This implementation follows the commonly-used black box approach, which consists of providing the necessary interface functions required by the immediately upper-layer logic while keeping the latter unaware of implementation details. The following sections describe the operation of each of the drivers implemented as part of this hardware abstraction layer. These descriptions provide a comprehensive explanation of the operation performed by the specific module under discussion, rather than a detailed and less instrumental explanation of the source code. A reader interested in implementation-specific issues is referred to Appendix C for further details. 4.2.1.1 The Clock library implementation As previously mentioned (see Section 4.1.2), any Contiki implementation must provide a Clock library with the following elements: •CLOCK_CONF_SECOND •clock_time_t •clock_init() •clock_time() •clock_seconds() In order to explain and justify the choices made regarding this driver, it is important to know some details about the specific micro-controller being used in our implementation. This micro-controller is a Texas Instruments family-5 ultra low-power MSP430 (MSP430F5435). This micro-controller is based on a 16-bit RISC processor. The MSP430F5435 has three different clock signals: MCLK, SMCLK, and ACLK. Each of this clock signals can be sourced from different external crystals or from the micro-controller’s internal oscillator. In our case, MCLK and SMCLK are sourced from an external high-frequency crystal (32 MHz), while ACLK is sourced from an external 32,768 Hz crystal. Each of the MSP430’s functional units requiring a clock signal can be sourced from any of the above clock signals, which can be used directly or divided (usually) by 2, 4, or 8. The divisors can vary however depending on the specific functional unit. In the clock library, we use the MSP430’s Timer A module in order to configure the micro-controller’s timer interrupt. The Timer A module is sourced by clock signal ACLK divided by 8. Since ACLK is sourced from a 32,768 Hz crystal, this makes our particular configuration of timer A run at 32,768/8=4,096 Hz.
72 CHAPTER 4. APPLYING THE METHOD The Timer A module is configured to execute the timer interrupt routine every 256 ACLK/8 cycles. This value needs to be chosen carefully, considering the trade-off between timer granularity and the frequency at which the timer interrupt routine is executed. In other words, too high a value would cause our minimum possible timer period to be too long, while too low a value would cause the interrupt routine to be executed too frequently, stealing processor cycles from the application or from other micro-controller modules. The interval value of 256 allows for a minimum timer of (1/4,096)/256 = 1/16 seconds, this is 62.5 milliseconds (which defines the duration of a system tick). This value seems to be appropriate for our application as it provides a balance between interrupt frequency and use of processor cycles. Note that, since the CPU is driven by MCLK, which operates at 32/2 MHz, i.e., a CPU clock frequency of 16 MHz, executing the interrupt routine once every 1/16 seconds means that this interrupt routine is executed once every 1,000,000 CPU cycles. Given this discussion an astute reader may have already guessed that our CLOCK_CONF_SECOND is 16. Since this is the number of times the interrupt routine has to be executed to measure one second. Regarding the definition of the clock_time_t, the chosen data type is unsigned long, which is a 32-bit long data type in our specific architecture. The reason for this choice instead of a 16-bit data type (note that the MSP430 has a 16-bit CPU) is that, in order to compare two timestamps (which is what timers need to do), the maximum distance between two timestamps that can be compared is half the maximum value allowed by the data type. Thus, a 16- bit data type would allow for a maximum timer of 65,535/2 = 32,767 system ticks. This number of system ticks expressed in seconds is 32,767/16 = 2,047 seconds (or 34 minutes) which may be too small a range for certain timer requirements. In addition, the MSP430 microprocessor is powerful enough to perform a 32-bit addition without its overall performance being negatively affected. Given all of the above choices, defining the rest of the functions of the Clock library is relatively straightforward: clock_init() initializes the Timer A module selecting ACLK divided by 8 as its source and sets a timer interrupt to be executed every 256 ACLK/8 cycles; the timer interrupt is implemented as follows:
4.2. APPLICATION OVERVIEW 73 interrupt void timer_interrupt(void) { system_ticks++; if (0== (ticks % CLOCK_SECOND)) { seconds++; } /* If there are Event timers pending, notify the event timer module */ if (etimer_pending()) { etimer_request_poll(); } } Where system_ticks and seconds are static variables of type clock_time_t. Thus, clock_time() returns the value of variable system_ticks while clock_seconds() returns the value of seconds. The final part of the function, as explained in Section 4.1.2, provides support for the Event timer library, requesting a poll on its behalf to the Contiki kernel every time a system tick occurs if there is any pending Event timer. 4.2.1.2 Ethernet Controller Driver The Ethernet controller driver is split into two layers: the lower one provides the actual hardware abstraction layer while the upper layer implements a Contiki process which requests polls from the Contiki kernel whenever the Ethernet controller signals that there is an incoming packet. As for the lower layer, the Ethernet micro-controller used is a Microchip’s ENC28J60. This micro-controller implements a SPI interface and an instruction set which allows the MSP430 to interact with it. Thus, all the communication between the MSP430 and the ENC28J60 (including Ethernet packets being received or sent out) occurs through this SPI interface and using the ENC28J60’s instruction set. The hardware abstraction layer needs to provide the upper layer with a set of functions to initialize the ENC28J60, and to send and read Ethernet packets. In addition it provides a function to check whether there is any packet pending to be read and an interrupt routine that requests a poll on behalf of its upper-layer’s process from the Contiki kernel when a packet arrives (Note that only processes can be polled from the Contiki kernel). As mentioned above, the upper-layer Ethernet driver implements a running Contiki process that, when polled, checks whether there is an incoming Ethernet packet pending to be read, and, if so, reads it and forwards it to the upper layer (in this case the Ethernet MAC layer). In addition, this upperlayer driver encapsulates lower-layer functions into slightly more complex functions that can be invoked from upper layers. Among this additional functions, this Ethernet driver supports turning on/off the whole Ethernet
74 CHAPTER 4. APPLYING THE METHOD operation and subtracts the Ethernet’s CRC length from the packet’s payload length. 4.2.1.3 Radio Transceiver Controller Driver While the Ethernet and the radio drivers have many aspects in common, the radio driver has some extra requirements. These requirements are due to the use of a specific IEEE 802.15.4 MAC layer provided by Contiki (Contikimac) which implements a radio duty cycling mechanism that allows for power saving by periodically turning the radio receiver off at specific times [20]. Although the radio driver implemented in the 6LP-GW as part of this thesis work fulfils these requirements by providing all the required interface functions (hence, it could be used in conjunction with the Contikimac MAC layer), the IEEE 802.15.4 MAC implementation utilised in our application is an earlier version (included in the Contiki 2.4 version) called Sicslowmac which does not perform the radio duty cycling mechanism, but keeps the radio receiver on. The reason for this is that the radio duty cycling mechanism saves power by turning off the radio, thus increasing the probability of missing frames during the time it is powered off. Since the 6LP-GW is assumed to be powered by the power mains, we choose not to use this radio receiver duty cycle mechanism. 4.2.1.4 Other Drivers As previously mentioned, the 6LP-GW implementation developed as part of this thesis project includes several components that, although not required for the purpose of our study, were useful for debugging purposes. Two such components support the board’s two buttons and three LEDs. Details about the implementation of these two components are detailed in this this section. Buttons The buttons driver can be seen as if it were divided into two different abstraction layers: the lower layer simply checks whether a button is pressed or not, the upper layer performs some operations at the Contiki operating system level. Regarding the lower layer, two functions, one for each button, return a value other than zero if the corresponding button is pressed and zero otherwise. This is performed simply by checking the value of the pin to which each button is directly connected. As for the upper layer, the implementation provides a function that permits Contiki processes to register themselves to use the buttons. This way, when a button is pressed, all the registered processes are notified about it. This notification includes information regarding which of the two buttons has been pressed. By this simple mechanism we enable Contiki processes to perform
4.2. APPLICATION OVERVIEW 75 blocking waits that depend upon on the state of the buttons, without requiring active waits that would block the entire system. LEDs The LEDs driver is even simpler than the buttons driver; it simply provides three functions (in addition to the required initialisation function) that permit setting a certain LED on, off, or perform a toggle operation on it depending on a parameter that specifies its color (this identifies the specific LED since the three different LEDs are red, green, and yellow). 4.2.2 MAC layer The MAC layer of this implementation performs the operations required for the encapsulation/decapsulation and transmission/reception of IP-layer packets over the physical media. The 6LP-GW internetworks two different media types, each of them having different MAC requirements. These two different MAC layers are described in the following paragraphs. 4.2.2.1 IEEE 802.3 MAC layer Before proceeding to describing the behaviour of this module, it is important to clarify the different types of IP packets that may traverse it. Our implementation has three different sources (and their three corresponding destinations) of IP packets, which will require different treatment. The 6LP-GW will use the IEEE 802.3 MAC layer in order to receive or send packets over the IEEE 802.3 media. Additionally, the local-host implemented in the same device will also use this same functionality. Moreover, this host has a dual stack, which means that either IPv4 and IPv6 packets will be sent or received over through this MAC layer. The IEEE 802.3 MAC layer implemented operates differently depending on the IP version of the layer-3 packet. In the case of IPv4 packets, this module is responsible for performing link-layer address resolution (which, unlike the case of IPv6, is not performed at the IP layer). For this purpose, an implementation of the ARP protocol provided by Contiki has been used. In particular, the MAC layer will operate as follows regarding IPv4 traffic: •For outgoing, non-multicast, IPv4 traffic, it will generate the entire linklayer (Ethernet) header depending on the execution of the ARP protocol. If ARP is able to determine the link-layer address of the destination based on the destination IPv4 address, this address will be placed in the destination address field of the Ethernet header. If not, the ARP code will replace the outgoing packet by an ARP request for that address. In either case, the rest of the Ethernet header fields (source link-layer
76 CHAPTER 4. APPLYING THE METHOD address and the type/length field) will be filled with the local node’s linklayer address and the corresponding ethertype, which may be either the corresponding value for IPv4, or for ARP, depending on whether ARP succeeded into resolving the destination link-layer address or not. •For incoming, non-multicast IPv4 traffic, the ARP algorithm will update its cache with the pair <IPv4 source address, source link-layer address> if no entry with these values was already present. •Periodically, the MAC layer will perform maintenance operations on the ARP cache. In order to do so, the IEEE 802.3 MAC layer is implemented as a Contiki process which utilizes a periodic event timer. In contrast, IPv6 traffic does not require address resolution. Indeed, the task of address resolution is performed by the ND protocol and therefore it occurs at the IP layer. If a packet’s IPv6 source or destination address corresponds to the local host, its ND Address Resolution algorithm will handle the details regarding link-layer address resolution appropriately. If the IPv6 packet has been generated by or is destined to the 6LP-GW, then the 6LP-GW module itself will take appropriate care of the link-layer addresses. In all cases, the IEEE 802.3 MAC implementation will multiplex and forward incoming traffic to the required upper-layer module, which may be either the IPv4 or IPv6 stacks of the local node, or the 6LP-GW module. 4.2.2.2 IEEE 802.15.4 MAC layer Regarding the IEEE 802.15.4 MAC layer, few changes have been made to the code provided by Contiki. Contiki provides several MAC layers, each of them implementing different features. The one utilised by this implementation is called “sicslowmac” and it performs the basic operations regarding the IEEE 802.15.4 MAC layer. For outgoing packets, it generates the contents of the link-layer header; for incoming packets, it parses the contents of the IEEE 802.15.4 header (discarding any malformed packets) and forwards the packets to the appropriate upper layer, which in this case is always the 6LoWPAN Adaptation layer. 4.2.3 6LoWPAN Adaptation layer The 6LoWPAN Adaptation layer is located between the IEEE 802.15.4 MAC layer and the 6LP-GW module. As will be explained in Section 4.2.4, the IPv6 layer of the local-host stack does not have direct access to the 6LoWPAN layer. As we already mentioned, Contiki includes an implementation of the 6LoWPAN adaptation layer. However this implementation lacks certain features regarding the stateful IPv6 header compression feature specified in RFC 6282 [27] that were of interest for this thesis project. In particular,
4.2. APPLICATION OVERVIEW 77 what is missing in the original code is a dynamic mechanism to add/remove contexts, and code to utilize such dynamically added contexts for stateful compression/decompression. In addition, the 6LoWPAN implementation only allows the use of 64-bit fixed-length contexts, whereas RFC 6282 does not impose this limitation and I-D.ietf-6lowpan-nd [43] permits the dissemination of variable-length contexts of up to 128 bits. Thus, some modifications were made to the original Contiki’s 6LoWPAN code in order to permit the utilisation of arbitrarily long, dynamically acquired contexts. Apart from the changes described above, the rest of the 6LoWPAN code included in the implementation of the 6LP-GW is mostly the same as the original code and performs the following tasks: •For outgoing traffic, the 6LoWPAN layer compresses the IPv6 header and forwards the packet to the IEEE 802.15.4 MAC layer. •For incoming traffic, the IPv6 header is uncompressed and the packet is forwarded to the 6LP-GW pseudo layer. 4.2.4 The 6LP-GW pseudo-layer The 6LP-GW’s operation is described in detail in Chapter 3. Its implementation comprises the functions that handle packet forwarding and ND-proxying. This module is divided into three different sub-modules: the Forwarding module, the ND module, and the Proxy module. Each of these performing their tasks following as described below: The Forwarding module As its name suggests, the Forwarding module comprises the functions that handle the tasks regarding packet forwarding. Basically, this module is in charge of performing initial processing of incoming traffic, as well as sending out outgoing packets. Regarding the incoming traffic operations, it performs the basic bridging operations described in Section 3.2.3. In addition it translates any linklayer addresses that might be present in the payload (mainly in ND packets) when necessary. Moreover, incoming packets are passed through a filter that discards all IPv6 traffic which is not UDP or ICMPv6. Processing of outgoing packets consists of multiplexing these packets to the appropriate interface according to their origin and destination. This process also involves translating link-layer addresses (as explained for incoming packets) when necessary. Note that the local-host is considered to be attached to a virtual Ethernet interface of the 6LP-GW, and thus this host must also be taken into account for this processing of incoming and outgoing packets. In fact, this is the reason why the 6LoWPAN Adaptation layer does not have direct access to the
78 CHAPTER 4. APPLYING THE METHOD IPv6 module: it is the 6LP-GW (in particular, the Forwarding sub-module) who multiplexes all the incoming IPv6 traffic to its corresponding destination, which may be the local-host, a remote host, or none of them (e.g. if the proxy operations determine that such a packet needs to be replaced by another packet). It is important note also that the process of determining the source and destination link-layer addresses is performed according to the information gathered by the bridging function, which might be modified by the Proxy operation. The ND module This ND module provides all the functions and data structures required to perform the tasks regarding 6LoWPAN-ND that correspond to a 6LR, as specified in I-D.ietf-6lowpan-nd. This means that this module provides the facilities to handle and maintain the NC, and the contexts table. Although not being strictly part of the 6LoWPAN-ND specification, this module also performs the operations regarding the DAD mechanism when performed on behalf of 6LHs. The reasons to include these functionality here is that, apart from being related to the ND protocol, the results (either positive or negative) of DAD imply generating 6LoWPAN-ND responses (see Section 3.2.4.1). The Proxy module The Proxy module is the main sub-module among the three comprising the 6LP-GW implementation. It implements a Contiki process that is in charge of performing ND-proxying, which means that it carries out the operations described in Section 3.2.4, besides controlling the other two sub-modules for the required tasks. Figure 4.4 illustrates the relationship between these three modules. 4.2.5 Network Layer Regarding the network layer, few changes were made to the IPv4 and IPv6 implementations that come with Contiki. These few modifications are mainly related to the way packets get into or out from the stacks rather than to their actual implementation. The reason for this is that, as mentioned in Section 4.1.3, Contiki does not support the use of the IPv4 and IPv6 stacks simultaneously. In addition, both the stacks reuse certain variables and functions (using the same names) when used separately.When possible, these variables and functions have been made available for both stacks simultaneously, allowing their shared use. This is the case of the variables uip_buf and uip_len, which hold the buffer for both incoming and outgoing traffic, and the length of the
4.2. APPLICATION OVERVIEW 79 Proxy module Forwarding module ND module Incoming ND packet Forwarding module (1) (2) (3) (4) (5) (6) Figure 4.4: The 6LP-GW module architecture. The numbers in the arrows indicate the order in which each module’s operations are invoked for the event of an incoming ND packet. The forwarding module appears twice because it is normally required to handle the reception and dispatch of packets. data contained in it respectively. When this shared use has not been possible, a duplication and renaming has been applied. The data-flow between both IP stacks and the modules lying immediately above or beneath them in the communications stack is illustrated in Figure 4.3 on page 70. 4.2.6 Application Layer The only application implemented in the application layer as part of this thesis project is a DHCP client. Contiki provides the core functions required for this DHCP client. It was only necessary to implement a Contiki process to handle specific events (arrival of packets or expiration of a timer) and two callback functions. Of these functions, one will be called if the DHCP client succeeds in acquiring an IPv4 address while the other will be invoked in the event of failing to renew the lease of the assigned address with the DHCP server.