Parses a Windows EventLog (EVT) file-like object.

    Args:
      parser_mediator (ParserMediator): mediates interactions between parsers
          and other components, such as storage and dfvfs.
      file_object (dfvfs.FileIO): a file-like object.
507563
def ParseFileObject(self, parser_mediator, file_object):
    
    evt_file = pyevt.file()
    evt_file.set_ascii_codepage(parser_mediator.codepage)

    try:
      evt_file.open_file_object(file_object)
    except IOError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to open file with error: {0!s}'.format(exception))
      return

    try:
      self._ParseRecords(parser_mediator, evt_file)
    finally:
      evt_file.close()
215829
def parse_item(location: str, item_type: Type[T], item_name_for_log: str = None,
               file_mapping_conf: FileMappingConfiguration = None,
               logger: Logger = default_logger, lazy_mfcollection_parsing: bool = False) -> T:
    
    rp = _create_parser_from_default(logger)
    opts = create_parser_options(lazy_mfcollection_parsing=lazy_mfcollection_parsing)
    return rp.parse_item(location, item_type, item_name_for_log=item_name_for_log, file_mapping_conf=file_mapping_conf,
                         options=opts)
672232
def ParseFileObject(self, parser_mediator, file_object):
    
    file_header_map = self._GetDataTypeMap('systemd_journal_file_header')

    try:
      file_header, _ = self._ReadStructureFromFileObject(
          file_object, 0, file_header_map)
    except (ValueError, errors.ParseError) as exception:
      raise errors.UnableToParseFile(
          'Unable to parse file header with error: {0!s}'.format(
              exception))

    if file_header.signature != self._FILE_SIGNATURE:
      raise errors.UnableToParseFile('Invalid file signature.')

    if file_header.header_size not in self._SUPPORTED_FILE_HEADER_SIZES:
      raise errors.UnableToParseFile(
          'Unsupported file header size: {0:d}.'.format(
              file_header.header_size))

    data_hash_table_end_offset = (
        file_header.data_hash_table_offset +
        file_header.data_hash_table_size)
    field_hash_table_end_offset = (
        file_header.field_hash_table_offset +
        file_header.field_hash_table_size)
    self._maximum_journal_file_offset = max(
        data_hash_table_end_offset, field_hash_table_end_offset)

    entry_object_offsets = self._ParseEntryObjectOffsets(
        file_object, file_header.entry_array_offset)

    for entry_object_offset in entry_object_offsets:
      if entry_object_offset == 0:
        continue

      try:
        fields = self._ParseJournalEntry(file_object, entry_object_offset)
      except errors.ParseError as exception:
        parser_mediator.ProduceExtractionWarning((
            'Unable to parse journal entry at offset: 0x{0:08x} with '
            'error: {1!s}').format(entry_object_offset, exception))
        return

      event_data = SystemdJournalEventData()

      event_data.body = fields.get('MESSAGE', None)
      event_data.hostname = fields.get('_HOSTNAME', None)
      event_data.reporter = fields.get('SYSLOG_IDENTIFIER', None)

      if event_data.reporter and event_data.reporter != 'kernel':
        event_data.pid = fields.get('_PID', fields.get('SYSLOG_PID', None))

      date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
          timestamp=fields['real_time'])
      event = time_events.DateTimeValuesEvent(
          date_time, definitions.TIME_DESCRIPTION_WRITTEN)
      parser_mediator.ProduceEventWithEventData(event, event_data)
