opentun.py 25.3 KB
Newer Older
1 2 3
# -*- coding: utf-8 -*-

import json
4 5 6 7 8 9 10 11 12 13 14
import logging
import os
import struct
import threading
import time
import traceback
from fcntl import ioctl
import sys

from kombu import Exchange

15
from utils import arrow_down, arrow_up, finterop_banner
16
from utils.messages import *
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
DEFAULT_IPV6_PREFIX = 'bbbb'

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger(__name__)

# ============================ defines =========================================

# insert 4 octedts ID tun for compatibility (it'll be discard)
VIRTUALTUNID = [0x00, 0x00, 0x86, 0xdd]

IFF_TUN = 0x0001
TUNSETIFF = 0x400454ca


def buf2int(buf):
    """
    Converts some consecutive bytes of a buffer into an integer.
    Big-endianness is assumed.

    :param buf:      [in] Byte array.
    """
    returnVal = 0
    for i in range(len(buf)):
        returnVal += buf[i] << (8 * (len(buf) - i - 1))
    return returnVal


# ===== formatting

def formatStringBuf(buf):
    return '({0:>2}B) {1}'.format(
49 50
        len(buf),
        '-'.join(["%02x" % ord(b) for b in buf]),
51 52 53 54 55 56 57 58 59
    )


def formatBuf(buf):
    """
    Format a bytelist into an easy-to-read string. For example:
    ``[0xab,0xcd,0xef,0x00] -> '(4B) ab-cd-ef-00'``
    """
    return '({0:>2}B) {1}'.format(
60 61
        len(buf),
        '-'.join(["%02x" % b for b in buf]),
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
    )


def formatIPv6Addr(addr):
    # group by 2 bytes
    addr = [buf2int(addr[2 * i:2 * i + 2]) for i in range(len(addr) / 2)]
    return ':'.join(["%x" % b for b in addr])


def formatAddr(addr):
    return '-'.join(["%02x" % b for b in addr])


def formatThreadList():
    return '\nActive threads ({0})\n   {1}'.format(
77 78
        threading.activeCount(),
        '\n   '.join([t.name for t in threading.enumerate()]),
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    )


# ===== parsing

def hex2buf(s):
    """
    Convert a string of hex caracters into a byte list. For example:
    ``'abcdef00' -> [0xab,0xcd,0xef,0x00]``

    :param s: [in] The string to convert

    :returns: A list of integers, each element in [0x00..0xff].
    """
    assert type(s) == str
    assert len(s) % 2 == 0

    returnVal = []

    for i in range(len(s) / 2):
        realIdx = i * 2
        returnVal.append(int(s[realIdx:realIdx + 2], 16))

    return returnVal


# ===== CRC

def calculateCRC(payload):
    checksum = [0x00] * 2

    checksum = _oneComplementSum(payload, checksum)

    checksum[0] ^= 0xFF
    checksum[1] ^= 0xFF

    checksum[0] = int(checksum[0])
    checksum[1] = int(checksum[1])

    return checksum


def calculatePseudoHeaderCRC(src, dst, length, nh, payload):
    """
    See these references:

    * http://www-net.cs.umass.edu/kurose/transport/UDP.html
    * http://tools.ietf.org/html/rfc1071
    * http://en.wikipedia.org/wiki/User_Datagram_Protocol#IPv6_PSEUDO-HEADER
    """

    checksum = [0x00] * 2

    # compute pseudo header crc
    checksum = _oneComplementSum(src, checksum)
    checksum = _oneComplementSum(dst, checksum)
    checksum = _oneComplementSum(length, checksum)
    checksum = _oneComplementSum(nh, checksum)
    checksum = _oneComplementSum(payload, checksum)

    checksum[0] ^= 0xFF
    checksum[1] ^= 0xFF

    checksum[0] = int(checksum[0])
    checksum[1] = int(checksum[1])

    return checksum


def _oneComplementSum(field, checksum):
    sum = 0xFFFF & (checksum[0] << 8 | checksum[1])
    i = len(field)
    while i > 1:
        sum += 0xFFFF & (field[-i] << 8 | (field[-i + 1]))
        i -= 2
    if i:
        sum += (0xFF & field[-1]) << 8
    while sum >> 16:
        sum = (sum & 0xFFFF) + (sum >> 16)

    checksum[0] = (sum >> 8) & 0xFF
    checksum[1] = sum & 0xFF

    return checksum


