# Path: lib/cuckoo/common/config.py
# class Config:
#     """Configuration file parser."""
# 
#     def __init__(self, file_name="cuckoo", cfg=None):
#         """
#         @param file_name: file name without extension.
#         @param cfg: configuration file path.
#         """
#         config = ConfigParser.ConfigParser()
# 
#         if cfg:
#             config.read(cfg)
#         else:
#             config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name))
# 
#         for section in config.sections():
#             setattr(self, section, Dictionary())
#             for name, raw_value in config.items(section):
#                 try:
#                     # Ugly fix to avoid '0' and '1' to be parsed as a
#                     # boolean value.
#                     # We raise an exception to goto fail^w parse it
#                     # as integer.
#                     if config.get(section, name) in ["0", "1"]:
#                         raise ValueError
# 
#                     value = config.getboolean(section, name)
#                 except ValueError:
#                     try:
#                         value = config.getint(section, name)
#                     except ValueError:
#                         value = config.get(section, name)
# 
#                 setattr(getattr(self, section), name, value)
# 
#     def get(self, section):
#         """Get option.
#         @param section: section to fetch.
#         @raise CuckooOperationalError: if section not found.
#         @return: option value.
#         """
#         try:
#             return getattr(self, section)
#         except AttributeError as e:
#             raise CuckooOperationalError("Option %s is not found in "
#                                          "configuration, error: %s" %
#                                          (section, e))
# 
# Path: lib/cuckoo/common/utils.py
# def create_folder(root=".", folder=None):
#     """Create directory.
#     @param root: root path.
#     @param folder: folder name to be created.
#     @raise CuckooOperationalError: if fails to create folder.
#     """
#     folder_path = os.path.join(root, folder)
#     if folder and not os.path.isdir(folder_path):
#         try:
#             os.makedirs(folder_path)
#         except OSError:
#             raise CuckooOperationalError("Unable to create folder: %s" %
#                                          folder_path)
# 
# class Singleton(type):
#     """Singleton.
#     @see: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
#     """
#     _instances = {}
# 
#     def __call__(cls, *args, **kwargs):
#         if cls not in cls._instances:
#             cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
#         return cls._instances[cls]
# 
# def logtime(dt):
#     """Formats time like a logger does, for the csv output
#        (e.g. "2013-01-25 13:21:44,590")
#     @param dt: datetime object
#     @return: time string
#     """
#     t = time.strftime("%Y-%m-%d %H:%M:%S", dt.timetuple())
#     s = "%s,%03d" % (t, dt.microsecond/1000)
#     return s


import os
import socket
import select
import logging
import datetime
import SocketServer
from threading import Event, Thread
from lib.cuckoo.common.config import Config
from lib.cuckoo.common.constants import CUCKOO_ROOT
from lib.cuckoo.common.exceptions import CuckooOperationalError
from lib.cuckoo.common.exceptions import CuckooCriticalError
from lib.cuckoo.common.exceptions import CuckooResultError
from lib.cuckoo.common.netlog import NetlogParser, BsonParser
from lib.cuckoo.common.utils import create_folder, Singleton, logtime
# Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.



log = logging.getLogger(__name__)

BUFSIZE = 16 * 1024
EXTENSIONS = {
    NetlogParser: ".raw",
    BsonParser: ".bson",
}

class Disconnect(Exception):
    pass


class ResultServer(SocketServer.ThreadingTCPServer, object):
    """Result server. Singleton!

    This class handles results coming back from the analysis machines.
    """


# Path: lib/cuckoo/common/config.py
# class Config:
#     """Configuration file parser."""
# 
#     def __init__(self, file_name="cuckoo", cfg=None):
#         """
#         @param file_name: file name without extension.
#         @param cfg: configuration file path.
#         """
#         config = ConfigParser.ConfigParser()
# 
#         if cfg:
#             config.read(cfg)
#         else:
#             config.read(os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % file_name))
# 
#         for section in config.sections():
#             setattr(self, section, Dictionary())
#             for name, raw_value in config.items(section):
#                 try:
#                     # Ugly fix to avoid '0' and '1' to be parsed as a
#                     # boolean value.
#                     # We raise an exception to goto fail^w parse it
#                     # as integer.
#                     if config.get(section, name) in ["0", "1"]:
#                         raise ValueError
# 
#                     value = config.getboolean(section, name)
#                 except ValueError:
#                     try:
#                         value = config.getint(section, name)
#                     except ValueError:
#                         value = config.get(section, name)
# 
#                 setattr(getattr(self, section), name, value)
# 
#     def get(self, section):
#         """Get option.
#         @param section: section to fetch.
#         @raise CuckooOperationalError: if section not found.
#         @return: option value.
#         """
#         try:
#             return getattr(self, section)
#         except AttributeError as e:
#             raise CuckooOperationalError("Option %s is not found in "
#                                          "configuration, error: %s" %
#                                          (section, e))
# 
# Path: lib/cuckoo/common/utils.py
# def create_folder(root=".", folder=None):
#     """Create directory.
#     @param root: root path.
#     @param folder: folder name to be created.
#     @raise CuckooOperationalError: if fails to create folder.
#     """
#     folder_path = os.path.join(root, folder)
#     if folder and not os.path.isdir(folder_path):
#         try:
#             os.makedirs(folder_path)
#         except OSError:
#             raise CuckooOperationalError("Unable to create folder: %s" %
#                                          folder_path)
# 
# class Singleton(type):
#     """Singleton.
#     @see: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python
#     """
#     _instances = {}
# 
#     def __call__(cls, *args, **kwargs):
#         if cls not in cls._instances:
#             cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
#         return cls._instances[cls]
# 
# def logtime(dt):
#     """Formats time like a logger does, for the csv output
#        (e.g. "2013-01-25 13:21:44,590")
#     @param dt: datetime object
#     @return: time string
#     """
#     t = time.strftime("%Y-%m-%d %H:%M:%S", dt.timetuple())
#     s = "%s,%03d" % (t, dt.microsecond/1000)
#     return s


# Path: lib/cuckoo/core/resultserver.py
import os
import socket
import select
import logging
import datetime
import SocketServer
from threading import Event, Thread
from lib.cuckoo.common.config import Config
from lib.cuckoo.common.constants import CUCKOO_ROOT
from lib.cuckoo.common.exceptions import CuckooOperationalError
from lib.cuckoo.common.exceptions import CuckooCriticalError
from lib.cuckoo.common.exceptions import CuckooResultError
from lib.cuckoo.common.netlog import NetlogParser, BsonParser
from lib.cuckoo.common.utils import create_folder, Singleton, logtime

# Copyright (C) 2010-2015 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.



log = logging.getLogger(__name__)

BUFSIZE = 16 * 1024
EXTENSIONS = {
    NetlogParser: ".raw",
    BsonParser: ".bson",
}

class Disconnect(Exception):
    pass


class ResultServer(SocketServer.ThreadingTCPServer, object):
    """Result server. Singleton!

    This class handles results coming back from the analysis machines.
    """


    __metaclass__ = Singleton