338256
def GetEntries(
      self, parser_mediator, cookie_data=None, url=None, **kwargs):
    
    fields = cookie_data.split('.')
    number_of_fields = len(fields)

    if number_of_fields != 1:
      parser_mediator.ProduceExtractionWarning(
          'unsupported number of fields: {0:d} in cookie: {1:s}'.format(
              number_of_fields, self.COOKIE_NAME))
      return

    try:
      # TODO: fix that we're losing precision here use dfdatetime.
      last_visit_posix_time = int(fields[0], 10) / 10000000
    except ValueError:
      last_visit_posix_time = None

    if last_visit_posix_time is not None:
      date_time = dfdatetime_posix_time.PosixTime(
          timestamp=last_visit_posix_time)
      timestamp_description = definitions.TIME_DESCRIPTION_LAST_VISITED
    else:
      date_time = dfdatetime_semantic_time.SemanticTime('Not set')
      timestamp_description = definitions.TIME_DESCRIPTION_NOT_A_TIME

    event_data = GoogleAnalyticsEventData('utmt')
    event_data.cookie_name = self.COOKIE_NAME
    event_data.url = url

    event = time_events.DateTimeValuesEvent(date_time, timestamp_description)
    parser_mediator.ProduceEventWithEventData(event, event_data)
887653
def CompileReport(self, mediator):
    
    report_text = 'Tagging plugin produced {0:d} tags.\n'.format(
        self._number_of_event_tags)
    self._number_of_event_tags = 0
    return reports.AnalysisReport(plugin_name=self.NAME, text=report_text)
732666
def ExamineEvent(self, mediator, event):
    
    if self._session_end_timestamp is None:
      self._session_end_timestamp = (
          event.timestamp + self._maximum_pause_microseconds)
      self._events_per_session.append(0)

    if event.timestamp > self._session_end_timestamp:
      self._session_counter += 1
      self._events_per_session.append(0)

    self._session_end_timestamp = (
        event.timestamp + self._maximum_pause_microseconds)
    # The counter for the current session is the always the last item in
    # the list.
    self._events_per_session[-1] += 1

    label = 'session_{0:d}'.format(self._session_counter)
    event_tag = self._CreateEventTag(event, self._EVENT_TAG_COMMENT, [label])
    mediator.ProduceEventTag(event_tag)
    self._number_of_event_tags += 1
1238521
def parse_event_record(self, node):
        

        if self.current_simulation == None:
            self.raise_error('<EventRecord> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<EventRecord> must specify a quantity.')

        if 'eventport' in node.lattrib:
            eventPort = node.lattrib['eventport']
        else:
            self.raise_error('<EventRecord> must specify an eventPort.')


        self.current_simulation.add_event_record(EventRecord(quantity, eventPort))
1324478
def _ProcessEvent(self, mediator, event):
    
    try:
      self._analysis_plugin.ExamineEvent(mediator, event)

    except Exception as exception:  # pylint: disable=broad-except
      self.SignalAbort()

      # TODO: write analysis error.

      if self._debug_output:
        logger.warning('Unhandled exception while processing event object.')
        logger.exception(exception)
25249
def _ProcessDirectory(self, mediator, file_entry):
    
    self.processing_status = definitions.STATUS_INDICATOR_COLLECTING

    if self._processing_profiler:
      self._processing_profiler.StartTiming('collecting')

    for sub_file_entry in file_entry.sub_file_entries:
      if self._abort:
        break

      try:
        if not sub_file_entry.IsAllocated():
          continue

      except dfvfs_errors.BackEndError as exception:
        warning_message = (
            'unable to process directory entry: {0:s} with error: '
            '{1!s}').format(sub_file_entry.name, exception)
        mediator.ProduceExtractionWarning(
            warning_message, path_spec=file_entry.path_spec)
        continue

      # For TSK-based file entries only, ignore the virtual /$OrphanFiles
      # directory.
      if sub_file_entry.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK:
        if file_entry.IsRoot() and sub_file_entry.name == '$OrphanFiles':
          continue

      event_source = event_sources.FileEntryEventSource(
          path_spec=sub_file_entry.path_spec)

      # TODO: move this into a dfVFS file entry property.
      stat_object = sub_file_entry.GetStat()
      if stat_object:
        event_source.file_entry_type = stat_object.type

      mediator.ProduceEventSource(event_source)

      self.last_activity_timestamp = time.time()

    if self._processing_profiler:
      self._processing_profiler.StopTiming('collecting')

    self.processing_status = definitions.STATUS_INDICATOR_RUNNING