def byteinverse(b):
    # TODO: speed up through lookup table
    rb = 0
    for pos in range(8):
        if b & (1 << pos) != 0:
            bitval = 1
        else:
            bitval = 0
        rb |= bitval << (7 - pos)
    return rb


def calculateFCS(rpayload):
    payload = []
    for b in rpayload:
        payload += [byteinverse(b)]

    FCS16TAB = (
        0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
        0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
        0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
        0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
        0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
        0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
        0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
        0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
        0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
        0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
        0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
        0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
        0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
        0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
        0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
        0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
        0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
        0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
        0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
        0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
        0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
        0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
        0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
        0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
        0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
        0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
        0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
        0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
        0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
        0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
        0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
        0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
    )
    crc = 0x0000
    for b in payload:
        crc = ((crc << 8) & 0xffff) ^ FCS16TAB[((crc >> 8) ^ b) & 0xff]

    returnVal = [
        byteinverse(crc >> 8),
        byteinverse(crc & 0xff)
    ]
    return returnVal


def formatCriticalMessage(error):
    returnVal = []
    returnVal += ['Error:']
    returnVal += [str(error)]
    returnVal += ['\ncall stack:\n']
    returnVal += [traceback.format_exc()]
    returnVal += ['\n']
    returnVal = '\n'.join(returnVal)
    return returnVal


def formatCrashMessage(threadName, error):
    returnVal = []
    returnVal += ['\n']
    returnVal += ['======= crash in {0} ======='.format(threadName)]
    returnVal += [formatCriticalMessage(error)]
    returnVal = '\n'.join(returnVal)
    return returnVal


class TunReadThread(threading.Thread):
    """
    Thread which continously reads input from a TUN interface.

    When data is received from the interface, it calls a callback configured
    during instantiation.
    """

    ETHERNET_MTU = 1500
    IPv6_HEADER_LENGTH = 40

    def __init__(self, tunIf, callback):

        # store params
        self.tunIf = tunIf
        self.callback = callback

        # local variables
        self.goOn = True

        # initialize parent
        threading.Thread.__init__(self)

        # give this thread a name
        self.name = 'TunReadThread'

273 274 275 276
        # check if running on MacOs, in this situation tuntap driver doesnt put the 4extra bytes
        # tested with brew install Caskroom/cask/tuntap
        self.tunTapHeader = not sys.platform.startswith('darwin')

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
        # start myself
        self.start()

    def run(self):
        try:
            p = []

            while self.goOn:

                # wait for data
                p = os.read(self.tunIf, self.ETHERNET_MTU)

                # convert input from a string to a byte list
                p = [ord(b) for b in p]

                # debug info
                log.debug('packet captured on tun interface: {0}'.format(formatBuf(p)))

                # remove tun ID octets
296 297
                if self.tunTapHeader:
                    p = p[4:]
298 299 300 301

                # make sure it's an IPv6 packet (i.e., starts with 0x6x)
                if (p[0] & 0xf0) != 0x60:
                    log.info('this is not an IPv6 packet')
302
                    log.debug('first bytes: {0}'.format(formatBuf(p[:2])))
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
                    continue

                # because of the nature of tun for Windows, p contains ETHERNET_MTU
                # bytes. Cut at length of IPv6 packet.
                p = p[:self.IPv6_HEADER_LENGTH + 256 * p[4] + p[5]]

                # call the callback
                self.callback(p)

        except Exception as err:
            errMsg = formatCrashMessage(self.name, err)
            log.critical(errMsg)
            sys.exit(1)

    # ======================== public ==========================================

    def close(self):
        self.goOn = False


323 324
# TODO Create an interface class OpenTun to agregate common stuff between linux and macos

325 326 327 328 329
class OpenTunLinux(object):
    """
    Class which interfaces between a TUN virtual interface and an EventBus.
    """

330
    def __init__(self, name, rmq_connection, rmq_exchange="amq.topic",
331
                 ipv6_prefix=None, ipv6_host=None, ipv6_no_forwarding=None,
332
                 ipv4_host=None, ipv4_network=None, ipv4_netmask=None):
