/* metadata.cc
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 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 "metadata.h"

using namespace trafficmeter;

/**************************************************************************************************************/
Metadata::Metadata( Timestamp timestamp, const uint8_t* data2, unsigned nBytes2 ) :
    timestamp( timestamp ),
    nBytes2( nBytes2 ),
    nBytes( 0 ),
    offsetLayer3( 14 ),
    offsetLayer4( 0 ),
    etype( ntohs(*reinterpret_cast<const uint16_t*>(data2+12)) ),
    vlan( 0 ),
    smac( data2 + 6 ),
    dmac( data2 ),
    proto( 0 ),
    sport( 0 ),
    dport( 0 )
{
    if ( etype == 0x8100 )
    {
        etype = ntohs( *reinterpret_cast<const uint16_t*>(data2 + 16) );
        vlan = ntohs( *reinterpret_cast<const uint16_t*>(data2 + 14) ) & 0xfff;
        offsetLayer3 += 4;
    }

    if ( etype == 0x0800 )  // IPv4
    {
        nBytes = ntohs( *reinterpret_cast<const uint16_t*>(data2 + offsetLayer3 + 2) );
        proto = *( data2 + offsetLayer3 + 9 );
        sip = ntohl( *reinterpret_cast<const uint32_t*>(data2 + offsetLayer3 + 12) );
        dip = ntohl( *reinterpret_cast<const uint32_t*>(data2 + offsetLayer3 + 16) );
    }

    if ( proto == 6 || proto == 17 )    // TCP or UDP
    {
        offsetLayer4 = offsetLayer3 + ( (*(data2+offsetLayer3) & 0xf) << 2 );
        sport = ntohs( *reinterpret_cast<const uint16_t*>(data2 + offsetLayer4) );
        dport = ntohs( *reinterpret_cast<const uint16_t*>(data2 + offsetLayer4 + 2) );
    }
}