1147472
def parse_event_writer(self, node):
        

        if 'path' in node.lattrib:
            path = node.lattrib['path']
        else:
            self.raise_error('<EventWriter> must specify a path.')

        if 'filename' in node.lattrib:
            file_path = node.lattrib['filename']
        else:
            self.raise_error("Event writer for '{0}' must specify a filename.",
                             path)
                             
        if 'format' in node.lattrib:
            format = node.lattrib['format']
        else:
            self.raise_error("Event writer for '{0}' must specify a format.",
                             path)

        self.current_simulation.add_event_writer(EventWriter(path, file_path, format))
368995
def CompileReport(self, mediator):
    
    report_text = [
        'Sessionize plugin identified {0:d} sessions and '
        'applied {1:d} tags.'.format(
            len(self._events_per_session), self._number_of_event_tags)]
    for session, event_count in enumerate(self._events_per_session):
      report_text.append('\tSession {0:d}: {1:d} events'.format(
          session, event_count))
    report_text = '\n'.join(report_text)
    return reports.AnalysisReport(plugin_name=self.NAME, text=report_text)
617424
def ParseMessageRow(self, parser_mediator, query, row, **unused_kwargs):
    
    query_hash = hash(query)

    event_data = KikIOSMessageEventData()
    event_data.body = self._GetRowValue(query_hash, row, 'ZBODY')
    event_data.displayname = self._GetRowValue(query_hash, row, 'ZDISPLAYNAME')
    event_data.message_status = self._GetRowValue(query_hash, row, 'ZSTATE')
    event_data.message_type = self._GetRowValue(query_hash, row, 'ZTYPE')
    event_data.offset = self._GetRowValue(query_hash, row, 'id')
    event_data.query = query
    event_data.username = self._GetRowValue(query_hash, row, 'ZUSERNAME')

    timestamp = self._GetRowValue(query_hash, row, 'ZRECEIVEDTIMESTAMP')
    # Convert the floating point value to an integer.
    timestamp = int(timestamp)
    date_time = dfdatetime_cocoa_time.CocoaTime(timestamp=timestamp)
    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_CREATION)
    parser_mediator.ProduceEventWithEventData(event, event_data)
619376
def parse(self, stream, media_type=None, parser_context=None):
        
        result = super(JSONParser, self).parse(
            stream, media_type=media_type, parser_context=parser_context
        )

        if not isinstance(result, dict) or 'data' not in result:
            raise ParseError('Received document does not contain primary data')

        data = result.get('data')
        view = parser_context['view']

        from rest_framework_json_api.views import RelationshipView
        if isinstance(view, RelationshipView):
            # We skip parsing the object as JSONAPI Resource Identifier Object and not a regular
            # Resource Object
            if isinstance(data, list):
                for resource_identifier_object in data:
                    if not (
                        resource_identifier_object.get('id') and
                        resource_identifier_object.get('type')
                    ):
                        raise ParseError(
                            'Received data contains one or more malformed JSONAPI '
                            'Resource Identifier Object(s)'
                        )
            elif not (data.get('id') and data.get('type')):
                raise ParseError('Received data is not a valid JSONAPI Resource Identifier Object')

            return data

        request = parser_context.get('request')

        # Check for inconsistencies
        if request.method in ('PUT', 'POST', 'PATCH'):
            resource_name = utils.get_resource_name(
                parser_context, expand_polymorphic_types=True)
            if isinstance(resource_name, six.string_types):
                if data.get('type') != resource_name:
                    raise exceptions.Conflict(
                        "The resource object's type ({data_type}) is not the type that "
                        "constitute the collection represented by the endpoint "
                        "({resource_type}).".format(
                            data_type=data.get('type'),
                            resource_type=resource_name))
            else:
                if data.get('type') not in resource_name:
                    raise exceptions.Conflict(
                        "The resource object's type ({data_type}) is not the type that "
                        "constitute the collection represented by the endpoint "
                        "(one of [{resource_types}]).".format(
                            data_type=data.get('type'),
                            resource_types=", ".join(resource_name)))
        if not data.get('id') and request.method in ('PATCH', 'PUT'):
            raise ParseError("The resource identifier object must contain an 'id' member")

        # Construct the return data
        serializer_class = getattr(view, 'serializer_class', None)
        parsed_data = {'id': data.get('id')} if 'id' in data else {}
        # `type` field needs to be allowed in none polymorphic serializers
        if serializer_class is not None:
            if issubclass(serializer_class, serializers.PolymorphicModelSerializer):
                parsed_data['type'] = data.get('type')
        parsed_data.update(self.parse_attributes(data))
        parsed_data.update(self.parse_relationships(data))
        parsed_data.update(self.parse_metadata(result))
        return parsed_data