333 334 335 336

        # RMQ setups
        self.connection = rmq_connection
        self.producer = self.connection.Producer(serializer='json')
337
        self.exchange = rmq_exchange
338 339

        self.name = name
340
        self.packet_count = 0
341 342 343 344 345 346 347 348 349 350 351 352 353

        if ipv6_prefix is None:
            # self.ipv6_prefix = [0xbb, 0xbb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
            ipv6_prefix = DEFAULT_IPV6_PREFIX

        self.ipv6_prefix = ipv6_prefix

        if ipv6_host is None:
            # self.ipv6_host = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]
            ipv6_host = ":1"

        self.ipv6_host = ipv6_host

354 355 356 357
        if ipv6_no_forwarding is None:
            ipv6_no_forwarding = False
        self.ipv6_no_forwarding = ipv6_no_forwarding

358 359 360 361 362 363 364 365 366 367 368 369 370
        if ipv4_host is None:
            ipv4_host = "2.2.2.2"

        self.ipv4_host = ipv4_host

        if ipv4_network is None:
            ipv4_network = [10, 2, 0, 0]
        self.ipv4_network = ipv4_network

        if ipv4_netmask is None:
            ipv4_netmask = [255, 255, 0, 0]
        self.ipv4_netmask = ipv4_netmask

371
        log.debug("IP info: \n {}".format(self.get_tun_configuration()))
372 373 374 375 376 377 378 379 380 381

        # local variables
        self.tunIf = self._createTunIf()
        if self.tunIf:
            self.tunReadThread = self._createTunReadThread()
        else:
            self.tunReadThread = None

    # ======================== public ==========================================

382 383 384 385 386 387 388 389 390 391 392 393
    def get_tun_configuration(self):

        return {
            'ipv6_prefix': self.ipv6_prefix,
            'ipv6_host': self.ipv6_host,
            'ipv6_no_forwarding': self.ipv6_no_forwarding,
            'ipv4_host': self.ipv4_host,
            'ipv4_network': self.ipv4_network,
            'ipv4_netmask': self.ipv4_netmask,
        }


394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    # def close(self):

    #     if self.tunReadThread:

    #         self.tunReadThread.close()

    #         # Send a packet to openTun interface to break out of blocking read.
    #         attempts = 0
    #         while self.tunReadThread.isAlive() and attempts < 3:
    #             attempts += 1
    #             try:
    #                 log.info('Sending UDP packet to close openTun')
    #                 sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    #                 # Destination must route through the TUN host, but not be the host itself.
    #                 # OK if host does not really exist.
    #                 dst = self.ipv6_prefix + self.ipv6_host
    #                 dst[15] += 1
    #                 # Payload and destination port are arbitrary
    #                 sock.sendto('stop', (formatIPv6Addr(dst),18004))
    #                 # Give thread some time to exit
    #                 time.sleep(0.05)
    #             except Exception as err:
    #                 log.error('Unable to send UDP to close tunReadThread: {0}'.join(err))


    # ======================== private =========================================

    def _getNetworkPrefix_notif(self, sender, signal, data):
        return self.ipv6_prefix

    def _createTunIf(self):
        """
        Open a TUN/TAP interface and switch it to TUN mode.

        :returns: The handler of the interface, which can be used for later
            read/write operations.
        """

        try:
            # =====
            log.info("opening tun interface")
            returnVal = os.open("/dev/net/tun", os.O_RDWR)
            ifs = ioctl(returnVal, TUNSETIFF, struct.pack("16sH", "tun%d", IFF_TUN))
437
            self.ifname = ifs[:16].strip("\x00")
438 439 440 441 442 443

            # =====
            log.info("configuring IPv6 address...")
            # ipv6_prefixStr = formatIPv6Addr(self.ipv6_prefix)
            # ipv6_hostStr = formatIPv6Addr(self.ipv6_host)

444 445 446
            # delete any : character in the host string (old API used to define those with that char)
            self.ipv6_host = self.ipv6_host.replace(":", "")

447 448
            v = os.system('ip tuntap add dev ' + self.ifname + ' mode tun user root')
            v = os.system('ip link set ' + self.ifname + ' up')
