text
stringlengths
81
112k
Set multiple attributes' values for this subject in one operation. def MultiSet(self, subject, values, timestamp=None, replace=True, sync=True, to_delete=None): """Set multiple attributes' values for this subject in one opera...
Get connection from pool and execute query. def ExecuteQuery(self, query, args=None): """Get connection from pool and execute query.""" def Action(connection): connection.cursor.execute(query, args) rowcount = connection.cursor.rowcount results = connection.cursor.fetchall() return res...
Get connection from pool and execute transaction. def _ExecuteTransaction(self, transaction): """Get connection from pool and execute transaction.""" def Action(connection): connection.cursor.execute("START TRANSACTION") for query in transaction: connection.cursor.execute(query["query"], q...
Build a mapping between column names and types. def _CalculateAttributeStorageTypes(self): """Build a mapping between column names and types.""" self.attribute_types = {} for attribute in itervalues(aff4.Attribute.PREDICATES): self.attribute_types[attribute.predicate] = ( attribute.attribu...
Encode the value for the attribute. def _Encode(self, value): """Encode the value for the attribute.""" try: return value.SerializeToString().encode("hex") except AttributeError: if isinstance(value, (int, long)): return str(value).encode("hex") else: # Types "string" and ...
Build the SELECT query to be executed. def _BuildQuery(self, subject, attribute=None, timestamp=None, limit=None, is_prefix=False): """Build the SELECT query to be executed.""" args = [] subject = utils.SmartUnicode(s...
Build the DELETE query to be executed. def _BuildDelete(self, subject, attribute=None, timestamp=None): """Build the DELETE query to be executed.""" subjects_q = { "query": "DELETE subjects FROM subjects WHERE hash=unhex(md5(%s))", "args": [subject] } aff4_q = { "query": "DELET...
Create a timestamp using a start and end time. Args: start: Start timestamp. end: End timestamp. Returns: A tuple (start, end) of converted timestamps or None for all time. def _MakeTimestamp(self, start=None, end=None): """Create a timestamp using a start and end time. Args: ...
Remove the lock. Note that this only resets the lock if we actually hold it since lock_expiration == self.expires and lock_owner = self.lock_token. def Release(self): """Remove the lock. Note that this only resets the lock if we actually hold it since lock_expiration == self.expires and lock_owne...
Finds objects associated with keywords. Find the names related to all keywords. Args: keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this point in time. ...
Finds all objects associated with any of the keywords. Args: keywords: A collection of keywords that we are interested in. start_time: Only considers keywords added at or after this point in time. end_time: Only considers keywords at or before this point in time. last_seen_map: If present, ...
Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name. def AddKeywordsForName(self, name, keywords): """Associates keywords with name. Reco...
Removes keywords for a name. Args: name: A name which should not be associated with some keywords anymore. keywords: A collection of keywords. def RemoveKeywordsForName(self, name, keywords): """Removes keywords for a name. Args: name: A name which should not be associated with some key...
Reads an old config file and imports keys and user accounts. def ImportConfig(filename, config): """Reads an old config file and imports keys and user accounts.""" sections_to_import = ["PrivateKeys"] entries_to_import = [ "Client.executable_signing_public_key", "CA.certificate", "Frontend.certificat...
Continually ask a question until the output_re is matched. def RetryQuestion(question_text, output_re="", default_val=None): """Continually ask a question until the output_re is matched.""" while True: if default_val is not None: new_text = "%s [%s]: " % (question_text, default_val) else: new_t...
This configures the hostnames stored in the config. def ConfigureHostnames(config, external_hostname = None): """This configures the hostnames stored in the config.""" if not external_hostname: try: external_hostname = socket.gethostname() except (OSError, IOError): print("Sorry, we couldn't gu...
Checks whether a connection can be established to MySQL. Args: db_options: A dict mapping GRR MySQL config options to their values. Returns: A boolean indicating whether a connection could be made to a MySQL server instance with the given options. def CheckMySQLConnection(db_options): """Checks whe...
Prompts the user for configuration details for a MySQL datastore. def ConfigureMySQLDatastore(config): """Prompts the user for configuration details for a MySQL datastore.""" print("GRR will use MySQL as its database backend. Enter connection details:") datastore_init_complete = False db_options = {} while n...
Guides the user through configuration of the datastore. def ConfigureDatastore(config): """Guides the user through configuration of the datastore.""" print("\n\n-=GRR Datastore=-\n" "For GRR to work each GRR server has to be able to communicate with\n" "the datastore. To do this we need to configur...
Guides the user through configuration of various URLs used by GRR. def ConfigureUrls(config, external_hostname = None): """Guides the user through configuration of various URLs used by GRR.""" print("\n\n-=GRR URLs=-\n" "For GRR to work each client has to be able to communicate with the\n" "server....
Guides the user through email setup. def ConfigureEmails(config): """Guides the user through email setup.""" print("\n\n-=GRR Emails=-\n" "GRR needs to be able to send emails for various logging and\n" "alerting functions. The email domain will be appended to GRR\n" "usernames when sending ...
Call pip to install the templates. def InstallTemplatePackage(): """Call pip to install the templates.""" virtualenv_bin = os.path.dirname(sys.executable) extension = os.path.splitext(sys.executable)[1] pip = "%s/pip%s" % (virtualenv_bin, extension) # Install the GRR server component to satisfy the dependen...
Performs the final steps of config initialization. def FinalizeConfigInit(config, token, admin_password = None, redownload_templates = False, repack_templates = True, prompt = True): """Performs the fin...
Initialize or update a GRR configuration. def Initialize(config=None, external_hostname = None, admin_password = None, redownload_templates = False, repack_templates = True, token = None): """Initialize or update a GRR configuration.""" pr...
Initialize GRR with no prompts. Args: config: config object external_hostname: A hostname. admin_password: A password used for the admin user. mysql_hostname: A hostname used for establishing connection to MySQL. mysql_port: A port used for establishing connection to MySQL. mysql_username: A ...
Signs a binary and uploads it to the datastore. Args: source_path: Path to the binary to upload. binary_type: Type of the binary, e.g python-hack or executable. platform: Client platform where the binary is intended to be run. upload_subdirectory: Path of a subdirectory to upload the binary to, ...
Creates a new GRR user. def CreateUser(username, password=None, is_admin=False): """Creates a new GRR user.""" grr_api = maintenance_utils.InitGRRRootAPI() try: user_exists = grr_api.GrrUser(username).Get() is not None except api_errors.ResourceNotFoundError: user_exists = False if user_exists: r...
Updates the password or privilege-level for a user. def UpdateUser(username, password=None, is_admin=False): """Updates the password or privilege-level for a user.""" user_type, password = _GetUserTypeAndPassword( username, password=password, is_admin=is_admin) grr_api = maintenance_utils.InitGRRRootAPI() ...
Returns a string with summary info for a user. def GetUserSummary(username): """Returns a string with summary info for a user.""" grr_api = maintenance_utils.InitGRRRootAPI() try: return _Summarize(grr_api.GrrUser(username).Get().data) except api_errors.ResourceNotFoundError: raise UserNotFoundError(us...
Returns a string containing summary info for all GRR users. def GetAllUserSummaries(): """Returns a string containing summary info for all GRR users.""" grr_api = maintenance_utils.InitGRRRootAPI() user_wrappers = sorted(grr_api.ListGrrUsers(), key=lambda x: x.username) summaries = [_Summarize(w.data) for w in...
Returns a string with summary info for a user. def _Summarize(user_info): """Returns a string with summary info for a user.""" return "Username: %s\nIs Admin: %s" % ( user_info.username, user_info.user_type == api_user.ApiGrrUser.UserType.USER_TYPE_ADMIN)
Deletes a GRR user from the datastore. def DeleteUser(username): """Deletes a GRR user from the datastore.""" grr_api = maintenance_utils.InitGRRRootAPI() try: grr_api.GrrUser(username).Get().Delete() except api_errors.ResourceNotFoundError: raise UserNotFoundError(username)
Returns the user-type and password for a user. Args: username: Username for the user. password: Password for the user. If None, or not provided, we will prompt for one via the terminal. is_admin: Indicates whether the user should have admin privileges. def _GetUserTypeAndPassword(username, passwor...
Creates a Responses object from new style flow request and responses. def FromResponses(cls, request=None, responses=None): """Creates a Responses object from new style flow request and responses.""" res = cls() res.request = request if request: res.request_data = request.request_data for r ...
Creates a Responses object from old style flow request and responses. def FromLegacyResponses(cls, request=None, responses=None): """Creates a Responses object from old style flow request and responses.""" res = cls() res.request = request if request: res.request_data = rdf_protodict.Dict(request...
Run the kill. def Run(self, unused_arg): """Run the kill.""" # Send a message back to the service to say that we are about to shutdown. reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK) # Queue up the response message, jump the queue. self.SendReply(reply, message_type=rdf_f...
Retrieve the configuration except for the blocked parameters. def Run(self, unused_arg): """Retrieve the configuration except for the blocked parameters.""" out = self.out_rdfvalues[0]() for descriptor in config.CONFIG.type_infos: if descriptor.name in self.BLOCKED_PARAMETERS: value = "[Reda...
Does the actual work. def Run(self, arg): """Does the actual work.""" try: if self.grr_worker.client.FleetspeakEnabled(): raise ValueError("Not supported on Fleetspeak enabled clients.") except AttributeError: pass smart_arg = {str(field): value for field, value in iteritems(arg)} ...
Returns the client stats. def Run(self, arg): """Returns the client stats.""" if arg is None: arg = rdf_client_action.GetClientStatsRequest() proc = psutil.Process(os.getpid()) meminfo = proc.memory_info() boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time()) create_...
Returns the startup information. def Run(self, unused_arg, ttl=None): """Returns the startup information.""" logging.debug("Sending startup information.") boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time()) response = rdf_client.StartupInfo( boot_time=boot_time, client_in...
Converts an unicode string to a filesystem safe filename. For maximum compatibility we escape all chars which are not alphanumeric (in the unicode sense). Args: name: a unicode string that is part of a subject. Returns: A safe filename with escaped special chars. def ConvertStringToFilename(name): ...
Returns the directory/filename where the subject will be stored. Args: subject: The subject. regexes: The list of regular expressions by priority. Returns: File name and directory. def ResolveSubjectDestination(subject, regexes): """Returns the directory/filename where the subject will be stored. A...
Creates a name that identifies a database file. def MakeDestinationKey(directory, filename): """Creates a name that identifies a database file.""" return utils.SmartStr(utils.JoinPath(directory, filename)).lstrip("/")
Compute size (in bytes) and number of files of a file-based data store. def DatabaseDirectorySize(root_path, extension): """Compute size (in bytes) and number of files of a file-based data store.""" directories = collections.deque([root_path]) total_size = 0 total_files = 0 while directories: directory =...
Generator that yields active filestore children in priority order. def GetChildrenByPriority(self, allow_external=True): """Generator that yields active filestore children in priority order.""" for child in sorted(self.OpenChildren(), key=lambda x: x.PRIORITY): if not allow_external and child.EXTERNAL: ...
Checks a list of hashes for presence in the store. Sub stores need to pass back the original HashDigest objects since they carry state about the original file source. Only unique hashes are checked, if there is duplication in the hashes input it is the caller's responsibility to maintain any necessary...
Create a new file in the file store. We delegate the actual file addition to our contained implementations. Implementations can either implement the AddFile() method, returning a file like object which will be written on, or directly support the AddBlobToStore() method which can copy the VFSBlobImage e...
Search the index for matches starting with target_prefix. Args: index_urn: The index to use. Should be a urn that points to the sha256 namespace. target_prefix: The prefix to match against the index. limit: Either a tuple of (start, limit) or a maximum number of results to re...
Check hashes against the filestore. Blobs use the hash in the schema: aff4:/files/hash/generic/sha256/[sha256hash] Args: hashes: A list of Hash objects to check. Yields: Tuples of (RDFURN, hash object) that exist in the store. def CheckHashes(self, hashes): """Check hashes against th...
Look for the required hashes in the file. def _HashFile(self, fd): """Look for the required hashes in the file.""" hashes = data_store_utils.GetFileHashEntry(fd) if hashes: found_all = True for fingerprint_type, hash_types in iteritems(self.HASH_TYPES): for hash_type in hash_types: ...
Adds a file to the hash file store. We take a file in the client space: aff4:/C.123123123/fs/os/usr/local/blah Hash it, update the hash in the original file if its different to the one calculated on the client, and copy the original AFF4 object to aff4:/files/hash/generic/sha256/123123123 (ca...
Yields all the hashes in the file store. Args: age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in microseconds since Jan 1st, 1970. If just a microseconds value is given it's treat...
Yields client_files for the specified file store hash. Args: hash_obj: RDFURN that we want to get hits for. token: Security token. age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, en...
Yields (hash, client_files) pairs for all the specified hashes. Args: hashes: List of RDFURN's. token: Security token. age: AFF4 age specification. Only get hits corresponding to the given age spec. Should be aff4.NEWEST_TIME or a time range given as a tuple (start, end) in micros...
Checks a list of hashes for presence in the store. Only unique sha1 hashes are checked, if there is duplication in the hashes input it is the caller's responsibility to maintain any necessary mappings. Args: hashes: A list of Hash objects to check. unused_external: Ignored. Yields: ...
Adds a new file from the NSRL hash database. We create a new subject in: aff4:/files/nsrl/<sha1> with all the other arguments as attributes. Args: sha1: SHA1 digest as a hex encoded string. md5: MD5 digest as a hex encoded string. crc: File CRC as an integer. file_name: Filen...
Create FileStore and HashFileStore namespaces. def Run(self): """Create FileStore and HashFileStore namespaces.""" if not data_store.AFF4Enabled(): return try: filestore = aff4.FACTORY.Create( FileStore.PATH, FileStore, mode="rw", token=aff4.FACTORY.root_token) filestore.Close(...
Writes new artifact to the database. def WriteArtifact(self, artifact, cursor=None): """Writes new artifact to the database.""" name = Text(artifact.name) try: cursor.execute("INSERT INTO artifacts (name, definition) VALUES (%s, %s)", [name, artifact.SerializeToString()]) ex...
Looks up an artifact with given name from the database. def ReadArtifact(self, name, cursor=None): """Looks up an artifact with given name from the database.""" cursor.execute("SELECT definition FROM artifacts WHERE name = %s", [name]) row = cursor.fetchone() if row is None: raise db.UnknownArti...
Lists all artifacts that are stored in the database. def ReadAllArtifacts(self, cursor=None): """Lists all artifacts that are stored in the database.""" cursor.execute("SELECT definition FROM artifacts") return [_RowToArtifact(row) for row in cursor.fetchall()]
Deletes an artifact with given name from the database. def DeleteArtifact(self, name, cursor=None): """Deletes an artifact with given name from the database.""" cursor.execute("DELETE FROM artifacts WHERE name = %s", [name]) if cursor.rowcount == 0: raise db.UnknownArtifactError(name)
Begins an enrollment flow for this client. Args: message: The Certificate sent by the client. Note that this message is not authenticated. def ProcessMessage(self, message): """Begins an enrollment flow for this client. Args: message: The Certificate sent by the client. Note tha...
The main run method of the client. def Run(self): """The main run method of the client.""" for thread in itervalues(self._threads): thread.start() logging.info(START_STRING) while True: dead_threads = [ tn for (tn, t) in iteritems(self._threads) if not t.isAlive() ] i...
Sends Foreman checks periodically. def _ForemanOp(self): """Sends Foreman checks periodically.""" period = config.CONFIG["Client.foreman_check_frequency"] self._threads["Worker"].SendReply( rdf_protodict.DataBlob(), session_id=rdfvalue.FlowSessionID(flow_name="Foreman"), require_fas...
Sends a block of messages through Fleetspeak. def _SendMessages(self, grr_msgs, background=False): """Sends a block of messages through Fleetspeak.""" message_list = rdf_flows.PackedMessageList() communicator.Communicator.EncodeMessageList( rdf_flows.MessageList(job=grr_msgs), message_list) fs_...
Sends messages through Fleetspeak. def _SendOp(self): """Sends messages through Fleetspeak.""" msg = self._sender_queue.get() msgs = [] background_msgs = [] if not msg.require_fastpoll: background_msgs.append(msg) else: msgs.append(msg) count = 1 size = len(msg.SerializeToS...
Receives a single message through Fleetspeak. def _ReceiveOp(self): """Receives a single message through Fleetspeak.""" try: fs_msg, received_bytes = self._fs.Recv() except (IOError, struct.error): logging.critical("Broken local Fleetspeak connection (read end).") raise received_type...
Deletes a list of artifacts from the data store. def DeleteArtifactsFromDatastore(artifact_names, reload_artifacts=True): """Deletes a list of artifacts from the data store.""" artifacts_list = sorted( REGISTRY.GetArtifacts(reload_datastore_artifacts=reload_artifacts)) to_delete = set(artifact_names) de...
Validates artifact syntax. This method can be used to validate individual artifacts as they are loaded, without needing all artifacts to be loaded first, as for Validate(). Args: rdf_artifact: RDF object artifact. Raises: ArtifactSyntaxError: If artifact syntax is invalid. def ValidateSyntax(rdf_art...
Validates artifact dependencies. This method checks whether all dependencies of the artifact are present and contain no errors. This method can be called only after all other artifacts have been loaded. Args: rdf_artifact: RDF object artifact. Raises: ArtifactDependencyError: If a dependency is mi...
Return a set of artifact dependencies. Args: rdf_artifact: RDF object artifact. recursive: If True recurse into dependencies to find their dependencies. depth: Used for limiting recursion depth. Returns: A set of strings containing the dependent artifact names. Raises: RuntimeError: If maxi...
For all the artifacts in the list returns them and their dependencies. def GetArtifactsDependenciesClosure(name_list, os_name=None): """For all the artifacts in the list returns them and their dependencies.""" artifacts = set(REGISTRY.GetArtifacts(os_name=os_name, name_list=name_list)) dependencies = set() f...
Return a set of knowledgebase path dependencies. Args: rdf_artifact: RDF artifact object. Returns: A set of strings for the required kb objects e.g. ["users.appdata", "systemroot"] def GetArtifactPathDependencies(rdf_artifact): """Return a set of knowledgebase path dependencies. Args: rdf_ar...
Return the set of knowledgebase path dependencies required by the parser. Args: rdf_artifact: RDF artifact object. Returns: A set of strings for the required kb objects e.g. ["users.appdata", "systemroot"] def GetArtifactParserDependencies(rdf_artifact): """Return the set of knowledgebase path depe...
Adds a directory path as a source. Args: dirpath: a string representing a path to the directory. Returns: True if the directory is not an already existing source. def AddDir(self, dirpath): """Adds a directory path as a source. Args: dirpath: a string representing a path to the dir...
Adds a file path as a source. Args: filepath: a string representing a path to the file. Returns: True if the file is not an already existing source. def AddFile(self, filepath): """Adds a file path as a source. Args: filepath: a string representing a path to the file. Returns:...
Adds a datastore URN as a source. Args: urn: an RDF URN value of the datastore. Returns: True if the datastore is not an already existing source. def AddDatastore(self, urn): """Adds a datastore URN as a source. Args: urn: an RDF URN value of the datastore. Returns: True...
Yields all defined source file paths. This includes file paths defined directly and those defined implicitly by defining a directory. def GetAllFiles(self): """Yields all defined source file paths. This includes file paths defined directly and those defined implicitly by defining a directory. ...
Load artifacts from the data store. def _LoadArtifactsFromDatastore(self): """Load artifacts from the data store.""" loaded_artifacts = [] # TODO(hanuszczak): Why do we have to remove anything? If some artifact # tries to shadow system artifact shouldn't we just ignore them and perhaps # issue som...
Get a list of Artifacts from yaml. def ArtifactsFromYaml(self, yaml_content): """Get a list of Artifacts from yaml.""" raw_list = yaml.ParseMany(yaml_content) # TODO(hanuszczak): I am very sceptical about that "doing the right thing" # below. What are the real use cases? # Try to do the right thi...
Load artifacts from file paths as json or yaml. def _LoadArtifactsFromFiles(self, file_paths, overwrite_if_exists=True): """Load artifacts from file paths as json or yaml.""" loaded_files = [] loaded_artifacts = [] for file_path in file_paths: try: with io.open(file_path, mode="r", encodi...
Registers a new artifact. def RegisterArtifact(self, artifact_rdfvalue, source="datastore", overwrite_if_exists=False, overwrite_system_artifacts=False): """Registers a new artifact.""" artifact_name = artifact_rdfvalue...
Load artifacts from all sources. def _ReloadArtifacts(self): """Load artifacts from all sources.""" self._artifacts = {} self._LoadArtifactsFromFiles(self._sources.GetAllFiles()) self.ReloadDatastoreArtifacts()
Remove artifacts that came from the datastore. def _UnregisterDatastoreArtifacts(self): """Remove artifacts that came from the datastore.""" to_remove = [] for name, artifact in iteritems(self._artifacts): if artifact.loaded_from.startswith("datastore"): to_remove.append(name) for key in ...
Retrieve artifact classes with optional filtering. All filters must match for the artifact to be returned. Args: os_name: string to match against supported_os name_list: list of strings to match against artifact names source_type: rdf_artifacts.ArtifactSource.SourceType to match against ...
Get artifact by name. Args: name: artifact name string. Returns: artifact object. Raises: ArtifactNotRegisteredError: if artifact doesn't exist in the registy. def GetArtifact(self, name): """Get artifact by name. Args: name: artifact name string. Returns: arti...
Return a set of artifact names needed to fulfill dependencies. Search the path dependency tree for all artifacts that can fulfill dependencies of artifact_name_list. If multiple artifacts provide a dependency, they are all included. Args: os_name: operating system string artifact_name_lis...
Dump a list of artifacts into a yaml string. def DumpArtifactsToYaml(self, sort_by_os=True): """Dump a list of artifacts into a yaml string.""" artifact_list = self.GetArtifacts() if sort_by_os: # Sort so its easier to split these if necessary. yaml_list = [] done_set = set() for os...
Returns whether the provided GRR id is a Fleetspeak client. def IsFleetspeakEnabledClient(grr_id, token=None): """Returns whether the provided GRR id is a Fleetspeak client.""" if grr_id is None: return False if data_store.RelationalDBEnabled(): md = data_store.REL_DB.ReadClientMetadata(grr_id) if n...
Sends the given GrrMessage through FS. def SendGrrMessageThroughFleetspeak(grr_id, msg): """Sends the given GrrMessage through FS.""" fs_msg = fs_common_pb2.Message( message_type="GrrMessage", destination=fs_common_pb2.Address( client_id=GRRIDToFleetspeakID(grr_id), service_name="GRR")) fs_...
Returns the primary GRR label to use for a fleetspeak client. def GetLabelFromFleetspeak(client_id): """Returns the primary GRR label to use for a fleetspeak client.""" res = fleetspeak_connector.CONN.outgoing.ListClients( admin_pb2.ListClientsRequest(client_ids=[GRRIDToFleetspeakID(client_id)])) if not re...
Initialize our state. def Start(self, file_size=0, maximum_pending_files=1000, use_external_stores=False): """Initialize our state.""" super(MultiGetFileLogic, self).Start() self.state.files_hashed = 0 self.state.use_external_stores = use_external_stores self.st...
The entry point for this flow mixin - Schedules new file transfer. def StartFileFetch(self, pathspec, request_data=None): """The entry point for this flow mixin - Schedules new file transfer.""" # Create an index so we can find this pathspec later. self.state.indexed_pathspecs.append(pathspec) self.sta...
Try to schedule the next pathspec if there is enough capacity. def _TryToStartNextPathspec(self): """Try to schedule the next pathspec if there is enough capacity.""" # Nothing to do here. if self.state.maximum_pending_files <= len(self.state.pending_files): return if self.state.maximum_pending...
Removes a pathspec from the list of pathspecs. def _RemoveCompletedPathspec(self, index): """Removes a pathspec from the list of pathspecs.""" pathspec = self.state.indexed_pathspecs[index] request_data = self.state.request_data_list[index] self.state.indexed_pathspecs[index] = None self.state.req...
Remove pathspec for this index and call the ReceiveFetchedFile method. def _ReceiveFetchedFile(self, tracker): """Remove pathspec for this index and call the ReceiveFetchedFile method.""" index = tracker["index"] _, request_data = self._RemoveCompletedPathspec(index) # Report the request_data for thi...
Remove pathspec for this index and call the FileFetchFailed method. def _FileFetchFailed(self, index, request_name): """Remove pathspec for this index and call the FileFetchFailed method.""" pathspec, request_data = self._RemoveCompletedPathspec(index) # Report the request_data for this flow's caller. ...
Stores stat entry in the flow's state. def StoreStat(self, responses): """Stores stat entry in the flow's state.""" index = responses.request_data["index"] if not responses.success: self.Log("Failed to stat file: %s", responses.status) # Report failure. self._FileFetchFailed(index, respon...
Add hash digest to tracker and check with filestore. def ReceiveFileHash(self, responses): """Add hash digest to tracker and check with filestore.""" index = responses.request_data["index"] if not responses.success: self.Log("Failed to hash file: %s", responses.status) self.state.pending_hashes...
Check all queued up hashes for existence in file store (legacy). Hashes which do not exist in the file store will be downloaded. This function flushes the entire queue (self.state.pending_hashes) in order to minimize the round trips to the file store. If a file was found in the file store it is copied...