Hands off messages to well known flows.

def HandleWellKnownFlows(self, messages):
    """Hands off messages to well known flows."""
    msgs_by_wkf = {}
    result = []
    for msg in messages:
      # Regular message - queue it.
      if msg.response_id != 0:
        result.append(msg)
        continue

      # Well known flows:
      flow_name = msg.session_id.FlowName()

      if flow_name in self.well_known_flows:
        # This message should be processed directly on the front end.
        msgs_by_wkf.setdefault(flow_name, []).append(msg)

        # TODO(user): Deprecate in favor of 'well_known_flow_requests'
        # metric.
        stats_collector_instance.Get().IncrementCounter(
            "grr_well_known_flow_requests")

        stats_collector_instance.Get().IncrementCounter(
            "well_known_flow_requests", fields=[str(msg.session_id)])
      else:
        # Message should be queued to be processed in the backend.

        # Well known flows have a response_id==0, but if we queue up the state
        # as that it will overwrite some other message that is queued. So we
        # change it to a random number here.
        msg.response_id = random.UInt32()

        # Queue the message in the data store.
        result.append(msg)

    for flow_name, msg_list in iteritems(msgs_by_wkf):
      wkf = self.well_known_flows[flow_name]
      wkf.ProcessMessages(msg_list)

    return result