449 450
            v = os.system('ip -6 addr add ' + self.ipv6_prefix + '::' + self.ipv6_host + '/64 dev ' + self.ifname)
            v = os.system('ip -6 addr add fe80::' + self.ipv6_host + '/64 dev ' + self.ifname)
451

452
            # v = os.system("ip addr add " + self.ipv4_host + "/24 dev " + self.ifname)
453 454 455 456 457 458 459 460

            # =====
            log.info("adding static route route...")
            # added 'metric 1' for router-compatibility constraint
            # (show ping packet on wireshark but don't send to mote at all)

            # TODO: fix hard-coded value

461 462
            # os.system('ip -6 route add ' + ipv6_prefixStr + ':1415:9200::/96 dev ' + self.ifname + ' metric 1')
            os.system('ip -6 route add ' + self.ipv6_prefix + ':1415:9200::/96 dev ' + self.ifname + ' metric 1')
463 464 465 466
            # trying to set a gateway for this route
            # os.system('ip -6 route add ' + ipv6_prefixStr + '::/64 via ' + IPv6Prefix + ':' + ipv6_hostStr + '/64')

            # =====
467 468 469 470 471 472 473

            if self.ipv6_no_forwarding:
                log.info("disabling IPv6 forwarding...")
                os.system('echo 0 > /proc/sys/net/ipv6/conf/all/forwarding')
            else:
                log.info("enabling IPv6 forwarding...")
                os.system('echo 1 > /proc/sys/net/ipv6/conf/all/forwarding')
474 475 476

            # =====
            log.info('\ncreated following virtual interface:')
477
            os.system('ip addr show ' + self.ifname)
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

            # =====start radvd
            # os.system('radvd start')

        except IOError as err:
            # happens when not root
            log.error('WARNING: could not created tun interface. Are you root? ({0})'.format(err))
            returnVal = None

        return returnVal

    def _createTunReadThread(self):
        """
        Creates and starts the thread to read messages arriving from the
        TUN interface.
        """
        return TunReadThread(
495 496
            self.tunIf,
            self._tunToEventBus
497 498
        )

499
    def _tunToEventBus(self, data):
500 501 502 503 504
        """
        Called when receiving data from the TUN interface.

        This function forwards the data to the the EventBus.
        """
505

506
        routing_key = MsgPacketSniffedRaw.routing_key.replace('*', self.name)
507 508 509
        log.debug("Pushing message to topic: %s" % routing_key)

        self.packet_count += 1
510
        log.info("Messaged captured in tun. Pushing message to testing tool. Message count (uplink): %s"
511 512
                 % self.packet_count)

513
        # dispatch to EventBus
514 515
        m = MsgPacketSniffedRaw(
            interface_name=self.ifname,
516
            timestamp=time.time(),
517 518
            data=data
        )
519
        print(arrow_up)
520
        log.info('\n # # # # # # # # # # # # OPEN TUN # # # # # # # # # # # # ' +
521
                 '\n data packet TUN -> EventBus' +
522
                 '\n' + m.to_json() +
523 524
                 '\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # #'
                 )
525
        # do not re-encode on json, producer does serialization
526
        self.producer.publish(m.to_dict(),
527 528 529
                              exchange=self.exchange,
                              routing_key=routing_key)

530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    def _eventBusToTun(self, sender, signal, data):
        """
        Called when receiving data from the EventBus.

        This function forwards the data to the the TUN interface.
        """

        # abort if not tun interface
        if not self.tunIf:
            return

        # add tun header
        data = VIRTUALTUNID + data

        # convert data to string
        data = ''.join([chr(b) for b in data])

        try:
            # write over tuntap interface
            os.write(self.tunIf, data)
            if log.isEnabledFor(logging.DEBUG):
                log.debug("data dispatched to tun correctly {0}, {1}".format(signal, sender))
        except Exception as err:
            errMsg = formatCriticalMessage(err)
            log.critical(errMsg)

556 557 558 559 560 561

class OpenTunMACOS(object):
    '''
    Class which interfaces between a TUN virtual interface and an EventBus.
    '''

