/* erspan.cc
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2020, 2021 Askar
    Almatov

    This file is part of Trafficmeter.

    Trafficmeter is free software: you can redistribute it and/or modify it under the terms of the GNU General
    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    Trafficmeter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License along with Trafficmeter. If not, see
    <http://www.gnu.org/licenses/>.
*/

#include "endian64.h"
#include "erspan.h"

using namespace trafficmeter;

constexpr const unsigned    MIN_FRAME_SIZE_ = 38 + 64;  // 64 is a minimal Ethernet frame length by IEEE 802.3

/**************************************************************************************************************/
Erspan::Erspan( const uint8_t* dataErspan, unsigned nBytesErspan )
{
    unsigned  payload = 0;

    if
    (
        ( (be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+32)) << 16) >> 32 ) == 0x88be &&  // 34x000088be
        dataErspan[ 23 ] == '\x2f' &&                                                              // 23x2f
        ( (be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+8)) << 32) >> 40 ) == 0x80045 &&  // 12x080045
        nBytesErspan >= MIN_FRAME_SIZE_
    )
    {
        payload = 38;
    }
    else if
    (
        ( be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+40)) >> 48 ) == 0x88be &&          // 40x88be
        ( be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+32)) << 48 ) == 0 &&               // 38x0000
        dataErspan[ 27 ] == '\x2f' &&                                                              // 27x2f
        ( (be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+8)) << 32) >> 48 ) == 0x8100 &&   // 12x8100
        ( be64toh(*reinterpret_cast<const uint64_t*>(dataErspan+16)) >> 40 ) == 0x80045 &&         // 16x080045
        nBytesErspan >= MIN_FRAME_SIZE_ + 4
    )
    {
        payload = 42;
    }

    data2_ = dataErspan + payload;
    nBytes2_ = nBytesErspan - payload;
}
