# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Mobius Forensic Toolkit
# Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019 Eduardo Aguiar
#
# This program 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 2, or (at your option) any later
# version.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
import pymobius.util
import mobius

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief generic cookie class
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
class Cookie (object):
  pass

# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# @brief Internet Explorer cookie file decoder
# @author Eduardo Aguiar
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
def decode (reader):

  # check reader
  if not reader:
    return

  # decode cookie file
  cookies = []
  state = 0
  time_low = 0
  data = reader.read ()

  try:
    for line in data.split ('\n'):
      line = line.rstrip ()

      if state == 0:
        cookie = Cookie ()
        cookie.name = line
        state = state + 1

      elif state == 1:
        cookie.value = line
        state = state + 1

      elif state == 2:
        cookie.domain = line[:-1]		# remove trailing '/'
        state = state + 1
      
      elif state == 3:
        cookie.flags = line
        state = state + 1

      elif state == 4:
        time_low = int (line)
        state = state + 1

      elif state == 5:
        time_high = int (line)
        timestamp = (time_high << 32) | time_low
        cookie.expiration_time = mobius.datetime.new_datetime_from_nt_timestamp (timestamp)
        state = state + 1

      elif state == 6:
        time_low = int (line)
        state = state + 1

      elif state == 7:
        time_high = int (line)
        timestamp = (time_high << 32) | time_low
        cookie.creation_time = mobius.datetime.new_datetime_from_nt_timestamp (timestamp)
        state = state + 1

      elif state == 8:
        cookies.append (cookie)
        state = 0

  except Exception, e:
    pass

  return cookies