562
    def __init__(self, name, rmq_connection, rmq_exchange="amq.topic",
563
                 ipv6_prefix=None, ipv6_host=None, ipv6_no_forwarding=None,
564
                 ipv4_host=None, ipv4_network=None, ipv4_netmask=None):
565 566 567 568

        # RMQ setups
        self.connection = rmq_connection
        self.producer = self.connection.Producer(serializer='json')
569
        self.exchange = rmq_exchange
570 571

        self.name = name
572
        self.tun_name = ''
573
        self.packet_count = 0
574 575 576 577 578 579 580 581

        if ipv6_prefix is None:
            # self.ipv6_prefix = [0xbb, 0xbb, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
            ipv6_prefix = DEFAULT_IPV6_PREFIX
        self.ipv6_prefix = ipv6_prefix

        if ipv6_host is None:
            # self.ipv6_host = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]
582
            ipv6_host = "1"
583 584
        self.ipv6_host = ipv6_host

585 586 587 588
        if ipv6_no_forwarding is None:
            ipv6_no_forwarding = False
        self.ipv6_no_forwarding = ipv6_no_forwarding

589 590 591 592 593 594 595 596 597 598 599 600
        if ipv4_host is None:
            ipv4_host = "2.2.2.2"
        self.ipv4_host = ipv4_host

        if ipv4_network is None:
            ipv4_network = [10, 2, 0, 0]
        self.ipv4_network = ipv4_network

        if ipv4_netmask is None:
            ipv4_netmask = [255, 255, 0, 0]
        self.ipv4_netmask = ipv4_netmask

601
        log.debug("IP info: \n {}".format(self.get_tun_configuration()))
602 603 604 605 606 607 608 609

        # local variables
        self.tunIf = self._createTunIf()
        if self.tunIf:
            self.tunReadThread = self._createTunReadThread()
        else:
            self.tunReadThread = None

610
    # ======================== public ==========================================
611

612 613 614 615 616 617 618 619 620 621 622
    def get_tun_configuration(self):

        return {
            'ipv6_prefix': self.ipv6_prefix,
            'ipv6_host': self.ipv6_host,
            'ipv6_no_forwarding': self.ipv6_no_forwarding,
            'ipv4_host': self.ipv4_host,
            'ipv4_network': self.ipv4_network,
            'ipv4_netmask': self.ipv4_netmask,
        }

623
    # ======================== private =========================================
624 625 626 627 628 629 630 631 632 633 634

    def _getNetworkPrefix_notif(self, sender, signal, data):
        return self.ipv6_prefix

    def _createTunIf(self):
        '''
        Open a TUN/TAP interface and switch it to TUN mode.

        :returns: The handler of the interface, which can be used for later
            read/write operations.
        '''
635
        # =====
636 637 638

        # import random
        # TODO test concurrency problems with MacOs drivers when launching two agents in same PC
639 640 641
        # random_time = 1 + (random.randint(0, 1000) / 1000)
        # log.debug('waiting {rt} before starting the tun'.format(rt=random_time))
        # time.sleep(random_time)
642

643
        log.info("opening tun interface")
644 645
        tun_counter = 0
        while tun_counter < 16:
646 647
            try:
                import os
648 649
                self.ifname = 'tun{0}'.format(tun_counter)
                f = os.open("/dev/{0}".format(self.ifname), os.O_RDWR)
650 651
                break
            except OSError:
652
                tun_counter += 1
653

654
        if tun_counter == 16:
655 656 657
            raise OSError('TUN device not found: check if it exists or if it is busy.'
                          ' TunTap driver installed on MacOs?'
                          ' Running as root?')
658
        else:
659

660
            # =====
661 662 663 664
            log.info("configuring IPv6 address...")
            # prefixStr = u.formatIPv6Addr(openTun.IPV6PREFIX)
            # hostStr   = u.formatIPv6Addr(openTun.IPV6HOST)

665 666
            # v=os.system('ifconfig {0} inet6 {1}:{2} prefixlen 64'.format(self.ifname, self.prefixStr, hostStr))
            # v=os.system('ifconfig {0} inet6 fe80::{1} prefixlen 64 add'.format(self.ifname, hostStr))
667

668
            # delete starting ":"
669 670
            self.ipv6_host = self.ipv6_host.replace(":", "")