1228029
def ParseFileEntry(self, parser_mediator, file_entry):
    
    stat_object = file_entry.GetStat()
    if not stat_object:
      return

    file_system_type = self._GetFileSystemTypeFromFileEntry(file_entry)

    event_data = FileStatEventData()
    event_data.file_entry_type = stat_object.type
    event_data.file_size = getattr(stat_object, 'size', None)
    event_data.file_system_type = file_system_type
    event_data.is_allocated = file_entry.IsAllocated()

    if file_entry.access_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.access_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.creation_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.creation_time, definitions.TIME_DESCRIPTION_CREATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.change_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.change_time, definitions.TIME_DESCRIPTION_CHANGE)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    if file_entry.modification_time:
      event = time_events.DateTimeValuesEvent(
          file_entry.modification_time,
          definitions.TIME_DESCRIPTION_MODIFICATION)
      parser_mediator.ProduceEventWithEventData(event, event_data)

    for time_attribute, usage in self._TIMESTAMP_DESCRIPTIONS.items():
      posix_time = getattr(stat_object, time_attribute, None)
      if posix_time is None:
        continue

      nano_time_attribute = '{0:s}_nano'.format(time_attribute)
      nano_time_attribute = getattr(stat_object, nano_time_attribute, None)

      timestamp = posix_time * 1000000
      if nano_time_attribute is not None:
        # Note that the _nano values are in intervals of 100th nano seconds.
        micro_time_attribute, _ = divmod(nano_time_attribute, 10)
        timestamp += micro_time_attribute

      # TSK will return 0 if the timestamp is not set.
      if (file_entry.type_indicator == dfvfs_definitions.TYPE_INDICATOR_TSK and
          not timestamp):
        continue

      date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
          timestamp=timestamp)
      event = time_events.DateTimeValuesEvent(date_time, usage)
      parser_mediator.ProduceEventWithEventData(event, event_data)
389933
def CompileReport(self, mediator):
    
    # TODO: move YAML representation out of plugin and into serialization.
    lines_of_text = []
    if self._output_format == 'yaml':
      lines_of_text.append(
          yaml.safe_dump_all(self._service_collection.services))
    else:
      lines_of_text.append('Listing Windows Services')
      for service in self._service_collection.services:
        lines_of_text.append(self._FormatServiceText(service))
        lines_of_text.append('')

    lines_of_text.append('')
    report_text = '\n'.join(lines_of_text)
    return reports.AnalysisReport(plugin_name=self.NAME, text=report_text)
1188103
function FileMediatorService(mediator, config) {
  this.mediator = mediator;
  this.config = config || {};
  
  this.usersTopics = new MediatorTopicUtility(mediator).prefix(CONSTANTS.TOPIC_PREFIX).entity(CONSTANTS.USERS_ENTITY_NAME);
  this.filesTopics = new MediatorTopicUtility(mediator).prefix(CONSTANTS.TOPIC_PREFIX).entity(CONSTANTS.FILES_ENTITY_NAME);
  this.fileUITopics = new MediatorTopicUtility(mediator).prefix(CONSTANTS.FILE_UI_TOPIC_PREFIX).entity(CONSTANTS.FILE);
}
907504
def Parse(self, parser_mediator):
    
    file_entry = parser_mediator.GetFileEntry()
    if not file_entry:
      raise errors.UnableToParseFile('Invalid file entry')

    parser_mediator.AppendToParserChain(self)
    try:
      self.ParseFileEntry(parser_mediator, file_entry)
    finally:
      parser_mediator.PopFromParserChain()