671 672 673
            v = os.system(
                'ifconfig {0} inet6 {1}::{2} prefixlen 64'.format(self.ifname, self.ipv6_prefix, self.ipv6_host))
            v = os.system('ifconfig {0} inet6 fe80::{1} prefixlen 64 add'.format(self.ifname, self.ipv6_host))
674

675
            # =====
676 677 678
            log.info("adding static route route...")
            # added 'metric 1' for router-compatibility constraint
            # (show ping packet on wireshark but don't send to mote at all)
679 680 681 682 683

            static_route = 'route add -inet6 {0}:1415:9200::/96 -interface {1}'.format(self.ipv6_prefix, self.ifname)
            log.info("trying with:" + static_route)
            os.system(static_route)

684
            # trying to set a gateway for this route
685
            # os.system('ip -6 route add ' + prefixStr + '::/64 via ' + IPv6Prefix + ':' + hostStr + '/64')
686

687
            # =====
688 689 690 691 692 693
            if self.ipv6_no_forwarding:
                log.info("disabling IPv6 forwarding...")
                os.system('sysctl -w net.inet6.ip6.forwarding=0')
            else:
                log.info("enabling IPv6 forwarding...")
                os.system('sysctl -w net.inet6.ip6.forwarding=1')
694

695
            # =====
696
            log.info('\ncreated following virtual interface:')
697
            os.system('ifconfig {0}'.format(self.ifname))
698

699 700
            # =====start radvd
            # os.system('radvd start')
701 702 703 704 705 706 707 708 709

            return f

    def _createTunReadThread(self):
        '''
        Creates and starts the thread to read messages arriving from the
        TUN interface.
        '''
        return TunReadThread(
710 711
            self.tunIf,
            self._tunToEventBus
712 713
        )

714
    def _tunToEventBus(self, data):
715 716 717 718 719
        """
        Called when receiving data from the TUN interface.

        This function forwards the data to the the EventBus.
        """
720

721
        routing_key = MsgPacketSniffedRaw.routing_key.replace('*', self.name)
722 723 724
        log.debug("Pushing message to topic: %s" % routing_key)

        self.packet_count += 1
725
        log.info("Messaged captured in tun. Pushing message to testing tool. Message count (uplink): %s"
726 727
                 % self.packet_count)

728
        # dispatch to EventBus
729 730
        m = MsgPacketSniffedRaw(
            interface_name=self.ifname,
731
            timestamp=time.time(),
732 733
            data=data
        )
734
        print(arrow_up)
735
        log.info('\n # # # # # # # # # # # # OPEN TUN # # # # # # # # # # # # ' +
736
                 '\n data packet TUN -> EventBus' +
737
                 '\n' + m.to_json() +
738 739
                 '\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # #'
                 )
740
        # do not re-encode on json, producer does serialization
741
        self.producer.publish(m.to_dict(),
742 743 744
                              exchange=self.exchange,
                              routing_key=routing_key)

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
    def _eventBusToTun(self, sender, signal, data):
        """
        Called when receiving data from the EventBus.

        This function forwards the data to the the TUN interface.
        """

        # abort if not tun interface
        if not self.tunIf:
            return

        # add tun header
        # data = VIRTUALTUNID + data

        # import binascii
        # stri = ""
        # for i in data:
        #     if type(i)==int:
        #         #stri += str(i)
        #         stri += binascii.hexlify(str(i))
        #     else:
        #         #stri += i.decode('utf-8')
        #         stri += binascii.hexlify(i.decode('utf-8'))

        log.info('\n # # # # # # # # # # # # OPEN TUN # # # # # # # # # # # # ' +
                 '\n data packet EventBus -> TUN' +
                 '\n' + json.dumps(data) +
                 '\n # # # # # # # # # # # # # # # # # # # # # # # # # # # # #'
                 )
        # convert data to string
        data = ''.join([chr(b) for b in data])

        try:
            # write over tuntap interface
            os.write(self.tunIf, data)
            if log.isEnabledFor(logging.DEBUG):
                log.debug("data dispatched to tun correctly {0}, {1}".format(signal, sender))
        except Exception as err:
            errMsg = formatCriticalMessage(err)
            log.critical(errMsg)


            # ======================== helpers =========================================