repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibLinkerFlags
def getThirdPartyLibLinkerFlags(self, libs): """ Retrieves the linker flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] includeLibs = True if (libs[0] == '--flagsonly'): includeLibs = False libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getLinkerFlags(self.getEngineRoot(), fmt, includeLibs)
python
def getThirdPartyLibLinkerFlags(self, libs): """ Retrieves the linker flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] includeLibs = True if (libs[0] == '--flagsonly'): includeLibs = False libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getLinkerFlags(self.getEngineRoot(), fmt, includeLibs)
[ "def", "getThirdPartyLibLinkerFlags", "(", "self", ",", "libs", ")", ":", "fmt", "=", "PrintingFormat", ".", "singleLine", "(", ")", "if", "libs", "[", "0", "]", "==", "'--multiline'", ":", "fmt", "=", "PrintingFormat", ".", "multiLine", "(", ")", "libs", "=", "libs", "[", "1", ":", "]", "includeLibs", "=", "True", "if", "(", "libs", "[", "0", "]", "==", "'--flagsonly'", ")", ":", "includeLibs", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "return", "details", ".", "getLinkerFlags", "(", "self", ".", "getEngineRoot", "(", ")", ",", "fmt", ",", "includeLibs", ")" ]
Retrieves the linker flags for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "linker", "flags", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L206-L226
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibCmakeFlags
def getThirdPartyLibCmakeFlags(self, libs): """ Retrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) CMakeCustomFlags.processLibraryDetails(details) return details.getCMakeFlags(self.getEngineRoot(), fmt)
python
def getThirdPartyLibCmakeFlags(self, libs): """ Retrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries """ fmt = PrintingFormat.singleLine() if libs[0] == '--multiline': fmt = PrintingFormat.multiLine() libs = libs[1:] platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) CMakeCustomFlags.processLibraryDetails(details) return details.getCMakeFlags(self.getEngineRoot(), fmt)
[ "def", "getThirdPartyLibCmakeFlags", "(", "self", ",", "libs", ")", ":", "fmt", "=", "PrintingFormat", ".", "singleLine", "(", ")", "if", "libs", "[", "0", "]", "==", "'--multiline'", ":", "fmt", "=", "PrintingFormat", ".", "multiLine", "(", ")", "libs", "=", "libs", "[", "1", ":", "]", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "CMakeCustomFlags", ".", "processLibraryDetails", "(", "details", ")", "return", "details", ".", "getCMakeFlags", "(", "self", ".", "getEngineRoot", "(", ")", ",", "fmt", ")" ]
Retrieves the CMake invocation flags for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "CMake", "invocation", "flags", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L228-L244
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibIncludeDirs
def getThirdPartyLibIncludeDirs(self, libs): """ Retrieves the list of include directories for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getIncludeDirectories(self.getEngineRoot(), delimiter='\n')
python
def getThirdPartyLibIncludeDirs(self, libs): """ Retrieves the list of include directories for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getIncludeDirectories(self.getEngineRoot(), delimiter='\n')
[ "def", "getThirdPartyLibIncludeDirs", "(", "self", ",", "libs", ")", ":", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "return", "details", ".", "getIncludeDirectories", "(", "self", ".", "getEngineRoot", "(", ")", ",", "delimiter", "=", "'\\n'", ")" ]
Retrieves the list of include directories for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "list", "of", "include", "directories", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L246-L256
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibFiles
def getThirdPartyLibFiles(self, libs): """ Retrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getLibraryFiles(self.getEngineRoot(), delimiter='\n')
python
def getThirdPartyLibFiles(self, libs): """ Retrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getLibraryFiles(self.getEngineRoot(), delimiter='\n')
[ "def", "getThirdPartyLibFiles", "(", "self", ",", "libs", ")", ":", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "return", "details", ".", "getLibraryFiles", "(", "self", ".", "getEngineRoot", "(", ")", ",", "delimiter", "=", "'\\n'", ")" ]
Retrieves the list of library files for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "list", "of", "library", "files", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L258-L268
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.getThirdPartyLibDefinitions
def getThirdPartyLibDefinitions(self, libs): """ Retrieves the list of preprocessor definitions for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getPreprocessorDefinitions(self.getEngineRoot(), delimiter='\n')
python
def getThirdPartyLibDefinitions(self, libs): """ Retrieves the list of preprocessor definitions for building against the Unreal-bundled versions of the specified third-party libraries """ platformDefaults = True if libs[0] == '--nodefaults': platformDefaults = False libs = libs[1:] details = self.getThirdpartyLibs(libs, includePlatformDefaults=platformDefaults) return details.getPreprocessorDefinitions(self.getEngineRoot(), delimiter='\n')
[ "def", "getThirdPartyLibDefinitions", "(", "self", ",", "libs", ")", ":", "platformDefaults", "=", "True", "if", "libs", "[", "0", "]", "==", "'--nodefaults'", ":", "platformDefaults", "=", "False", "libs", "=", "libs", "[", "1", ":", "]", "details", "=", "self", ".", "getThirdpartyLibs", "(", "libs", ",", "includePlatformDefaults", "=", "platformDefaults", ")", "return", "details", ".", "getPreprocessorDefinitions", "(", "self", ".", "getEngineRoot", "(", ")", ",", "delimiter", "=", "'\\n'", ")" ]
Retrieves the list of preprocessor definitions for building against the Unreal-bundled versions of the specified third-party libraries
[ "Retrieves", "the", "list", "of", "preprocessor", "definitions", "for", "building", "against", "the", "Unreal", "-", "bundled", "versions", "of", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L270-L280
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.generateProjectFiles
def generateProjectFiles(self, dir=os.getcwd(), args=[]): """ Generates IDE project files for the Unreal project in the specified directory """ # If the project is a pure Blueprint project, then we cannot generate project files if os.path.exists(os.path.join(dir, 'Source')) == False: Utility.printStderr('Pure Blueprint project, nothing to generate project files for.') return # Generate the project files genScript = self.getGenerateScript() projectFile = self.getProjectDescriptor(dir) Utility.run([genScript, '-project=' + projectFile, '-game', '-engine'] + args, cwd=os.path.dirname(genScript), raiseOnError=True)
python
def generateProjectFiles(self, dir=os.getcwd(), args=[]): """ Generates IDE project files for the Unreal project in the specified directory """ # If the project is a pure Blueprint project, then we cannot generate project files if os.path.exists(os.path.join(dir, 'Source')) == False: Utility.printStderr('Pure Blueprint project, nothing to generate project files for.') return # Generate the project files genScript = self.getGenerateScript() projectFile = self.getProjectDescriptor(dir) Utility.run([genScript, '-project=' + projectFile, '-game', '-engine'] + args, cwd=os.path.dirname(genScript), raiseOnError=True)
[ "def", "generateProjectFiles", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "args", "=", "[", "]", ")", ":", "# If the project is a pure Blueprint project, then we cannot generate project files", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'Source'", ")", ")", "==", "False", ":", "Utility", ".", "printStderr", "(", "'Pure Blueprint project, nothing to generate project files for.'", ")", "return", "# Generate the project files", "genScript", "=", "self", ".", "getGenerateScript", "(", ")", "projectFile", "=", "self", ".", "getProjectDescriptor", "(", "dir", ")", "Utility", ".", "run", "(", "[", "genScript", ",", "'-project='", "+", "projectFile", ",", "'-game'", ",", "'-engine'", "]", "+", "args", ",", "cwd", "=", "os", ".", "path", ".", "dirname", "(", "genScript", ")", ",", "raiseOnError", "=", "True", ")" ]
Generates IDE project files for the Unreal project in the specified directory
[ "Generates", "IDE", "project", "files", "for", "the", "Unreal", "project", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L282-L295
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.cleanDescriptor
def cleanDescriptor(self, dir=os.getcwd()): """ Cleans the build artifacts for the Unreal project or plugin in the specified directory """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) # Because performing a clean will also delete the engine build itself when using # a source build, we simply delete the `Binaries` and `Intermediate` directories shutil.rmtree(os.path.join(dir, 'Binaries'), ignore_errors=True) shutil.rmtree(os.path.join(dir, 'Intermediate'), ignore_errors=True) # If we are cleaning a project, also clean any plugins if self.isProject(descriptor): projectPlugins = glob.glob(os.path.join(dir, 'Plugins', '*')) for pluginDir in projectPlugins: self.cleanDescriptor(pluginDir)
python
def cleanDescriptor(self, dir=os.getcwd()): """ Cleans the build artifacts for the Unreal project or plugin in the specified directory """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) # Because performing a clean will also delete the engine build itself when using # a source build, we simply delete the `Binaries` and `Intermediate` directories shutil.rmtree(os.path.join(dir, 'Binaries'), ignore_errors=True) shutil.rmtree(os.path.join(dir, 'Intermediate'), ignore_errors=True) # If we are cleaning a project, also clean any plugins if self.isProject(descriptor): projectPlugins = glob.glob(os.path.join(dir, 'Plugins', '*')) for pluginDir in projectPlugins: self.cleanDescriptor(pluginDir)
[ "def", "cleanDescriptor", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ")", ":", "# Verify that an Unreal project or plugin exists in the specified directory", "descriptor", "=", "self", ".", "getDescriptor", "(", "dir", ")", "# Because performing a clean will also delete the engine build itself when using", "# a source build, we simply delete the `Binaries` and `Intermediate` directories", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'Binaries'", ")", ",", "ignore_errors", "=", "True", ")", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'Intermediate'", ")", ",", "ignore_errors", "=", "True", ")", "# If we are cleaning a project, also clean any plugins", "if", "self", ".", "isProject", "(", "descriptor", ")", ":", "projectPlugins", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'Plugins'", ",", "'*'", ")", ")", "for", "pluginDir", "in", "projectPlugins", ":", "self", ".", "cleanDescriptor", "(", "pluginDir", ")" ]
Cleans the build artifacts for the Unreal project or plugin in the specified directory
[ "Cleans", "the", "build", "artifacts", "for", "the", "Unreal", "project", "or", "plugin", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L297-L314
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.buildDescriptor
def buildDescriptor(self, dir=os.getcwd(), configuration='Development', args=[], suppressOutput=False): """ Builds the editor modules for the Unreal project or plugin in the specified directory, using the specified build configuration """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) descriptorType = 'project' if self.isProject(descriptor) else 'plugin' # If the project or plugin is Blueprint-only, there is no C++ code to build if os.path.exists(os.path.join(dir, 'Source')) == False: Utility.printStderr('Pure Blueprint {}, nothing to build.'.format(descriptorType)) return # Verify that the specified build configuration is valid if configuration not in self.validBuildConfigurations(): raise UnrealManagerException('invalid build configuration "' + configuration + '"') # Generate the arguments to pass to UBT target = self.getDescriptorName(descriptor) + 'Editor' if self.isProject(descriptor) else 'UE4Editor' baseArgs = ['-{}='.format(descriptorType) + descriptor] # Perform the build self._runUnrealBuildTool(target, self.getPlatformIdentifier(), configuration, baseArgs + args, capture=suppressOutput)
python
def buildDescriptor(self, dir=os.getcwd(), configuration='Development', args=[], suppressOutput=False): """ Builds the editor modules for the Unreal project or plugin in the specified directory, using the specified build configuration """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) descriptorType = 'project' if self.isProject(descriptor) else 'plugin' # If the project or plugin is Blueprint-only, there is no C++ code to build if os.path.exists(os.path.join(dir, 'Source')) == False: Utility.printStderr('Pure Blueprint {}, nothing to build.'.format(descriptorType)) return # Verify that the specified build configuration is valid if configuration not in self.validBuildConfigurations(): raise UnrealManagerException('invalid build configuration "' + configuration + '"') # Generate the arguments to pass to UBT target = self.getDescriptorName(descriptor) + 'Editor' if self.isProject(descriptor) else 'UE4Editor' baseArgs = ['-{}='.format(descriptorType) + descriptor] # Perform the build self._runUnrealBuildTool(target, self.getPlatformIdentifier(), configuration, baseArgs + args, capture=suppressOutput)
[ "def", "buildDescriptor", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "configuration", "=", "'Development'", ",", "args", "=", "[", "]", ",", "suppressOutput", "=", "False", ")", ":", "# Verify that an Unreal project or plugin exists in the specified directory", "descriptor", "=", "self", ".", "getDescriptor", "(", "dir", ")", "descriptorType", "=", "'project'", "if", "self", ".", "isProject", "(", "descriptor", ")", "else", "'plugin'", "# If the project or plugin is Blueprint-only, there is no C++ code to build", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "dir", ",", "'Source'", ")", ")", "==", "False", ":", "Utility", ".", "printStderr", "(", "'Pure Blueprint {}, nothing to build.'", ".", "format", "(", "descriptorType", ")", ")", "return", "# Verify that the specified build configuration is valid", "if", "configuration", "not", "in", "self", ".", "validBuildConfigurations", "(", ")", ":", "raise", "UnrealManagerException", "(", "'invalid build configuration \"'", "+", "configuration", "+", "'\"'", ")", "# Generate the arguments to pass to UBT", "target", "=", "self", ".", "getDescriptorName", "(", "descriptor", ")", "+", "'Editor'", "if", "self", ".", "isProject", "(", "descriptor", ")", "else", "'UE4Editor'", "baseArgs", "=", "[", "'-{}='", ".", "format", "(", "descriptorType", ")", "+", "descriptor", "]", "# Perform the build", "self", ".", "_runUnrealBuildTool", "(", "target", ",", "self", ".", "getPlatformIdentifier", "(", ")", ",", "configuration", ",", "baseArgs", "+", "args", ",", "capture", "=", "suppressOutput", ")" ]
Builds the editor modules for the Unreal project or plugin in the specified directory, using the specified build configuration
[ "Builds", "the", "editor", "modules", "for", "the", "Unreal", "project", "or", "plugin", "in", "the", "specified", "directory", "using", "the", "specified", "build", "configuration" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L316-L339
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.runUAT
def runUAT(self, args): """ Runs the Unreal Automation Tool with the supplied arguments """ Utility.run([self.getRunUATScript()] + args, cwd=self.getEngineRoot(), raiseOnError=True)
python
def runUAT(self, args): """ Runs the Unreal Automation Tool with the supplied arguments """ Utility.run([self.getRunUATScript()] + args, cwd=self.getEngineRoot(), raiseOnError=True)
[ "def", "runUAT", "(", "self", ",", "args", ")", ":", "Utility", ".", "run", "(", "[", "self", ".", "getRunUATScript", "(", ")", "]", "+", "args", ",", "cwd", "=", "self", ".", "getEngineRoot", "(", ")", ",", "raiseOnError", "=", "True", ")" ]
Runs the Unreal Automation Tool with the supplied arguments
[ "Runs", "the", "Unreal", "Automation", "Tool", "with", "the", "supplied", "arguments" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L349-L353
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.packageProject
def packageProject(self, dir=os.getcwd(), configuration='Shipping', extraArgs=[]): """ Packages a build of the Unreal project in the specified directory, using common packaging options """ # Verify that the specified build configuration is valid if configuration not in self.validBuildConfigurations(): raise UnrealManagerException('invalid build configuration "' + configuration + '"') # Strip out the `-NoCompileEditor` flag if the user has specified it, since the Development version # of the Editor modules for the project are needed in order to run the commandlet that cooks content extraArgs = Utility.stripArgs(extraArgs, ['-nocompileeditor']) # Prevent the user from specifying multiple `-platform=` or `-targetplatform=` arguments, # and use the current host platform if no platform argument was explicitly specified platformArgs = Utility.findArgs(extraArgs, ['-platform=', '-targetplatform=']) platform = Utility.getArgValue(platformArgs[0]) if len(platformArgs) > 0 else self.getPlatformIdentifier() extraArgs = Utility.stripArgs(extraArgs, platformArgs) + ['-platform={}'.format(platform)] # If we are packaging a Shipping build, do not include debug symbols if configuration == 'Shipping': extraArgs.append('-nodebuginfo') # Do not create a .pak file when packaging for HTML5 pakArg = '-package' if platform.upper() == 'HTML5' else '-pak' # Invoke UAT to package the build distDir = os.path.join(os.path.abspath(dir), 'dist') self.runUAT([ 'BuildCookRun', '-utf8output', '-clientconfig=' + configuration, '-serverconfig=' + configuration, '-project=' + self.getProjectDescriptor(dir), '-noP4', '-cook', '-allmaps', '-build', '-stage', '-prereqs', pakArg, '-archive', '-archivedirectory=' + distDir ] + extraArgs)
python
def packageProject(self, dir=os.getcwd(), configuration='Shipping', extraArgs=[]): """ Packages a build of the Unreal project in the specified directory, using common packaging options """ # Verify that the specified build configuration is valid if configuration not in self.validBuildConfigurations(): raise UnrealManagerException('invalid build configuration "' + configuration + '"') # Strip out the `-NoCompileEditor` flag if the user has specified it, since the Development version # of the Editor modules for the project are needed in order to run the commandlet that cooks content extraArgs = Utility.stripArgs(extraArgs, ['-nocompileeditor']) # Prevent the user from specifying multiple `-platform=` or `-targetplatform=` arguments, # and use the current host platform if no platform argument was explicitly specified platformArgs = Utility.findArgs(extraArgs, ['-platform=', '-targetplatform=']) platform = Utility.getArgValue(platformArgs[0]) if len(platformArgs) > 0 else self.getPlatformIdentifier() extraArgs = Utility.stripArgs(extraArgs, platformArgs) + ['-platform={}'.format(platform)] # If we are packaging a Shipping build, do not include debug symbols if configuration == 'Shipping': extraArgs.append('-nodebuginfo') # Do not create a .pak file when packaging for HTML5 pakArg = '-package' if platform.upper() == 'HTML5' else '-pak' # Invoke UAT to package the build distDir = os.path.join(os.path.abspath(dir), 'dist') self.runUAT([ 'BuildCookRun', '-utf8output', '-clientconfig=' + configuration, '-serverconfig=' + configuration, '-project=' + self.getProjectDescriptor(dir), '-noP4', '-cook', '-allmaps', '-build', '-stage', '-prereqs', pakArg, '-archive', '-archivedirectory=' + distDir ] + extraArgs)
[ "def", "packageProject", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "configuration", "=", "'Shipping'", ",", "extraArgs", "=", "[", "]", ")", ":", "# Verify that the specified build configuration is valid", "if", "configuration", "not", "in", "self", ".", "validBuildConfigurations", "(", ")", ":", "raise", "UnrealManagerException", "(", "'invalid build configuration \"'", "+", "configuration", "+", "'\"'", ")", "# Strip out the `-NoCompileEditor` flag if the user has specified it, since the Development version", "# of the Editor modules for the project are needed in order to run the commandlet that cooks content", "extraArgs", "=", "Utility", ".", "stripArgs", "(", "extraArgs", ",", "[", "'-nocompileeditor'", "]", ")", "# Prevent the user from specifying multiple `-platform=` or `-targetplatform=` arguments,", "# and use the current host platform if no platform argument was explicitly specified", "platformArgs", "=", "Utility", ".", "findArgs", "(", "extraArgs", ",", "[", "'-platform='", ",", "'-targetplatform='", "]", ")", "platform", "=", "Utility", ".", "getArgValue", "(", "platformArgs", "[", "0", "]", ")", "if", "len", "(", "platformArgs", ")", ">", "0", "else", "self", ".", "getPlatformIdentifier", "(", ")", "extraArgs", "=", "Utility", ".", "stripArgs", "(", "extraArgs", ",", "platformArgs", ")", "+", "[", "'-platform={}'", ".", "format", "(", "platform", ")", "]", "# If we are packaging a Shipping build, do not include debug symbols", "if", "configuration", "==", "'Shipping'", ":", "extraArgs", ".", "append", "(", "'-nodebuginfo'", ")", "# Do not create a .pak file when packaging for HTML5", "pakArg", "=", "'-package'", "if", "platform", ".", "upper", "(", ")", "==", "'HTML5'", "else", "'-pak'", "# Invoke UAT to package the build", "distDir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "dir", ")", ",", "'dist'", ")", "self", ".", "runUAT", "(", "[", "'BuildCookRun'", ",", "'-utf8output'", ",", "'-clientconfig='", "+", "configuration", ",", "'-serverconfig='", "+", "configuration", ",", "'-project='", "+", "self", ".", "getProjectDescriptor", "(", "dir", ")", ",", "'-noP4'", ",", "'-cook'", ",", "'-allmaps'", ",", "'-build'", ",", "'-stage'", ",", "'-prereqs'", ",", "pakArg", ",", "'-archive'", ",", "'-archivedirectory='", "+", "distDir", "]", "+", "extraArgs", ")" ]
Packages a build of the Unreal project in the specified directory, using common packaging options
[ "Packages", "a", "build", "of", "the", "Unreal", "project", "in", "the", "specified", "directory", "using", "common", "packaging", "options" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L355-L398
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.packagePlugin
def packagePlugin(self, dir=os.getcwd(), extraArgs=[]): """ Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module """ # Invoke UAT to package the build distDir = os.path.join(os.path.abspath(dir), 'dist') self.runUAT([ 'BuildPlugin', '-Plugin=' + self.getPluginDescriptor(dir), '-Package=' + distDir ] + extraArgs)
python
def packagePlugin(self, dir=os.getcwd(), extraArgs=[]): """ Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module """ # Invoke UAT to package the build distDir = os.path.join(os.path.abspath(dir), 'dist') self.runUAT([ 'BuildPlugin', '-Plugin=' + self.getPluginDescriptor(dir), '-Package=' + distDir ] + extraArgs)
[ "def", "packagePlugin", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "extraArgs", "=", "[", "]", ")", ":", "# Invoke UAT to package the build", "distDir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "abspath", "(", "dir", ")", ",", "'dist'", ")", "self", ".", "runUAT", "(", "[", "'BuildPlugin'", ",", "'-Plugin='", "+", "self", ".", "getPluginDescriptor", "(", "dir", ")", ",", "'-Package='", "+", "distDir", "]", "+", "extraArgs", ")" ]
Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module
[ "Packages", "a", "build", "of", "the", "Unreal", "plugin", "in", "the", "specified", "directory", "suitable", "for", "use", "as", "a", "prebuilt", "Engine", "module" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L400-L411
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.packageDescriptor
def packageDescriptor(self, dir=os.getcwd(), args=[]): """ Packages a build of the Unreal project or plugin in the specified directory """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) # Perform the packaging step if self.isProject(descriptor): self.packageProject(dir, args[0] if len(args) > 0 else 'Shipping', args[1:]) else: self.packagePlugin(dir, args)
python
def packageDescriptor(self, dir=os.getcwd(), args=[]): """ Packages a build of the Unreal project or plugin in the specified directory """ # Verify that an Unreal project or plugin exists in the specified directory descriptor = self.getDescriptor(dir) # Perform the packaging step if self.isProject(descriptor): self.packageProject(dir, args[0] if len(args) > 0 else 'Shipping', args[1:]) else: self.packagePlugin(dir, args)
[ "def", "packageDescriptor", "(", "self", ",", "dir", "=", "os", ".", "getcwd", "(", ")", ",", "args", "=", "[", "]", ")", ":", "# Verify that an Unreal project or plugin exists in the specified directory", "descriptor", "=", "self", ".", "getDescriptor", "(", "dir", ")", "# Perform the packaging step", "if", "self", ".", "isProject", "(", "descriptor", ")", ":", "self", ".", "packageProject", "(", "dir", ",", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "0", "else", "'Shipping'", ",", "args", "[", "1", ":", "]", ")", "else", ":", "self", ".", "packagePlugin", "(", "dir", ",", "args", ")" ]
Packages a build of the Unreal project or plugin in the specified directory
[ "Packages", "a", "build", "of", "the", "Unreal", "project", "or", "plugin", "in", "the", "specified", "directory" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L413-L425
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase.runAutomationCommands
def runAutomationCommands(self, projectFile, commands, capture=False): ''' Invokes the Automation Test commandlet for the specified project with the supplied automation test commands ''' # IMPORTANT IMPLEMENTATION NOTE: # We need to format the command as a string and execute it using a shell in order to # ensure the "-ExecCmds" argument will be parsed correctly under Windows. This is because # the WinMain() function uses GetCommandLineW() to retrieve the raw command-line string, # rather than using an argv-style structure. The string is then passed to FParse::Value(), # which checks for the presence of a quote character after the equals sign to determine if # whitespace should be stripped or preserved. Without the quote character, the spaces in the # argument payload will be stripped out, corrupting our list of automation commands and # preventing them from executing correctly. command = '{} {}'.format(Utility.escapePathForShell(self.getEditorBinary(True)), Utility.escapePathForShell(projectFile)) command += ' -game -buildmachine -stdout -fullstdoutlogoutput -forcelogflush -unattended -nopause -nullrhi -nosplash' command += ' -ExecCmds="automation {};quit"'.format(';'.join(commands)) if capture == True: return Utility.capture(command, shell=True) else: Utility.run(command, shell=True)
python
def runAutomationCommands(self, projectFile, commands, capture=False): ''' Invokes the Automation Test commandlet for the specified project with the supplied automation test commands ''' # IMPORTANT IMPLEMENTATION NOTE: # We need to format the command as a string and execute it using a shell in order to # ensure the "-ExecCmds" argument will be parsed correctly under Windows. This is because # the WinMain() function uses GetCommandLineW() to retrieve the raw command-line string, # rather than using an argv-style structure. The string is then passed to FParse::Value(), # which checks for the presence of a quote character after the equals sign to determine if # whitespace should be stripped or preserved. Without the quote character, the spaces in the # argument payload will be stripped out, corrupting our list of automation commands and # preventing them from executing correctly. command = '{} {}'.format(Utility.escapePathForShell(self.getEditorBinary(True)), Utility.escapePathForShell(projectFile)) command += ' -game -buildmachine -stdout -fullstdoutlogoutput -forcelogflush -unattended -nopause -nullrhi -nosplash' command += ' -ExecCmds="automation {};quit"'.format(';'.join(commands)) if capture == True: return Utility.capture(command, shell=True) else: Utility.run(command, shell=True)
[ "def", "runAutomationCommands", "(", "self", ",", "projectFile", ",", "commands", ",", "capture", "=", "False", ")", ":", "# IMPORTANT IMPLEMENTATION NOTE:", "# We need to format the command as a string and execute it using a shell in order to", "# ensure the \"-ExecCmds\" argument will be parsed correctly under Windows. This is because", "# the WinMain() function uses GetCommandLineW() to retrieve the raw command-line string,", "# rather than using an argv-style structure. The string is then passed to FParse::Value(),", "# which checks for the presence of a quote character after the equals sign to determine if", "# whitespace should be stripped or preserved. Without the quote character, the spaces in the", "# argument payload will be stripped out, corrupting our list of automation commands and", "# preventing them from executing correctly.", "command", "=", "'{} {}'", ".", "format", "(", "Utility", ".", "escapePathForShell", "(", "self", ".", "getEditorBinary", "(", "True", ")", ")", ",", "Utility", ".", "escapePathForShell", "(", "projectFile", ")", ")", "command", "+=", "' -game -buildmachine -stdout -fullstdoutlogoutput -forcelogflush -unattended -nopause -nullrhi -nosplash'", "command", "+=", "' -ExecCmds=\"automation {};quit\"'", ".", "format", "(", "';'", ".", "join", "(", "commands", ")", ")", "if", "capture", "==", "True", ":", "return", "Utility", ".", "capture", "(", "command", ",", "shell", "=", "True", ")", "else", ":", "Utility", ".", "run", "(", "command", ",", "shell", "=", "True", ")" ]
Invokes the Automation Test commandlet for the specified project with the supplied automation test commands
[ "Invokes", "the", "Automation", "Test", "commandlet", "for", "the", "specified", "project", "with", "the", "supplied", "automation", "test", "commands" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L427-L449
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase._getEngineVersionDetails
def _getEngineVersionDetails(self): """ Parses the JSON version details for the latest installed version of UE4 """ versionFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'Build.version') return json.loads(Utility.readFile(versionFile))
python
def _getEngineVersionDetails(self): """ Parses the JSON version details for the latest installed version of UE4 """ versionFile = os.path.join(self.getEngineRoot(), 'Engine', 'Build', 'Build.version') return json.loads(Utility.readFile(versionFile))
[ "def", "_getEngineVersionDetails", "(", "self", ")", ":", "versionFile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "getEngineRoot", "(", ")", ",", "'Engine'", ",", "'Build'", ",", "'Build.version'", ")", "return", "json", ".", "loads", "(", "Utility", ".", "readFile", "(", "versionFile", ")", ")" ]
Parses the JSON version details for the latest installed version of UE4
[ "Parses", "the", "JSON", "version", "details", "for", "the", "latest", "installed", "version", "of", "UE4" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L555-L560
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase._getEngineVersionHash
def _getEngineVersionHash(self): """ Computes the SHA-256 hash of the JSON version details for the latest installed version of UE4 """ versionDetails = self._getEngineVersionDetails() hash = hashlib.sha256() hash.update(json.dumps(versionDetails, sort_keys=True, indent=0).encode('utf-8')) return hash.hexdigest()
python
def _getEngineVersionHash(self): """ Computes the SHA-256 hash of the JSON version details for the latest installed version of UE4 """ versionDetails = self._getEngineVersionDetails() hash = hashlib.sha256() hash.update(json.dumps(versionDetails, sort_keys=True, indent=0).encode('utf-8')) return hash.hexdigest()
[ "def", "_getEngineVersionHash", "(", "self", ")", ":", "versionDetails", "=", "self", ".", "_getEngineVersionDetails", "(", ")", "hash", "=", "hashlib", ".", "sha256", "(", ")", "hash", ".", "update", "(", "json", ".", "dumps", "(", "versionDetails", ",", "sort_keys", "=", "True", ",", "indent", "=", "0", ")", ".", "encode", "(", "'utf-8'", ")", ")", "return", "hash", ".", "hexdigest", "(", ")" ]
Computes the SHA-256 hash of the JSON version details for the latest installed version of UE4
[ "Computes", "the", "SHA", "-", "256", "hash", "of", "the", "JSON", "version", "details", "for", "the", "latest", "installed", "version", "of", "UE4" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L562-L569
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase._runUnrealBuildTool
def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False): """ Invokes UnrealBuildTool with the specified parameters """ platform = self._transformBuildToolPlatform(platform) arguments = [self.getBuildScript(), target, platform, configuration] + args if capture == True: return Utility.capture(arguments, cwd=self.getEngineRoot(), raiseOnError=True) else: Utility.run(arguments, cwd=self.getEngineRoot(), raiseOnError=True)
python
def _runUnrealBuildTool(self, target, platform, configuration, args, capture=False): """ Invokes UnrealBuildTool with the specified parameters """ platform = self._transformBuildToolPlatform(platform) arguments = [self.getBuildScript(), target, platform, configuration] + args if capture == True: return Utility.capture(arguments, cwd=self.getEngineRoot(), raiseOnError=True) else: Utility.run(arguments, cwd=self.getEngineRoot(), raiseOnError=True)
[ "def", "_runUnrealBuildTool", "(", "self", ",", "target", ",", "platform", ",", "configuration", ",", "args", ",", "capture", "=", "False", ")", ":", "platform", "=", "self", ".", "_transformBuildToolPlatform", "(", "platform", ")", "arguments", "=", "[", "self", ".", "getBuildScript", "(", ")", ",", "target", ",", "platform", ",", "configuration", "]", "+", "args", "if", "capture", "==", "True", ":", "return", "Utility", ".", "capture", "(", "arguments", ",", "cwd", "=", "self", ".", "getEngineRoot", "(", ")", ",", "raiseOnError", "=", "True", ")", "else", ":", "Utility", ".", "run", "(", "arguments", ",", "cwd", "=", "self", ".", "getEngineRoot", "(", ")", ",", "raiseOnError", "=", "True", ")" ]
Invokes UnrealBuildTool with the specified parameters
[ "Invokes", "UnrealBuildTool", "with", "the", "specified", "parameters" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L607-L616
train
adamrehn/ue4cli
ue4cli/UnrealManagerBase.py
UnrealManagerBase._getUE4BuildInterrogator
def _getUE4BuildInterrogator(self): """ Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details """ ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True) interrogator = UE4BuildInterrogator(self.getEngineRoot(), self._getEngineVersionDetails(), self._getEngineVersionHash(), ubtLambda) return interrogator
python
def _getUE4BuildInterrogator(self): """ Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details """ ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True) interrogator = UE4BuildInterrogator(self.getEngineRoot(), self._getEngineVersionDetails(), self._getEngineVersionHash(), ubtLambda) return interrogator
[ "def", "_getUE4BuildInterrogator", "(", "self", ")", ":", "ubtLambda", "=", "lambda", "target", ",", "platform", ",", "config", ",", "args", ":", "self", ".", "_runUnrealBuildTool", "(", "target", ",", "platform", ",", "config", ",", "args", ",", "True", ")", "interrogator", "=", "UE4BuildInterrogator", "(", "self", ".", "getEngineRoot", "(", ")", ",", "self", ".", "_getEngineVersionDetails", "(", ")", ",", "self", ".", "_getEngineVersionHash", "(", ")", ",", "ubtLambda", ")", "return", "interrogator" ]
Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details
[ "Uses", "UE4BuildInterrogator", "to", "interrogate", "UnrealBuildTool", "about", "third", "-", "party", "library", "details" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UnrealManagerBase.py#L618-L624
train
adamrehn/ue4cli
ue4cli/JsonDataManager.py
JsonDataManager.getKey
def getKey(self, key): """ Retrieves the value for the specified dictionary key """ data = self.getDictionary() if key in data: return data[key] else: return None
python
def getKey(self, key): """ Retrieves the value for the specified dictionary key """ data = self.getDictionary() if key in data: return data[key] else: return None
[ "def", "getKey", "(", "self", ",", "key", ")", ":", "data", "=", "self", ".", "getDictionary", "(", ")", "if", "key", "in", "data", ":", "return", "data", "[", "key", "]", "else", ":", "return", "None" ]
Retrieves the value for the specified dictionary key
[ "Retrieves", "the", "value", "for", "the", "specified", "dictionary", "key" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/JsonDataManager.py#L15-L23
train
adamrehn/ue4cli
ue4cli/JsonDataManager.py
JsonDataManager.getDictionary
def getDictionary(self): """ Retrieves the entire data dictionary """ if os.path.exists(self.jsonFile): return json.loads(Utility.readFile(self.jsonFile)) else: return {}
python
def getDictionary(self): """ Retrieves the entire data dictionary """ if os.path.exists(self.jsonFile): return json.loads(Utility.readFile(self.jsonFile)) else: return {}
[ "def", "getDictionary", "(", "self", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "jsonFile", ")", ":", "return", "json", ".", "loads", "(", "Utility", ".", "readFile", "(", "self", ".", "jsonFile", ")", ")", "else", ":", "return", "{", "}" ]
Retrieves the entire data dictionary
[ "Retrieves", "the", "entire", "data", "dictionary" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/JsonDataManager.py#L25-L32
train
adamrehn/ue4cli
ue4cli/JsonDataManager.py
JsonDataManager.setKey
def setKey(self, key, value): """ Sets the value for the specified dictionary key """ data = self.getDictionary() data[key] = value self.setDictionary(data)
python
def setKey(self, key, value): """ Sets the value for the specified dictionary key """ data = self.getDictionary() data[key] = value self.setDictionary(data)
[ "def", "setKey", "(", "self", ",", "key", ",", "value", ")", ":", "data", "=", "self", ".", "getDictionary", "(", ")", "data", "[", "key", "]", "=", "value", "self", ".", "setDictionary", "(", "data", ")" ]
Sets the value for the specified dictionary key
[ "Sets", "the", "value", "for", "the", "specified", "dictionary", "key" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/JsonDataManager.py#L34-L40
train
adamrehn/ue4cli
ue4cli/JsonDataManager.py
JsonDataManager.setDictionary
def setDictionary(self, data): """ Overwrites the entire dictionary """ # Create the directory containing the JSON file if it doesn't already exist jsonDir = os.path.dirname(self.jsonFile) if os.path.exists(jsonDir) == False: os.makedirs(jsonDir) # Store the dictionary Utility.writeFile(self.jsonFile, json.dumps(data))
python
def setDictionary(self, data): """ Overwrites the entire dictionary """ # Create the directory containing the JSON file if it doesn't already exist jsonDir = os.path.dirname(self.jsonFile) if os.path.exists(jsonDir) == False: os.makedirs(jsonDir) # Store the dictionary Utility.writeFile(self.jsonFile, json.dumps(data))
[ "def", "setDictionary", "(", "self", ",", "data", ")", ":", "# Create the directory containing the JSON file if it doesn't already exist", "jsonDir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "jsonFile", ")", "if", "os", ".", "path", ".", "exists", "(", "jsonDir", ")", "==", "False", ":", "os", ".", "makedirs", "(", "jsonDir", ")", "# Store the dictionary", "Utility", ".", "writeFile", "(", "self", ".", "jsonFile", ",", "json", ".", "dumps", "(", "data", ")", ")" ]
Overwrites the entire dictionary
[ "Overwrites", "the", "entire", "dictionary" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/JsonDataManager.py#L42-L53
train
adamrehn/ue4cli
ue4cli/UE4BuildInterrogator.py
UE4BuildInterrogator.list
def list(self, platformIdentifier, configuration, libOverrides = {}): """ Returns the list of supported UE4-bundled third-party libraries """ modules = self._getThirdPartyLibs(platformIdentifier, configuration) return sorted([m['Name'] for m in modules] + [key for key in libOverrides])
python
def list(self, platformIdentifier, configuration, libOverrides = {}): """ Returns the list of supported UE4-bundled third-party libraries """ modules = self._getThirdPartyLibs(platformIdentifier, configuration) return sorted([m['Name'] for m in modules] + [key for key in libOverrides])
[ "def", "list", "(", "self", ",", "platformIdentifier", ",", "configuration", ",", "libOverrides", "=", "{", "}", ")", ":", "modules", "=", "self", ".", "_getThirdPartyLibs", "(", "platformIdentifier", ",", "configuration", ")", "return", "sorted", "(", "[", "m", "[", "'Name'", "]", "for", "m", "in", "modules", "]", "+", "[", "key", "for", "key", "in", "libOverrides", "]", ")" ]
Returns the list of supported UE4-bundled third-party libraries
[ "Returns", "the", "list", "of", "supported", "UE4", "-", "bundled", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UE4BuildInterrogator.py#L16-L21
train
adamrehn/ue4cli
ue4cli/UE4BuildInterrogator.py
UE4BuildInterrogator.interrogate
def interrogate(self, platformIdentifier, configuration, libraries, libOverrides = {}): """ Interrogates UnrealBuildTool about the build flags for the specified third-party libraries """ # Determine which libraries need their modules parsed by UBT, and which are override-only libModules = list([lib for lib in libraries if lib not in libOverrides]) # Check that we have at least one module to parse details = ThirdPartyLibraryDetails() if len(libModules) > 0: # Retrieve the list of third-party library modules from UnrealBuildTool modules = self._getThirdPartyLibs(platformIdentifier, configuration) # Filter the list of modules to include only those that were requested modules = [m for m in modules if m['Name'] in libModules] # Emit a warning if any of the requested modules are not supported names = [m['Name'] for m in modules] unsupported = ['"' + m + '"' for m in libModules if m not in names] if len(unsupported) > 0: Utility.printStderr('Warning: unsupported libraries ' + ','.join(unsupported)) # Some libraries are listed as just the filename without the leading directory (especially prevalent under Windows) for module in modules: if len(module['PublicAdditionalLibraries']) > 0 and len(module['PublicLibraryPaths']) > 0: libPath = (self._absolutePaths(module['PublicLibraryPaths']))[0] libs = list([lib.replace('\\', '/') for lib in module['PublicAdditionalLibraries']]) libs = list([os.path.join(libPath, lib) if '/' not in lib else lib for lib in libs]) module['PublicAdditionalLibraries'] = libs # Flatten the lists of paths fields = [ 'Directory', 'PublicAdditionalLibraries', 'PublicLibraryPaths', 'PublicSystemIncludePaths', 'PublicIncludePaths', 'PrivateIncludePaths', 'PublicDefinitions' ] flattened = {} for field in fields: transform = (lambda l: self._absolutePaths(l)) if field != 'Definitions' else None flattened[field] = self._flatten(field, modules, transform) # Compose the prefix directories from the module root directories, the header and library paths, and their direct parent directories libraryDirectories = flattened['PublicLibraryPaths'] headerDirectories = flattened['PublicSystemIncludePaths'] + flattened['PublicIncludePaths'] + flattened['PrivateIncludePaths'] modulePaths = flattened['Directory'] prefixDirectories = list(set(flattened['Directory'] + headerDirectories + libraryDirectories + [os.path.dirname(p) for p in headerDirectories + libraryDirectories])) # Wrap the results in a ThirdPartyLibraryDetails instance, converting any relative directory paths into absolute ones details = ThirdPartyLibraryDetails( prefixDirs = prefixDirectories, includeDirs = headerDirectories, linkDirs = libraryDirectories, definitions = flattened['PublicDefinitions'], libs = flattened['PublicAdditionalLibraries'] ) # Apply any overrides overridesToApply = list([libOverrides[lib] for lib in libraries if lib in libOverrides]) for override in overridesToApply: details.merge(override) return details
python
def interrogate(self, platformIdentifier, configuration, libraries, libOverrides = {}): """ Interrogates UnrealBuildTool about the build flags for the specified third-party libraries """ # Determine which libraries need their modules parsed by UBT, and which are override-only libModules = list([lib for lib in libraries if lib not in libOverrides]) # Check that we have at least one module to parse details = ThirdPartyLibraryDetails() if len(libModules) > 0: # Retrieve the list of third-party library modules from UnrealBuildTool modules = self._getThirdPartyLibs(platformIdentifier, configuration) # Filter the list of modules to include only those that were requested modules = [m for m in modules if m['Name'] in libModules] # Emit a warning if any of the requested modules are not supported names = [m['Name'] for m in modules] unsupported = ['"' + m + '"' for m in libModules if m not in names] if len(unsupported) > 0: Utility.printStderr('Warning: unsupported libraries ' + ','.join(unsupported)) # Some libraries are listed as just the filename without the leading directory (especially prevalent under Windows) for module in modules: if len(module['PublicAdditionalLibraries']) > 0 and len(module['PublicLibraryPaths']) > 0: libPath = (self._absolutePaths(module['PublicLibraryPaths']))[0] libs = list([lib.replace('\\', '/') for lib in module['PublicAdditionalLibraries']]) libs = list([os.path.join(libPath, lib) if '/' not in lib else lib for lib in libs]) module['PublicAdditionalLibraries'] = libs # Flatten the lists of paths fields = [ 'Directory', 'PublicAdditionalLibraries', 'PublicLibraryPaths', 'PublicSystemIncludePaths', 'PublicIncludePaths', 'PrivateIncludePaths', 'PublicDefinitions' ] flattened = {} for field in fields: transform = (lambda l: self._absolutePaths(l)) if field != 'Definitions' else None flattened[field] = self._flatten(field, modules, transform) # Compose the prefix directories from the module root directories, the header and library paths, and their direct parent directories libraryDirectories = flattened['PublicLibraryPaths'] headerDirectories = flattened['PublicSystemIncludePaths'] + flattened['PublicIncludePaths'] + flattened['PrivateIncludePaths'] modulePaths = flattened['Directory'] prefixDirectories = list(set(flattened['Directory'] + headerDirectories + libraryDirectories + [os.path.dirname(p) for p in headerDirectories + libraryDirectories])) # Wrap the results in a ThirdPartyLibraryDetails instance, converting any relative directory paths into absolute ones details = ThirdPartyLibraryDetails( prefixDirs = prefixDirectories, includeDirs = headerDirectories, linkDirs = libraryDirectories, definitions = flattened['PublicDefinitions'], libs = flattened['PublicAdditionalLibraries'] ) # Apply any overrides overridesToApply = list([libOverrides[lib] for lib in libraries if lib in libOverrides]) for override in overridesToApply: details.merge(override) return details
[ "def", "interrogate", "(", "self", ",", "platformIdentifier", ",", "configuration", ",", "libraries", ",", "libOverrides", "=", "{", "}", ")", ":", "# Determine which libraries need their modules parsed by UBT, and which are override-only", "libModules", "=", "list", "(", "[", "lib", "for", "lib", "in", "libraries", "if", "lib", "not", "in", "libOverrides", "]", ")", "# Check that we have at least one module to parse", "details", "=", "ThirdPartyLibraryDetails", "(", ")", "if", "len", "(", "libModules", ")", ">", "0", ":", "# Retrieve the list of third-party library modules from UnrealBuildTool", "modules", "=", "self", ".", "_getThirdPartyLibs", "(", "platformIdentifier", ",", "configuration", ")", "# Filter the list of modules to include only those that were requested", "modules", "=", "[", "m", "for", "m", "in", "modules", "if", "m", "[", "'Name'", "]", "in", "libModules", "]", "# Emit a warning if any of the requested modules are not supported", "names", "=", "[", "m", "[", "'Name'", "]", "for", "m", "in", "modules", "]", "unsupported", "=", "[", "'\"'", "+", "m", "+", "'\"'", "for", "m", "in", "libModules", "if", "m", "not", "in", "names", "]", "if", "len", "(", "unsupported", ")", ">", "0", ":", "Utility", ".", "printStderr", "(", "'Warning: unsupported libraries '", "+", "','", ".", "join", "(", "unsupported", ")", ")", "# Some libraries are listed as just the filename without the leading directory (especially prevalent under Windows)", "for", "module", "in", "modules", ":", "if", "len", "(", "module", "[", "'PublicAdditionalLibraries'", "]", ")", ">", "0", "and", "len", "(", "module", "[", "'PublicLibraryPaths'", "]", ")", ">", "0", ":", "libPath", "=", "(", "self", ".", "_absolutePaths", "(", "module", "[", "'PublicLibraryPaths'", "]", ")", ")", "[", "0", "]", "libs", "=", "list", "(", "[", "lib", ".", "replace", "(", "'\\\\'", ",", "'/'", ")", "for", "lib", "in", "module", "[", "'PublicAdditionalLibraries'", "]", "]", ")", "libs", "=", "list", "(", "[", "os", ".", "path", ".", "join", "(", "libPath", ",", "lib", ")", "if", "'/'", "not", "in", "lib", "else", "lib", "for", "lib", "in", "libs", "]", ")", "module", "[", "'PublicAdditionalLibraries'", "]", "=", "libs", "# Flatten the lists of paths", "fields", "=", "[", "'Directory'", ",", "'PublicAdditionalLibraries'", ",", "'PublicLibraryPaths'", ",", "'PublicSystemIncludePaths'", ",", "'PublicIncludePaths'", ",", "'PrivateIncludePaths'", ",", "'PublicDefinitions'", "]", "flattened", "=", "{", "}", "for", "field", "in", "fields", ":", "transform", "=", "(", "lambda", "l", ":", "self", ".", "_absolutePaths", "(", "l", ")", ")", "if", "field", "!=", "'Definitions'", "else", "None", "flattened", "[", "field", "]", "=", "self", ".", "_flatten", "(", "field", ",", "modules", ",", "transform", ")", "# Compose the prefix directories from the module root directories, the header and library paths, and their direct parent directories", "libraryDirectories", "=", "flattened", "[", "'PublicLibraryPaths'", "]", "headerDirectories", "=", "flattened", "[", "'PublicSystemIncludePaths'", "]", "+", "flattened", "[", "'PublicIncludePaths'", "]", "+", "flattened", "[", "'PrivateIncludePaths'", "]", "modulePaths", "=", "flattened", "[", "'Directory'", "]", "prefixDirectories", "=", "list", "(", "set", "(", "flattened", "[", "'Directory'", "]", "+", "headerDirectories", "+", "libraryDirectories", "+", "[", "os", ".", "path", ".", "dirname", "(", "p", ")", "for", "p", "in", "headerDirectories", "+", "libraryDirectories", "]", ")", ")", "# Wrap the results in a ThirdPartyLibraryDetails instance, converting any relative directory paths into absolute ones", "details", "=", "ThirdPartyLibraryDetails", "(", "prefixDirs", "=", "prefixDirectories", ",", "includeDirs", "=", "headerDirectories", ",", "linkDirs", "=", "libraryDirectories", ",", "definitions", "=", "flattened", "[", "'PublicDefinitions'", "]", ",", "libs", "=", "flattened", "[", "'PublicAdditionalLibraries'", "]", ")", "# Apply any overrides", "overridesToApply", "=", "list", "(", "[", "libOverrides", "[", "lib", "]", "for", "lib", "in", "libraries", "if", "lib", "in", "libOverrides", "]", ")", "for", "override", "in", "overridesToApply", ":", "details", ".", "merge", "(", "override", ")", "return", "details" ]
Interrogates UnrealBuildTool about the build flags for the specified third-party libraries
[ "Interrogates", "UnrealBuildTool", "about", "the", "build", "flags", "for", "the", "specified", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UE4BuildInterrogator.py#L23-L90
train
adamrehn/ue4cli
ue4cli/UE4BuildInterrogator.py
UE4BuildInterrogator._flatten
def _flatten(self, field, items, transform = None): """ Extracts the entry `field` from each item in the supplied iterable, flattening any nested lists """ # Retrieve the value for each item in the iterable values = [item[field] for item in items] # Flatten any nested lists flattened = [] for value in values: flattened.extend([value] if isinstance(value, str) else value) # Apply any supplied transformation function return transform(flattened) if transform != None else flattened
python
def _flatten(self, field, items, transform = None): """ Extracts the entry `field` from each item in the supplied iterable, flattening any nested lists """ # Retrieve the value for each item in the iterable values = [item[field] for item in items] # Flatten any nested lists flattened = [] for value in values: flattened.extend([value] if isinstance(value, str) else value) # Apply any supplied transformation function return transform(flattened) if transform != None else flattened
[ "def", "_flatten", "(", "self", ",", "field", ",", "items", ",", "transform", "=", "None", ")", ":", "# Retrieve the value for each item in the iterable", "values", "=", "[", "item", "[", "field", "]", "for", "item", "in", "items", "]", "# Flatten any nested lists", "flattened", "=", "[", "]", "for", "value", "in", "values", ":", "flattened", ".", "extend", "(", "[", "value", "]", "if", "isinstance", "(", "value", ",", "str", ")", "else", "value", ")", "# Apply any supplied transformation function", "return", "transform", "(", "flattened", ")", "if", "transform", "!=", "None", "else", "flattened" ]
Extracts the entry `field` from each item in the supplied iterable, flattening any nested lists
[ "Extracts", "the", "entry", "field", "from", "each", "item", "in", "the", "supplied", "iterable", "flattening", "any", "nested", "lists" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UE4BuildInterrogator.py#L103-L117
train
adamrehn/ue4cli
ue4cli/UE4BuildInterrogator.py
UE4BuildInterrogator._getThirdPartyLibs
def _getThirdPartyLibs(self, platformIdentifier, configuration): """ Runs UnrealBuildTool in JSON export mode and extracts the list of third-party libraries """ # If we have previously cached the library list for the current engine version, use the cached data cachedList = CachedDataManager.getCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries') if cachedList != None: return cachedList # Create a temp directory to hold the JSON file tempDir = tempfile.mkdtemp() jsonFile = os.path.join(tempDir, 'ubt_output.json') # Installed Builds of the Engine only contain a small handful of third-party libraries, rather than the full set # included in a source build of the Engine. However, if the ThirdParty directory from a source build is copied # into an Installed Build and the `InstalledBuild.txt` sentinel file is temporarily renamed, we can get the best # of both worlds and utilise the full set of third-party libraries. Enable this sentinel renaming behaviour only # if you have copied the ThirdParty directory from a source build into your Installed Build, or else the UBT # command will fail trying to rebuild UnrealHeaderTool. sentinelFile = os.path.join(self.engineRoot, 'Engine', 'Build', 'InstalledBuild.txt') sentinelBackup = sentinelFile + '.bak' renameSentinel = os.path.exists(sentinelFile) and os.environ.get('UE4CLI_SENTINEL_RENAME', '0') == '1' if renameSentinel == True: shutil.move(sentinelFile, sentinelBackup) # Invoke UnrealBuildTool in JSON export mode (make sure we specify gathering mode, since this is a prerequisite of JSON export) # (Ensure we always perform sentinel file cleanup even when errors occur) try: args = ['-Mode=JsonExport', '-OutputFile=' +jsonFile ] if self.engineVersion['MinorVersion'] >= 22 else ['-gather', '-jsonexport=' + jsonFile, '-SkipBuild'] self.runUBTFunc('UE4Editor', platformIdentifier, configuration, args) finally: if renameSentinel == True: shutil.move(sentinelBackup, sentinelFile) # Parse the JSON output result = json.loads(Utility.readFile(jsonFile)) # Extract the list of third-party library modules # (Note that since UE4.21, modules no longer have a "Type" field, so we must # rely on the "Directory" field filter below to identify third-party libraries) modules = [result['Modules'][key] for key in result['Modules']] # Filter out any modules from outside the Engine/Source/ThirdParty directory thirdPartyRoot = os.path.join(self.engineRoot, 'Engine', 'Source', 'ThirdParty') thirdparty = list([m for m in modules if thirdPartyRoot in m['Directory']]) # Remove the temp directory try: shutil.rmtree(tempDir) except: pass # Cache the list of libraries for use by subsequent runs CachedDataManager.setCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries', thirdparty) return thirdparty
python
def _getThirdPartyLibs(self, platformIdentifier, configuration): """ Runs UnrealBuildTool in JSON export mode and extracts the list of third-party libraries """ # If we have previously cached the library list for the current engine version, use the cached data cachedList = CachedDataManager.getCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries') if cachedList != None: return cachedList # Create a temp directory to hold the JSON file tempDir = tempfile.mkdtemp() jsonFile = os.path.join(tempDir, 'ubt_output.json') # Installed Builds of the Engine only contain a small handful of third-party libraries, rather than the full set # included in a source build of the Engine. However, if the ThirdParty directory from a source build is copied # into an Installed Build and the `InstalledBuild.txt` sentinel file is temporarily renamed, we can get the best # of both worlds and utilise the full set of third-party libraries. Enable this sentinel renaming behaviour only # if you have copied the ThirdParty directory from a source build into your Installed Build, or else the UBT # command will fail trying to rebuild UnrealHeaderTool. sentinelFile = os.path.join(self.engineRoot, 'Engine', 'Build', 'InstalledBuild.txt') sentinelBackup = sentinelFile + '.bak' renameSentinel = os.path.exists(sentinelFile) and os.environ.get('UE4CLI_SENTINEL_RENAME', '0') == '1' if renameSentinel == True: shutil.move(sentinelFile, sentinelBackup) # Invoke UnrealBuildTool in JSON export mode (make sure we specify gathering mode, since this is a prerequisite of JSON export) # (Ensure we always perform sentinel file cleanup even when errors occur) try: args = ['-Mode=JsonExport', '-OutputFile=' +jsonFile ] if self.engineVersion['MinorVersion'] >= 22 else ['-gather', '-jsonexport=' + jsonFile, '-SkipBuild'] self.runUBTFunc('UE4Editor', platformIdentifier, configuration, args) finally: if renameSentinel == True: shutil.move(sentinelBackup, sentinelFile) # Parse the JSON output result = json.loads(Utility.readFile(jsonFile)) # Extract the list of third-party library modules # (Note that since UE4.21, modules no longer have a "Type" field, so we must # rely on the "Directory" field filter below to identify third-party libraries) modules = [result['Modules'][key] for key in result['Modules']] # Filter out any modules from outside the Engine/Source/ThirdParty directory thirdPartyRoot = os.path.join(self.engineRoot, 'Engine', 'Source', 'ThirdParty') thirdparty = list([m for m in modules if thirdPartyRoot in m['Directory']]) # Remove the temp directory try: shutil.rmtree(tempDir) except: pass # Cache the list of libraries for use by subsequent runs CachedDataManager.setCachedDataKey(self.engineVersionHash, 'ThirdPartyLibraries', thirdparty) return thirdparty
[ "def", "_getThirdPartyLibs", "(", "self", ",", "platformIdentifier", ",", "configuration", ")", ":", "# If we have previously cached the library list for the current engine version, use the cached data", "cachedList", "=", "CachedDataManager", ".", "getCachedDataKey", "(", "self", ".", "engineVersionHash", ",", "'ThirdPartyLibraries'", ")", "if", "cachedList", "!=", "None", ":", "return", "cachedList", "# Create a temp directory to hold the JSON file", "tempDir", "=", "tempfile", ".", "mkdtemp", "(", ")", "jsonFile", "=", "os", ".", "path", ".", "join", "(", "tempDir", ",", "'ubt_output.json'", ")", "# Installed Builds of the Engine only contain a small handful of third-party libraries, rather than the full set", "# included in a source build of the Engine. However, if the ThirdParty directory from a source build is copied", "# into an Installed Build and the `InstalledBuild.txt` sentinel file is temporarily renamed, we can get the best", "# of both worlds and utilise the full set of third-party libraries. Enable this sentinel renaming behaviour only", "# if you have copied the ThirdParty directory from a source build into your Installed Build, or else the UBT", "# command will fail trying to rebuild UnrealHeaderTool.", "sentinelFile", "=", "os", ".", "path", ".", "join", "(", "self", ".", "engineRoot", ",", "'Engine'", ",", "'Build'", ",", "'InstalledBuild.txt'", ")", "sentinelBackup", "=", "sentinelFile", "+", "'.bak'", "renameSentinel", "=", "os", ".", "path", ".", "exists", "(", "sentinelFile", ")", "and", "os", ".", "environ", ".", "get", "(", "'UE4CLI_SENTINEL_RENAME'", ",", "'0'", ")", "==", "'1'", "if", "renameSentinel", "==", "True", ":", "shutil", ".", "move", "(", "sentinelFile", ",", "sentinelBackup", ")", "# Invoke UnrealBuildTool in JSON export mode (make sure we specify gathering mode, since this is a prerequisite of JSON export)", "# (Ensure we always perform sentinel file cleanup even when errors occur)", "try", ":", "args", "=", "[", "'-Mode=JsonExport'", ",", "'-OutputFile='", "+", "jsonFile", "]", "if", "self", ".", "engineVersion", "[", "'MinorVersion'", "]", ">=", "22", "else", "[", "'-gather'", ",", "'-jsonexport='", "+", "jsonFile", ",", "'-SkipBuild'", "]", "self", ".", "runUBTFunc", "(", "'UE4Editor'", ",", "platformIdentifier", ",", "configuration", ",", "args", ")", "finally", ":", "if", "renameSentinel", "==", "True", ":", "shutil", ".", "move", "(", "sentinelBackup", ",", "sentinelFile", ")", "# Parse the JSON output", "result", "=", "json", ".", "loads", "(", "Utility", ".", "readFile", "(", "jsonFile", ")", ")", "# Extract the list of third-party library modules", "# (Note that since UE4.21, modules no longer have a \"Type\" field, so we must", "# rely on the \"Directory\" field filter below to identify third-party libraries)", "modules", "=", "[", "result", "[", "'Modules'", "]", "[", "key", "]", "for", "key", "in", "result", "[", "'Modules'", "]", "]", "# Filter out any modules from outside the Engine/Source/ThirdParty directory", "thirdPartyRoot", "=", "os", ".", "path", ".", "join", "(", "self", ".", "engineRoot", ",", "'Engine'", ",", "'Source'", ",", "'ThirdParty'", ")", "thirdparty", "=", "list", "(", "[", "m", "for", "m", "in", "modules", "if", "thirdPartyRoot", "in", "m", "[", "'Directory'", "]", "]", ")", "# Remove the temp directory", "try", ":", "shutil", ".", "rmtree", "(", "tempDir", ")", "except", ":", "pass", "# Cache the list of libraries for use by subsequent runs", "CachedDataManager", ".", "setCachedDataKey", "(", "self", ".", "engineVersionHash", ",", "'ThirdPartyLibraries'", ",", "thirdparty", ")", "return", "thirdparty" ]
Runs UnrealBuildTool in JSON export mode and extracts the list of third-party libraries
[ "Runs", "UnrealBuildTool", "in", "JSON", "export", "mode", "and", "extracts", "the", "list", "of", "third", "-", "party", "libraries" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/UE4BuildInterrogator.py#L119-L175
train
adamrehn/ue4cli
ue4cli/CMakeCustomFlags.py
CMakeCustomFlags.processLibraryDetails
def processLibraryDetails(details): """ Processes the supplied ThirdPartyLibraryDetails instance and sets any custom CMake flags """ # If the header include directories list contains any directories we have flags for, add them for includeDir in details.includeDirs: # If the directory path matches any of the substrings in our list, generate the relevant flags for pattern in CUSTOM_FLAGS_FOR_INCLUDE_DIRS: if pattern in includeDir: flag = '-D' + CUSTOM_FLAGS_FOR_INCLUDE_DIRS[pattern] + '=' + includeDir details.cmakeFlags.append(flag) # If the libraries list contains any libs we have flags for, add them for lib in details.libs: # Extract the name of the library from the filename # (We remove any "lib" prefix or numerical suffix) filename = os.path.basename(lib) (name, ext) = os.path.splitext(filename) libName = name.replace('lib', '') if name.startswith('lib') else name libName = libName.rstrip('_-1234567890') # If the library name matches one in our list, generate its flag if libName in CUSTOM_FLAGS_FOR_LIBS: flag = '-D' + CUSTOM_FLAGS_FOR_LIBS[libName] + '=' + lib details.cmakeFlags.append(flag)
python
def processLibraryDetails(details): """ Processes the supplied ThirdPartyLibraryDetails instance and sets any custom CMake flags """ # If the header include directories list contains any directories we have flags for, add them for includeDir in details.includeDirs: # If the directory path matches any of the substrings in our list, generate the relevant flags for pattern in CUSTOM_FLAGS_FOR_INCLUDE_DIRS: if pattern in includeDir: flag = '-D' + CUSTOM_FLAGS_FOR_INCLUDE_DIRS[pattern] + '=' + includeDir details.cmakeFlags.append(flag) # If the libraries list contains any libs we have flags for, add them for lib in details.libs: # Extract the name of the library from the filename # (We remove any "lib" prefix or numerical suffix) filename = os.path.basename(lib) (name, ext) = os.path.splitext(filename) libName = name.replace('lib', '') if name.startswith('lib') else name libName = libName.rstrip('_-1234567890') # If the library name matches one in our list, generate its flag if libName in CUSTOM_FLAGS_FOR_LIBS: flag = '-D' + CUSTOM_FLAGS_FOR_LIBS[libName] + '=' + lib details.cmakeFlags.append(flag)
[ "def", "processLibraryDetails", "(", "details", ")", ":", "# If the header include directories list contains any directories we have flags for, add them", "for", "includeDir", "in", "details", ".", "includeDirs", ":", "# If the directory path matches any of the substrings in our list, generate the relevant flags", "for", "pattern", "in", "CUSTOM_FLAGS_FOR_INCLUDE_DIRS", ":", "if", "pattern", "in", "includeDir", ":", "flag", "=", "'-D'", "+", "CUSTOM_FLAGS_FOR_INCLUDE_DIRS", "[", "pattern", "]", "+", "'='", "+", "includeDir", "details", ".", "cmakeFlags", ".", "append", "(", "flag", ")", "# If the libraries list contains any libs we have flags for, add them", "for", "lib", "in", "details", ".", "libs", ":", "# Extract the name of the library from the filename", "# (We remove any \"lib\" prefix or numerical suffix)", "filename", "=", "os", ".", "path", ".", "basename", "(", "lib", ")", "(", "name", ",", "ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "libName", "=", "name", ".", "replace", "(", "'lib'", ",", "''", ")", "if", "name", ".", "startswith", "(", "'lib'", ")", "else", "name", "libName", "=", "libName", ".", "rstrip", "(", "'_-1234567890'", ")", "# If the library name matches one in our list, generate its flag", "if", "libName", "in", "CUSTOM_FLAGS_FOR_LIBS", ":", "flag", "=", "'-D'", "+", "CUSTOM_FLAGS_FOR_LIBS", "[", "libName", "]", "+", "'='", "+", "lib", "details", ".", "cmakeFlags", ".", "append", "(", "flag", ")" ]
Processes the supplied ThirdPartyLibraryDetails instance and sets any custom CMake flags
[ "Processes", "the", "supplied", "ThirdPartyLibraryDetails", "instance", "and", "sets", "any", "custom", "CMake", "flags" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/CMakeCustomFlags.py#L19-L46
train
adamrehn/ue4cli
ue4cli/PluginManager.py
PluginManager.getPlugins
def getPlugins(): """ Returns the list of valid ue4cli plugins """ # Retrieve the list of detected entry points in the ue4cli.plugins group plugins = { entry_point.name: entry_point.load() for entry_point in pkg_resources.iter_entry_points('ue4cli.plugins') } # Filter out any invalid plugins plugins = { name: plugins[name] for name in plugins if 'action' in plugins[name] and 'description' in plugins[name] and 'args' in plugins[name] and callable(plugins[name]['action']) == True and len(signature(plugins[name]['action']).parameters) == 2 } return plugins
python
def getPlugins(): """ Returns the list of valid ue4cli plugins """ # Retrieve the list of detected entry points in the ue4cli.plugins group plugins = { entry_point.name: entry_point.load() for entry_point in pkg_resources.iter_entry_points('ue4cli.plugins') } # Filter out any invalid plugins plugins = { name: plugins[name] for name in plugins if 'action' in plugins[name] and 'description' in plugins[name] and 'args' in plugins[name] and callable(plugins[name]['action']) == True and len(signature(plugins[name]['action']).parameters) == 2 } return plugins
[ "def", "getPlugins", "(", ")", ":", "# Retrieve the list of detected entry points in the ue4cli.plugins group", "plugins", "=", "{", "entry_point", ".", "name", ":", "entry_point", ".", "load", "(", ")", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "'ue4cli.plugins'", ")", "}", "# Filter out any invalid plugins", "plugins", "=", "{", "name", ":", "plugins", "[", "name", "]", "for", "name", "in", "plugins", "if", "'action'", "in", "plugins", "[", "name", "]", "and", "'description'", "in", "plugins", "[", "name", "]", "and", "'args'", "in", "plugins", "[", "name", "]", "and", "callable", "(", "plugins", "[", "name", "]", "[", "'action'", "]", ")", "==", "True", "and", "len", "(", "signature", "(", "plugins", "[", "name", "]", "[", "'action'", "]", ")", ".", "parameters", ")", "==", "2", "}", "return", "plugins" ]
Returns the list of valid ue4cli plugins
[ "Returns", "the", "list", "of", "valid", "ue4cli", "plugins" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/PluginManager.py#L10-L34
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getCompilerFlags
def getCompilerFlags(self, engineRoot, fmt): """ Constructs the compiler flags string for building against this library """ return Utility.join( fmt.delim, self.prefixedStrings(self.definitionPrefix, self.definitions, engineRoot) + self.prefixedStrings(self.includeDirPrefix, self.includeDirs, engineRoot) + self.resolveRoot(self.cxxFlags, engineRoot), fmt.quotes )
python
def getCompilerFlags(self, engineRoot, fmt): """ Constructs the compiler flags string for building against this library """ return Utility.join( fmt.delim, self.prefixedStrings(self.definitionPrefix, self.definitions, engineRoot) + self.prefixedStrings(self.includeDirPrefix, self.includeDirs, engineRoot) + self.resolveRoot(self.cxxFlags, engineRoot), fmt.quotes )
[ "def", "getCompilerFlags", "(", "self", ",", "engineRoot", ",", "fmt", ")", ":", "return", "Utility", ".", "join", "(", "fmt", ".", "delim", ",", "self", ".", "prefixedStrings", "(", "self", ".", "definitionPrefix", ",", "self", ".", "definitions", ",", "engineRoot", ")", "+", "self", ".", "prefixedStrings", "(", "self", ".", "includeDirPrefix", ",", "self", ".", "includeDirs", ",", "engineRoot", ")", "+", "self", ".", "resolveRoot", "(", "self", ".", "cxxFlags", ",", "engineRoot", ")", ",", "fmt", ".", "quotes", ")" ]
Constructs the compiler flags string for building against this library
[ "Constructs", "the", "compiler", "flags", "string", "for", "building", "against", "this", "library" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L71-L81
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getLinkerFlags
def getLinkerFlags(self, engineRoot, fmt, includeLibs=True): """ Constructs the linker flags string for building against this library """ components = self.resolveRoot(self.ldFlags, engineRoot) if includeLibs == True: components.extend(self.prefixedStrings(self.linkerDirPrefix, self.linkDirs, engineRoot)) components.extend(self.resolveRoot(self.libs, engineRoot)) return Utility.join(fmt.delim, components, fmt.quotes)
python
def getLinkerFlags(self, engineRoot, fmt, includeLibs=True): """ Constructs the linker flags string for building against this library """ components = self.resolveRoot(self.ldFlags, engineRoot) if includeLibs == True: components.extend(self.prefixedStrings(self.linkerDirPrefix, self.linkDirs, engineRoot)) components.extend(self.resolveRoot(self.libs, engineRoot)) return Utility.join(fmt.delim, components, fmt.quotes)
[ "def", "getLinkerFlags", "(", "self", ",", "engineRoot", ",", "fmt", ",", "includeLibs", "=", "True", ")", ":", "components", "=", "self", ".", "resolveRoot", "(", "self", ".", "ldFlags", ",", "engineRoot", ")", "if", "includeLibs", "==", "True", ":", "components", ".", "extend", "(", "self", ".", "prefixedStrings", "(", "self", ".", "linkerDirPrefix", ",", "self", ".", "linkDirs", ",", "engineRoot", ")", ")", "components", ".", "extend", "(", "self", ".", "resolveRoot", "(", "self", ".", "libs", ",", "engineRoot", ")", ")", "return", "Utility", ".", "join", "(", "fmt", ".", "delim", ",", "components", ",", "fmt", ".", "quotes", ")" ]
Constructs the linker flags string for building against this library
[ "Constructs", "the", "linker", "flags", "string", "for", "building", "against", "this", "library" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L83-L92
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getPrefixDirectories
def getPrefixDirectories(self, engineRoot, delimiter=' '): """ Returns the list of prefix directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.prefixDirs, engineRoot))
python
def getPrefixDirectories(self, engineRoot, delimiter=' '): """ Returns the list of prefix directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.prefixDirs, engineRoot))
[ "def", "getPrefixDirectories", "(", "self", ",", "engineRoot", ",", "delimiter", "=", "' '", ")", ":", "return", "delimiter", ".", "join", "(", "self", ".", "resolveRoot", "(", "self", ".", "prefixDirs", ",", "engineRoot", ")", ")" ]
Returns the list of prefix directories for this library, joined using the specified delimiter
[ "Returns", "the", "list", "of", "prefix", "directories", "for", "this", "library", "joined", "using", "the", "specified", "delimiter" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L94-L98
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getIncludeDirectories
def getIncludeDirectories(self, engineRoot, delimiter=' '): """ Returns the list of include directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.includeDirs, engineRoot))
python
def getIncludeDirectories(self, engineRoot, delimiter=' '): """ Returns the list of include directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.includeDirs, engineRoot))
[ "def", "getIncludeDirectories", "(", "self", ",", "engineRoot", ",", "delimiter", "=", "' '", ")", ":", "return", "delimiter", ".", "join", "(", "self", ".", "resolveRoot", "(", "self", ".", "includeDirs", ",", "engineRoot", ")", ")" ]
Returns the list of include directories for this library, joined using the specified delimiter
[ "Returns", "the", "list", "of", "include", "directories", "for", "this", "library", "joined", "using", "the", "specified", "delimiter" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L100-L104
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getLinkerDirectories
def getLinkerDirectories(self, engineRoot, delimiter=' '): """ Returns the list of linker directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.linkDirs, engineRoot))
python
def getLinkerDirectories(self, engineRoot, delimiter=' '): """ Returns the list of linker directories for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.linkDirs, engineRoot))
[ "def", "getLinkerDirectories", "(", "self", ",", "engineRoot", ",", "delimiter", "=", "' '", ")", ":", "return", "delimiter", ".", "join", "(", "self", ".", "resolveRoot", "(", "self", ".", "linkDirs", ",", "engineRoot", ")", ")" ]
Returns the list of linker directories for this library, joined using the specified delimiter
[ "Returns", "the", "list", "of", "linker", "directories", "for", "this", "library", "joined", "using", "the", "specified", "delimiter" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L106-L110
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getLibraryFiles
def getLibraryFiles(self, engineRoot, delimiter=' '): """ Returns the list of library files for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.libs, engineRoot))
python
def getLibraryFiles(self, engineRoot, delimiter=' '): """ Returns the list of library files for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.libs, engineRoot))
[ "def", "getLibraryFiles", "(", "self", ",", "engineRoot", ",", "delimiter", "=", "' '", ")", ":", "return", "delimiter", ".", "join", "(", "self", ".", "resolveRoot", "(", "self", ".", "libs", ",", "engineRoot", ")", ")" ]
Returns the list of library files for this library, joined using the specified delimiter
[ "Returns", "the", "list", "of", "library", "files", "for", "this", "library", "joined", "using", "the", "specified", "delimiter" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L112-L116
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getPreprocessorDefinitions
def getPreprocessorDefinitions(self, engineRoot, delimiter=' '): """ Returns the list of preprocessor definitions for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.definitions, engineRoot))
python
def getPreprocessorDefinitions(self, engineRoot, delimiter=' '): """ Returns the list of preprocessor definitions for this library, joined using the specified delimiter """ return delimiter.join(self.resolveRoot(self.definitions, engineRoot))
[ "def", "getPreprocessorDefinitions", "(", "self", ",", "engineRoot", ",", "delimiter", "=", "' '", ")", ":", "return", "delimiter", ".", "join", "(", "self", ".", "resolveRoot", "(", "self", ".", "definitions", ",", "engineRoot", ")", ")" ]
Returns the list of preprocessor definitions for this library, joined using the specified delimiter
[ "Returns", "the", "list", "of", "preprocessor", "definitions", "for", "this", "library", "joined", "using", "the", "specified", "delimiter" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L118-L122
train
adamrehn/ue4cli
ue4cli/ThirdPartyLibraryDetails.py
ThirdPartyLibraryDetails.getCMakeFlags
def getCMakeFlags(self, engineRoot, fmt): """ Constructs the CMake invocation flags string for building against this library """ return Utility.join( fmt.delim, [ '-DCMAKE_PREFIX_PATH=' + self.getPrefixDirectories(engineRoot, ';'), '-DCMAKE_INCLUDE_PATH=' + self.getIncludeDirectories(engineRoot, ';'), '-DCMAKE_LIBRARY_PATH=' + self.getLinkerDirectories(engineRoot, ';'), ] + self.resolveRoot(self.cmakeFlags, engineRoot), fmt.quotes )
python
def getCMakeFlags(self, engineRoot, fmt): """ Constructs the CMake invocation flags string for building against this library """ return Utility.join( fmt.delim, [ '-DCMAKE_PREFIX_PATH=' + self.getPrefixDirectories(engineRoot, ';'), '-DCMAKE_INCLUDE_PATH=' + self.getIncludeDirectories(engineRoot, ';'), '-DCMAKE_LIBRARY_PATH=' + self.getLinkerDirectories(engineRoot, ';'), ] + self.resolveRoot(self.cmakeFlags, engineRoot), fmt.quotes )
[ "def", "getCMakeFlags", "(", "self", ",", "engineRoot", ",", "fmt", ")", ":", "return", "Utility", ".", "join", "(", "fmt", ".", "delim", ",", "[", "'-DCMAKE_PREFIX_PATH='", "+", "self", ".", "getPrefixDirectories", "(", "engineRoot", ",", "';'", ")", ",", "'-DCMAKE_INCLUDE_PATH='", "+", "self", ".", "getIncludeDirectories", "(", "engineRoot", ",", "';'", ")", ",", "'-DCMAKE_LIBRARY_PATH='", "+", "self", ".", "getLinkerDirectories", "(", "engineRoot", ",", "';'", ")", ",", "]", "+", "self", ".", "resolveRoot", "(", "self", ".", "cmakeFlags", ",", "engineRoot", ")", ",", "fmt", ".", "quotes", ")" ]
Constructs the CMake invocation flags string for building against this library
[ "Constructs", "the", "CMake", "invocation", "flags", "string", "for", "building", "against", "this", "library" ]
f1c34502c96059e36757b7433da7e98760a75a6f
https://github.com/adamrehn/ue4cli/blob/f1c34502c96059e36757b7433da7e98760a75a6f/ue4cli/ThirdPartyLibraryDetails.py#L124-L136
train
tkrajina/git-plus
gitutils/__init__.py
is_changed
def is_changed(): """ Checks if current project has any noncommited changes. """ executed, changed_lines = execute_git('status --porcelain', output=False) merge_not_finished = mod_path.exists('.git/MERGE_HEAD') return changed_lines.strip() or merge_not_finished
python
def is_changed(): """ Checks if current project has any noncommited changes. """ executed, changed_lines = execute_git('status --porcelain', output=False) merge_not_finished = mod_path.exists('.git/MERGE_HEAD') return changed_lines.strip() or merge_not_finished
[ "def", "is_changed", "(", ")", ":", "executed", ",", "changed_lines", "=", "execute_git", "(", "'status --porcelain'", ",", "output", "=", "False", ")", "merge_not_finished", "=", "mod_path", ".", "exists", "(", "'.git/MERGE_HEAD'", ")", "return", "changed_lines", ".", "strip", "(", ")", "or", "merge_not_finished" ]
Checks if current project has any noncommited changes.
[ "Checks", "if", "current", "project", "has", "any", "noncommited", "changes", "." ]
6adf9ae5c695feab5e8ed18f93777ac05dd4957c
https://github.com/tkrajina/git-plus/blob/6adf9ae5c695feab5e8ed18f93777ac05dd4957c/gitutils/__init__.py#L108-L112
train
edx/edx-rest-api-client
edx_rest_api_client/client.py
user_agent
def user_agent(): """ Return a User-Agent that identifies this client. Example: python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce The last item in the list will be the application name, taken from the OS environment variable EDX_REST_API_CLIENT_NAME. If that environment variable is not set, it will default to the hostname. """ client_name = 'unknown_client_name' try: client_name = os.environ.get("EDX_REST_API_CLIENT_NAME") or socket.gethostbyname(socket.gethostname()) except: # pylint: disable=bare-except pass # using 'unknown_client_name' is good enough. no need to log. return "{} edx-rest-api-client/{} {}".format( requests.utils.default_user_agent(), # e.g. "python-requests/2.9.1" __version__, # version of this client client_name )
python
def user_agent(): """ Return a User-Agent that identifies this client. Example: python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce The last item in the list will be the application name, taken from the OS environment variable EDX_REST_API_CLIENT_NAME. If that environment variable is not set, it will default to the hostname. """ client_name = 'unknown_client_name' try: client_name = os.environ.get("EDX_REST_API_CLIENT_NAME") or socket.gethostbyname(socket.gethostname()) except: # pylint: disable=bare-except pass # using 'unknown_client_name' is good enough. no need to log. return "{} edx-rest-api-client/{} {}".format( requests.utils.default_user_agent(), # e.g. "python-requests/2.9.1" __version__, # version of this client client_name )
[ "def", "user_agent", "(", ")", ":", "client_name", "=", "'unknown_client_name'", "try", ":", "client_name", "=", "os", ".", "environ", ".", "get", "(", "\"EDX_REST_API_CLIENT_NAME\"", ")", "or", "socket", ".", "gethostbyname", "(", "socket", ".", "gethostname", "(", ")", ")", "except", ":", "# pylint: disable=bare-except", "pass", "# using 'unknown_client_name' is good enough. no need to log.", "return", "\"{} edx-rest-api-client/{} {}\"", ".", "format", "(", "requests", ".", "utils", ".", "default_user_agent", "(", ")", ",", "# e.g. \"python-requests/2.9.1\"", "__version__", ",", "# version of this client", "client_name", ")" ]
Return a User-Agent that identifies this client. Example: python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce The last item in the list will be the application name, taken from the OS environment variable EDX_REST_API_CLIENT_NAME. If that environment variable is not set, it will default to the hostname.
[ "Return", "a", "User", "-", "Agent", "that", "identifies", "this", "client", "." ]
7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b
https://github.com/edx/edx-rest-api-client/blob/7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b/edx_rest_api_client/client.py#L14-L34
train
edx/edx-rest-api-client
edx_rest_api_client/client.py
get_oauth_access_token
def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None): """ Retrieves OAuth 2.0 access token using the given grant type. Args: url (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret Kwargs: token_type (str): Type of token to return. Options include bearer and jwt. grant_type (str): One of 'client_credentials' or 'refresh_token' refresh_token (str): The previous access token (for grant_type=refresh_token) Returns: tuple: Tuple containing access token string and expiration datetime. """ now = datetime.datetime.utcnow() data = { 'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'token_type': token_type, } if refresh_token: data['refresh_token'] = refresh_token else: assert grant_type != 'refresh_token', "refresh_token parameter required" response = requests.post( url, data=data, headers={ 'User-Agent': USER_AGENT, }, ) data = response.json() try: access_token = data['access_token'] expires_in = data['expires_in'] except KeyError: raise requests.RequestException(response=response) expires_at = now + datetime.timedelta(seconds=expires_in) return access_token, expires_at
python
def get_oauth_access_token(url, client_id, client_secret, token_type='jwt', grant_type='client_credentials', refresh_token=None): """ Retrieves OAuth 2.0 access token using the given grant type. Args: url (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret Kwargs: token_type (str): Type of token to return. Options include bearer and jwt. grant_type (str): One of 'client_credentials' or 'refresh_token' refresh_token (str): The previous access token (for grant_type=refresh_token) Returns: tuple: Tuple containing access token string and expiration datetime. """ now = datetime.datetime.utcnow() data = { 'grant_type': grant_type, 'client_id': client_id, 'client_secret': client_secret, 'token_type': token_type, } if refresh_token: data['refresh_token'] = refresh_token else: assert grant_type != 'refresh_token', "refresh_token parameter required" response = requests.post( url, data=data, headers={ 'User-Agent': USER_AGENT, }, ) data = response.json() try: access_token = data['access_token'] expires_in = data['expires_in'] except KeyError: raise requests.RequestException(response=response) expires_at = now + datetime.timedelta(seconds=expires_in) return access_token, expires_at
[ "def", "get_oauth_access_token", "(", "url", ",", "client_id", ",", "client_secret", ",", "token_type", "=", "'jwt'", ",", "grant_type", "=", "'client_credentials'", ",", "refresh_token", "=", "None", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", "data", "=", "{", "'grant_type'", ":", "grant_type", ",", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "client_secret", ",", "'token_type'", ":", "token_type", ",", "}", "if", "refresh_token", ":", "data", "[", "'refresh_token'", "]", "=", "refresh_token", "else", ":", "assert", "grant_type", "!=", "'refresh_token'", ",", "\"refresh_token parameter required\"", "response", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "data", ",", "headers", "=", "{", "'User-Agent'", ":", "USER_AGENT", ",", "}", ",", ")", "data", "=", "response", ".", "json", "(", ")", "try", ":", "access_token", "=", "data", "[", "'access_token'", "]", "expires_in", "=", "data", "[", "'expires_in'", "]", "except", "KeyError", ":", "raise", "requests", ".", "RequestException", "(", "response", "=", "response", ")", "expires_at", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "expires_in", ")", "return", "access_token", ",", "expires_at" ]
Retrieves OAuth 2.0 access token using the given grant type. Args: url (str): Oauth2 access token endpoint client_id (str): client ID client_secret (str): client secret Kwargs: token_type (str): Type of token to return. Options include bearer and jwt. grant_type (str): One of 'client_credentials' or 'refresh_token' refresh_token (str): The previous access token (for grant_type=refresh_token) Returns: tuple: Tuple containing access token string and expiration datetime.
[ "Retrieves", "OAuth", "2", ".", "0", "access", "token", "using", "the", "given", "grant", "type", "." ]
7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b
https://github.com/edx/edx-rest-api-client/blob/7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b/edx_rest_api_client/client.py#L40-L85
train
edx/edx-rest-api-client
edx_rest_api_client/client.py
OAuthAPIClient.request
def request(self, method, url, **kwargs): # pylint: disable=arguments-differ """ Overrides Session.request to ensure that the session is authenticated """ self._check_auth() return super(OAuthAPIClient, self).request(method, url, **kwargs)
python
def request(self, method, url, **kwargs): # pylint: disable=arguments-differ """ Overrides Session.request to ensure that the session is authenticated """ self._check_auth() return super(OAuthAPIClient, self).request(method, url, **kwargs)
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=arguments-differ", "self", ".", "_check_auth", "(", ")", "return", "super", "(", "OAuthAPIClient", ",", "self", ")", ".", "request", "(", "method", ",", "url", ",", "*", "*", "kwargs", ")" ]
Overrides Session.request to ensure that the session is authenticated
[ "Overrides", "Session", ".", "request", "to", "ensure", "that", "the", "session", "is", "authenticated" ]
7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b
https://github.com/edx/edx-rest-api-client/blob/7ed2a833691d2fdf3a4fbc9189ee5c4443bd892b/edx_rest_api_client/client.py#L121-L126
train
greenbone/ospd
ospd/ospd_ssh.py
OSPDaemonSimpleSSH.run_command
def run_command(self, scan_id, host, cmd): """ Run a single command via SSH and return the content of stdout or None in case of an Error. A scan error is issued in the latter case. For logging into 'host', the scan options 'port', 'username', 'password' and 'ssh_timeout' are used. """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) options = self.get_scan_options(scan_id) port = int(options['port']) timeout = int(options['ssh_timeout']) # For backward compatibility, consider the legacy mode to get # credentials as scan_option. # First and second modes should be removed in future releases. # On the third case it receives the credentials as a subelement of # the <target>. credentials = self.get_scan_credentials(scan_id, host) if ('username_password' in options and ':' in options['username_password']): username, password = options['username_password'].split(':', 1) elif 'username' in options and options['username']: username = options['username'] password = options['password'] elif credentials: cred_params = credentials.get('ssh') username = cred_params.get('username', '') password = cred_params.get('password', '') else: self.add_scan_error(scan_id, host=host, value='Erroneous username_password value') raise ValueError('Erroneous username_password value') try: ssh.connect(hostname=host, username=username, password=password, timeout=timeout, port=port) except (paramiko.ssh_exception.AuthenticationException, socket.error) as err: # Errors: No route to host, connection timeout, authentication # failure etc,. self.add_scan_error(scan_id, host=host, value=str(err)) return None _, stdout, _ = ssh.exec_command(cmd) result = stdout.readlines() ssh.close() return result
python
def run_command(self, scan_id, host, cmd): """ Run a single command via SSH and return the content of stdout or None in case of an Error. A scan error is issued in the latter case. For logging into 'host', the scan options 'port', 'username', 'password' and 'ssh_timeout' are used. """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) options = self.get_scan_options(scan_id) port = int(options['port']) timeout = int(options['ssh_timeout']) # For backward compatibility, consider the legacy mode to get # credentials as scan_option. # First and second modes should be removed in future releases. # On the third case it receives the credentials as a subelement of # the <target>. credentials = self.get_scan_credentials(scan_id, host) if ('username_password' in options and ':' in options['username_password']): username, password = options['username_password'].split(':', 1) elif 'username' in options and options['username']: username = options['username'] password = options['password'] elif credentials: cred_params = credentials.get('ssh') username = cred_params.get('username', '') password = cred_params.get('password', '') else: self.add_scan_error(scan_id, host=host, value='Erroneous username_password value') raise ValueError('Erroneous username_password value') try: ssh.connect(hostname=host, username=username, password=password, timeout=timeout, port=port) except (paramiko.ssh_exception.AuthenticationException, socket.error) as err: # Errors: No route to host, connection timeout, authentication # failure etc,. self.add_scan_error(scan_id, host=host, value=str(err)) return None _, stdout, _ = ssh.exec_command(cmd) result = stdout.readlines() ssh.close() return result
[ "def", "run_command", "(", "self", ",", "scan_id", ",", "host", ",", "cmd", ")", ":", "ssh", "=", "paramiko", ".", "SSHClient", "(", ")", "ssh", ".", "set_missing_host_key_policy", "(", "paramiko", ".", "AutoAddPolicy", "(", ")", ")", "options", "=", "self", ".", "get_scan_options", "(", "scan_id", ")", "port", "=", "int", "(", "options", "[", "'port'", "]", ")", "timeout", "=", "int", "(", "options", "[", "'ssh_timeout'", "]", ")", "# For backward compatibility, consider the legacy mode to get", "# credentials as scan_option.", "# First and second modes should be removed in future releases.", "# On the third case it receives the credentials as a subelement of", "# the <target>.", "credentials", "=", "self", ".", "get_scan_credentials", "(", "scan_id", ",", "host", ")", "if", "(", "'username_password'", "in", "options", "and", "':'", "in", "options", "[", "'username_password'", "]", ")", ":", "username", ",", "password", "=", "options", "[", "'username_password'", "]", ".", "split", "(", "':'", ",", "1", ")", "elif", "'username'", "in", "options", "and", "options", "[", "'username'", "]", ":", "username", "=", "options", "[", "'username'", "]", "password", "=", "options", "[", "'password'", "]", "elif", "credentials", ":", "cred_params", "=", "credentials", ".", "get", "(", "'ssh'", ")", "username", "=", "cred_params", ".", "get", "(", "'username'", ",", "''", ")", "password", "=", "cred_params", ".", "get", "(", "'password'", ",", "''", ")", "else", ":", "self", ".", "add_scan_error", "(", "scan_id", ",", "host", "=", "host", ",", "value", "=", "'Erroneous username_password value'", ")", "raise", "ValueError", "(", "'Erroneous username_password value'", ")", "try", ":", "ssh", ".", "connect", "(", "hostname", "=", "host", ",", "username", "=", "username", ",", "password", "=", "password", ",", "timeout", "=", "timeout", ",", "port", "=", "port", ")", "except", "(", "paramiko", ".", "ssh_exception", ".", "AuthenticationException", ",", "socket", ".", "error", ")", "as", "err", ":", "# Errors: No route to host, connection timeout, authentication", "# failure etc,.", "self", ".", "add_scan_error", "(", "scan_id", ",", "host", "=", "host", ",", "value", "=", "str", "(", "err", ")", ")", "return", "None", "_", ",", "stdout", ",", "_", "=", "ssh", ".", "exec_command", "(", "cmd", ")", "result", "=", "stdout", ".", "readlines", "(", ")", "ssh", ".", "close", "(", ")", "return", "result" ]
Run a single command via SSH and return the content of stdout or None in case of an Error. A scan error is issued in the latter case. For logging into 'host', the scan options 'port', 'username', 'password' and 'ssh_timeout' are used.
[ "Run", "a", "single", "command", "via", "SSH", "and", "return", "the", "content", "of", "stdout", "or", "None", "in", "case", "of", "an", "Error", ".", "A", "scan", "error", "is", "issued", "in", "the", "latter", "case", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd_ssh.py#L94-L147
train
greenbone/ospd
ospd/xml.py
get_result_xml
def get_result_xml(result): """ Formats a scan result to XML format. Arguments: result (dict): Dictionary with a scan result. Return: Result as xml element object. """ result_xml = Element('result') for name, value in [('name', result['name']), ('type', ResultType.get_str(result['type'])), ('severity', result['severity']), ('host', result['host']), ('test_id', result['test_id']), ('port', result['port']), ('qod', result['qod'])]: result_xml.set(name, str(value)) result_xml.text = result['value'] return result_xml
python
def get_result_xml(result): """ Formats a scan result to XML format. Arguments: result (dict): Dictionary with a scan result. Return: Result as xml element object. """ result_xml = Element('result') for name, value in [('name', result['name']), ('type', ResultType.get_str(result['type'])), ('severity', result['severity']), ('host', result['host']), ('test_id', result['test_id']), ('port', result['port']), ('qod', result['qod'])]: result_xml.set(name, str(value)) result_xml.text = result['value'] return result_xml
[ "def", "get_result_xml", "(", "result", ")", ":", "result_xml", "=", "Element", "(", "'result'", ")", "for", "name", ",", "value", "in", "[", "(", "'name'", ",", "result", "[", "'name'", "]", ")", ",", "(", "'type'", ",", "ResultType", ".", "get_str", "(", "result", "[", "'type'", "]", ")", ")", ",", "(", "'severity'", ",", "result", "[", "'severity'", "]", ")", ",", "(", "'host'", ",", "result", "[", "'host'", "]", ")", ",", "(", "'test_id'", ",", "result", "[", "'test_id'", "]", ")", ",", "(", "'port'", ",", "result", "[", "'port'", "]", ")", ",", "(", "'qod'", ",", "result", "[", "'qod'", "]", ")", "]", ":", "result_xml", ".", "set", "(", "name", ",", "str", "(", "value", ")", ")", "result_xml", ".", "text", "=", "result", "[", "'value'", "]", "return", "result_xml" ]
Formats a scan result to XML format. Arguments: result (dict): Dictionary with a scan result. Return: Result as xml element object.
[ "Formats", "a", "scan", "result", "to", "XML", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/xml.py#L25-L44
train
greenbone/ospd
ospd/xml.py
simple_response_str
def simple_response_str(command, status, status_text, content=""): """ Creates an OSP response XML string. Arguments: command (str): OSP Command to respond to. status (int): Status of the response. status_text (str): Status text of the response. content (str): Text part of the response XML element. Return: String of response in xml format. """ response = Element('%s_response' % command) for name, value in [('status', str(status)), ('status_text', status_text)]: response.set(name, str(value)) if isinstance(content, list): for elem in content: response.append(elem) elif isinstance(content, Element): response.append(content) else: response.text = content return tostring(response)
python
def simple_response_str(command, status, status_text, content=""): """ Creates an OSP response XML string. Arguments: command (str): OSP Command to respond to. status (int): Status of the response. status_text (str): Status text of the response. content (str): Text part of the response XML element. Return: String of response in xml format. """ response = Element('%s_response' % command) for name, value in [('status', str(status)), ('status_text', status_text)]: response.set(name, str(value)) if isinstance(content, list): for elem in content: response.append(elem) elif isinstance(content, Element): response.append(content) else: response.text = content return tostring(response)
[ "def", "simple_response_str", "(", "command", ",", "status", ",", "status_text", ",", "content", "=", "\"\"", ")", ":", "response", "=", "Element", "(", "'%s_response'", "%", "command", ")", "for", "name", ",", "value", "in", "[", "(", "'status'", ",", "str", "(", "status", ")", ")", ",", "(", "'status_text'", ",", "status_text", ")", "]", ":", "response", ".", "set", "(", "name", ",", "str", "(", "value", ")", ")", "if", "isinstance", "(", "content", ",", "list", ")", ":", "for", "elem", "in", "content", ":", "response", ".", "append", "(", "elem", ")", "elif", "isinstance", "(", "content", ",", "Element", ")", ":", "response", ".", "append", "(", "content", ")", "else", ":", "response", ".", "text", "=", "content", "return", "tostring", "(", "response", ")" ]
Creates an OSP response XML string. Arguments: command (str): OSP Command to respond to. status (int): Status of the response. status_text (str): Status text of the response. content (str): Text part of the response XML element. Return: String of response in xml format.
[ "Creates", "an", "OSP", "response", "XML", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/xml.py#L47-L69
train
greenbone/ospd
ospd/ospd.py
close_client_stream
def close_client_stream(client_stream, unix_path): """ Closes provided client stream """ try: client_stream.shutdown(socket.SHUT_RDWR) if unix_path: logger.debug('%s: Connection closed', unix_path) else: peer = client_stream.getpeername() logger.debug('%s:%s: Connection closed', peer[0], peer[1]) except (socket.error, OSError) as exception: logger.debug('Connection closing error: %s', exception) client_stream.close()
python
def close_client_stream(client_stream, unix_path): """ Closes provided client stream """ try: client_stream.shutdown(socket.SHUT_RDWR) if unix_path: logger.debug('%s: Connection closed', unix_path) else: peer = client_stream.getpeername() logger.debug('%s:%s: Connection closed', peer[0], peer[1]) except (socket.error, OSError) as exception: logger.debug('Connection closing error: %s', exception) client_stream.close()
[ "def", "close_client_stream", "(", "client_stream", ",", "unix_path", ")", ":", "try", ":", "client_stream", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "if", "unix_path", ":", "logger", ".", "debug", "(", "'%s: Connection closed'", ",", "unix_path", ")", "else", ":", "peer", "=", "client_stream", ".", "getpeername", "(", ")", "logger", ".", "debug", "(", "'%s:%s: Connection closed'", ",", "peer", "[", "0", "]", ",", "peer", "[", "1", "]", ")", "except", "(", "socket", ".", "error", ",", "OSError", ")", "as", "exception", ":", "logger", ".", "debug", "(", "'Connection closing error: %s'", ",", "exception", ")", "client_stream", ".", "close", "(", ")" ]
Closes provided client stream
[ "Closes", "provided", "client", "stream" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L169-L180
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_command_attributes
def set_command_attributes(self, name, attributes): """ Sets the xml attributes of a specified command. """ if self.command_exists(name): command = self.commands.get(name) command['attributes'] = attributes
python
def set_command_attributes(self, name, attributes): """ Sets the xml attributes of a specified command. """ if self.command_exists(name): command = self.commands.get(name) command['attributes'] = attributes
[ "def", "set_command_attributes", "(", "self", ",", "name", ",", "attributes", ")", ":", "if", "self", ".", "command_exists", "(", "name", ")", ":", "command", "=", "self", ".", "commands", ".", "get", "(", "name", ")", "command", "[", "'attributes'", "]", "=", "attributes" ]
Sets the xml attributes of a specified command.
[ "Sets", "the", "xml", "attributes", "of", "a", "specified", "command", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L243-L247
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scanner_param
def add_scanner_param(self, name, scanner_param): """ Add a scanner parameter. """ assert name assert scanner_param self.scanner_params[name] = scanner_param command = self.commands.get('start_scan') command['elements'] = { 'scanner_params': {k: v['name'] for k, v in self.scanner_params.items()}}
python
def add_scanner_param(self, name, scanner_param): """ Add a scanner parameter. """ assert name assert scanner_param self.scanner_params[name] = scanner_param command = self.commands.get('start_scan') command['elements'] = { 'scanner_params': {k: v['name'] for k, v in self.scanner_params.items()}}
[ "def", "add_scanner_param", "(", "self", ",", "name", ",", "scanner_param", ")", ":", "assert", "name", "assert", "scanner_param", "self", ".", "scanner_params", "[", "name", "]", "=", "scanner_param", "command", "=", "self", ".", "commands", ".", "get", "(", "'start_scan'", ")", "command", "[", "'elements'", "]", "=", "{", "'scanner_params'", ":", "{", "k", ":", "v", "[", "'name'", "]", "for", "k", ",", "v", "in", "self", ".", "scanner_params", ".", "items", "(", ")", "}", "}" ]
Add a scanner parameter.
[ "Add", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L249-L258
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_vt
def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None, custom=None, vt_creation_time=None, vt_modification_time=None, vt_dependencies=None, summary=None, impact=None, affected=None, insight=None, solution=None, solution_t=None, detection=None, qod_t=None, qod_v=None, severities=None): """ Add a vulnerability test information. Returns: The new number of stored VTs. -1 in case the VT ID was already present and thus the new VT was not considered. -2 in case the vt_id was invalid. """ if not vt_id: return -2 # no valid vt_id if self.vt_id_pattern.fullmatch(vt_id) is None: return -2 # no valid vt_id if vt_id in self.vts: return -1 # The VT was already in the list. if name is None: name = '' self.vts[vt_id] = {'name': name} if custom is not None: self.vts[vt_id]["custom"] = custom if vt_params is not None: self.vts[vt_id]["vt_params"] = vt_params if vt_refs is not None: self.vts[vt_id]["vt_refs"] = vt_refs if vt_dependencies is not None: self.vts[vt_id]["vt_dependencies"] = vt_dependencies if vt_creation_time is not None: self.vts[vt_id]["creation_time"] = vt_creation_time if vt_modification_time is not None: self.vts[vt_id]["modification_time"] = vt_modification_time if summary is not None: self.vts[vt_id]["summary"] = summary if impact is not None: self.vts[vt_id]["impact"] = impact if affected is not None: self.vts[vt_id]["affected"] = affected if insight is not None: self.vts[vt_id]["insight"] = insight if solution is not None: self.vts[vt_id]["solution"] = solution if solution_t is not None: self.vts[vt_id]["solution_type"] = solution_t if detection is not None: self.vts[vt_id]["detection"] = detection if qod_t is not None: self.vts[vt_id]["qod_type"] = qod_t elif qod_v is not None: self.vts[vt_id]["qod"] = qod_v if severities is not None: self.vts[vt_id]["severities"] = severities return len(self.vts)
python
def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None, custom=None, vt_creation_time=None, vt_modification_time=None, vt_dependencies=None, summary=None, impact=None, affected=None, insight=None, solution=None, solution_t=None, detection=None, qod_t=None, qod_v=None, severities=None): """ Add a vulnerability test information. Returns: The new number of stored VTs. -1 in case the VT ID was already present and thus the new VT was not considered. -2 in case the vt_id was invalid. """ if not vt_id: return -2 # no valid vt_id if self.vt_id_pattern.fullmatch(vt_id) is None: return -2 # no valid vt_id if vt_id in self.vts: return -1 # The VT was already in the list. if name is None: name = '' self.vts[vt_id] = {'name': name} if custom is not None: self.vts[vt_id]["custom"] = custom if vt_params is not None: self.vts[vt_id]["vt_params"] = vt_params if vt_refs is not None: self.vts[vt_id]["vt_refs"] = vt_refs if vt_dependencies is not None: self.vts[vt_id]["vt_dependencies"] = vt_dependencies if vt_creation_time is not None: self.vts[vt_id]["creation_time"] = vt_creation_time if vt_modification_time is not None: self.vts[vt_id]["modification_time"] = vt_modification_time if summary is not None: self.vts[vt_id]["summary"] = summary if impact is not None: self.vts[vt_id]["impact"] = impact if affected is not None: self.vts[vt_id]["affected"] = affected if insight is not None: self.vts[vt_id]["insight"] = insight if solution is not None: self.vts[vt_id]["solution"] = solution if solution_t is not None: self.vts[vt_id]["solution_type"] = solution_t if detection is not None: self.vts[vt_id]["detection"] = detection if qod_t is not None: self.vts[vt_id]["qod_type"] = qod_t elif qod_v is not None: self.vts[vt_id]["qod"] = qod_v if severities is not None: self.vts[vt_id]["severities"] = severities return len(self.vts)
[ "def", "add_vt", "(", "self", ",", "vt_id", ",", "name", "=", "None", ",", "vt_params", "=", "None", ",", "vt_refs", "=", "None", ",", "custom", "=", "None", ",", "vt_creation_time", "=", "None", ",", "vt_modification_time", "=", "None", ",", "vt_dependencies", "=", "None", ",", "summary", "=", "None", ",", "impact", "=", "None", ",", "affected", "=", "None", ",", "insight", "=", "None", ",", "solution", "=", "None", ",", "solution_t", "=", "None", ",", "detection", "=", "None", ",", "qod_t", "=", "None", ",", "qod_v", "=", "None", ",", "severities", "=", "None", ")", ":", "if", "not", "vt_id", ":", "return", "-", "2", "# no valid vt_id", "if", "self", ".", "vt_id_pattern", ".", "fullmatch", "(", "vt_id", ")", "is", "None", ":", "return", "-", "2", "# no valid vt_id", "if", "vt_id", "in", "self", ".", "vts", ":", "return", "-", "1", "# The VT was already in the list.", "if", "name", "is", "None", ":", "name", "=", "''", "self", ".", "vts", "[", "vt_id", "]", "=", "{", "'name'", ":", "name", "}", "if", "custom", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"custom\"", "]", "=", "custom", "if", "vt_params", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"vt_params\"", "]", "=", "vt_params", "if", "vt_refs", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"vt_refs\"", "]", "=", "vt_refs", "if", "vt_dependencies", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"vt_dependencies\"", "]", "=", "vt_dependencies", "if", "vt_creation_time", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"creation_time\"", "]", "=", "vt_creation_time", "if", "vt_modification_time", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"modification_time\"", "]", "=", "vt_modification_time", "if", "summary", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"summary\"", "]", "=", "summary", "if", "impact", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"impact\"", "]", "=", "impact", "if", "affected", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"affected\"", "]", "=", "affected", "if", "insight", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"insight\"", "]", "=", "insight", "if", "solution", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"solution\"", "]", "=", "solution", "if", "solution_t", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"solution_type\"", "]", "=", "solution_t", "if", "detection", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"detection\"", "]", "=", "detection", "if", "qod_t", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"qod_type\"", "]", "=", "qod_t", "elif", "qod_v", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"qod\"", "]", "=", "qod_v", "if", "severities", "is", "not", "None", ":", "self", ".", "vts", "[", "vt_id", "]", "[", "\"severities\"", "]", "=", "severities", "return", "len", "(", "self", ".", "vts", ")" ]
Add a vulnerability test information. Returns: The new number of stored VTs. -1 in case the VT ID was already present and thus the new VT was not considered. -2 in case the vt_id was invalid.
[ "Add", "a", "vulnerability", "test", "information", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L260-L319
train
greenbone/ospd
ospd/ospd.py
OSPDaemon._preprocess_scan_params
def _preprocess_scan_params(self, xml_params): """ Processes the scan parameters. """ params = {} for param in xml_params: params[param.tag] = param.text or '' # Set default values. for key in self.scanner_params: if key not in params: params[key] = self.get_scanner_param_default(key) if self.get_scanner_param_type(key) == 'selection': params[key] = params[key].split('|')[0] # Validate values. for key in params: param_type = self.get_scanner_param_type(key) if not param_type: continue if param_type in ['integer', 'boolean']: try: params[key] = int(params[key]) except ValueError: raise OSPDError('Invalid %s value' % key, 'start_scan') if param_type == 'boolean': if params[key] not in [0, 1]: raise OSPDError('Invalid %s value' % key, 'start_scan') elif param_type == 'selection': selection = self.get_scanner_param_default(key).split('|') if params[key] not in selection: raise OSPDError('Invalid %s value' % key, 'start_scan') if self.get_scanner_param_mandatory(key) and params[key] == '': raise OSPDError('Mandatory %s value is missing' % key, 'start_scan') return params
python
def _preprocess_scan_params(self, xml_params): """ Processes the scan parameters. """ params = {} for param in xml_params: params[param.tag] = param.text or '' # Set default values. for key in self.scanner_params: if key not in params: params[key] = self.get_scanner_param_default(key) if self.get_scanner_param_type(key) == 'selection': params[key] = params[key].split('|')[0] # Validate values. for key in params: param_type = self.get_scanner_param_type(key) if not param_type: continue if param_type in ['integer', 'boolean']: try: params[key] = int(params[key]) except ValueError: raise OSPDError('Invalid %s value' % key, 'start_scan') if param_type == 'boolean': if params[key] not in [0, 1]: raise OSPDError('Invalid %s value' % key, 'start_scan') elif param_type == 'selection': selection = self.get_scanner_param_default(key).split('|') if params[key] not in selection: raise OSPDError('Invalid %s value' % key, 'start_scan') if self.get_scanner_param_mandatory(key) and params[key] == '': raise OSPDError('Mandatory %s value is missing' % key, 'start_scan') return params
[ "def", "_preprocess_scan_params", "(", "self", ",", "xml_params", ")", ":", "params", "=", "{", "}", "for", "param", "in", "xml_params", ":", "params", "[", "param", ".", "tag", "]", "=", "param", ".", "text", "or", "''", "# Set default values.", "for", "key", "in", "self", ".", "scanner_params", ":", "if", "key", "not", "in", "params", ":", "params", "[", "key", "]", "=", "self", ".", "get_scanner_param_default", "(", "key", ")", "if", "self", ".", "get_scanner_param_type", "(", "key", ")", "==", "'selection'", ":", "params", "[", "key", "]", "=", "params", "[", "key", "]", ".", "split", "(", "'|'", ")", "[", "0", "]", "# Validate values.", "for", "key", "in", "params", ":", "param_type", "=", "self", ".", "get_scanner_param_type", "(", "key", ")", "if", "not", "param_type", ":", "continue", "if", "param_type", "in", "[", "'integer'", ",", "'boolean'", "]", ":", "try", ":", "params", "[", "key", "]", "=", "int", "(", "params", "[", "key", "]", ")", "except", "ValueError", ":", "raise", "OSPDError", "(", "'Invalid %s value'", "%", "key", ",", "'start_scan'", ")", "if", "param_type", "==", "'boolean'", ":", "if", "params", "[", "key", "]", "not", "in", "[", "0", ",", "1", "]", ":", "raise", "OSPDError", "(", "'Invalid %s value'", "%", "key", ",", "'start_scan'", ")", "elif", "param_type", "==", "'selection'", ":", "selection", "=", "self", ".", "get_scanner_param_default", "(", "key", ")", ".", "split", "(", "'|'", ")", "if", "params", "[", "key", "]", "not", "in", "selection", ":", "raise", "OSPDError", "(", "'Invalid %s value'", "%", "key", ",", "'start_scan'", ")", "if", "self", ".", "get_scanner_param_mandatory", "(", "key", ")", "and", "params", "[", "key", "]", "==", "''", ":", "raise", "OSPDError", "(", "'Mandatory %s value is missing'", "%", "key", ",", "'start_scan'", ")", "return", "params" ]
Processes the scan parameters.
[ "Processes", "the", "scan", "parameters", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L363-L394
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_vts_params
def process_vts_params(self, scanner_vts): """ Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: <vt_selection> <vt_single id='vt1' /> <vt_single id='vt2'> <vt_value id='param1'>value</vt_value> </vt_single> <vt_group filter='family=debian'/> <vt_group filter='family=general'/> </vt_selection> @return: Dictionary containing the vts attribute and subelements, like the VT's id and VT's parameters. Example form: {'vt1': {}, 'vt2': {'value_id': 'value'}, 'vt_groups': ['family=debian', 'family=general']} """ vt_selection = {} filters = list() for vt in scanner_vts: if vt.tag == 'vt_single': vt_id = vt.attrib.get('id') vt_selection[vt_id] = {} for vt_value in vt: if not vt_value.attrib.get('id'): raise OSPDError('Invalid VT preference. No attribute id', 'start_scan') vt_value_id = vt_value.attrib.get('id') vt_value_value = vt_value.text if vt_value.text else '' vt_selection[vt_id][vt_value_id] = vt_value_value if vt.tag == 'vt_group': vts_filter = vt.attrib.get('filter', None) if vts_filter is None: raise OSPDError('Invalid VT group. No filter given.', 'start_scan') filters.append(vts_filter) vt_selection['vt_groups'] = filters return vt_selection
python
def process_vts_params(self, scanner_vts): """ Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: <vt_selection> <vt_single id='vt1' /> <vt_single id='vt2'> <vt_value id='param1'>value</vt_value> </vt_single> <vt_group filter='family=debian'/> <vt_group filter='family=general'/> </vt_selection> @return: Dictionary containing the vts attribute and subelements, like the VT's id and VT's parameters. Example form: {'vt1': {}, 'vt2': {'value_id': 'value'}, 'vt_groups': ['family=debian', 'family=general']} """ vt_selection = {} filters = list() for vt in scanner_vts: if vt.tag == 'vt_single': vt_id = vt.attrib.get('id') vt_selection[vt_id] = {} for vt_value in vt: if not vt_value.attrib.get('id'): raise OSPDError('Invalid VT preference. No attribute id', 'start_scan') vt_value_id = vt_value.attrib.get('id') vt_value_value = vt_value.text if vt_value.text else '' vt_selection[vt_id][vt_value_id] = vt_value_value if vt.tag == 'vt_group': vts_filter = vt.attrib.get('filter', None) if vts_filter is None: raise OSPDError('Invalid VT group. No filter given.', 'start_scan') filters.append(vts_filter) vt_selection['vt_groups'] = filters return vt_selection
[ "def", "process_vts_params", "(", "self", ",", "scanner_vts", ")", ":", "vt_selection", "=", "{", "}", "filters", "=", "list", "(", ")", "for", "vt", "in", "scanner_vts", ":", "if", "vt", ".", "tag", "==", "'vt_single'", ":", "vt_id", "=", "vt", ".", "attrib", ".", "get", "(", "'id'", ")", "vt_selection", "[", "vt_id", "]", "=", "{", "}", "for", "vt_value", "in", "vt", ":", "if", "not", "vt_value", ".", "attrib", ".", "get", "(", "'id'", ")", ":", "raise", "OSPDError", "(", "'Invalid VT preference. No attribute id'", ",", "'start_scan'", ")", "vt_value_id", "=", "vt_value", ".", "attrib", ".", "get", "(", "'id'", ")", "vt_value_value", "=", "vt_value", ".", "text", "if", "vt_value", ".", "text", "else", "''", "vt_selection", "[", "vt_id", "]", "[", "vt_value_id", "]", "=", "vt_value_value", "if", "vt", ".", "tag", "==", "'vt_group'", ":", "vts_filter", "=", "vt", ".", "attrib", ".", "get", "(", "'filter'", ",", "None", ")", "if", "vts_filter", "is", "None", ":", "raise", "OSPDError", "(", "'Invalid VT group. No filter given.'", ",", "'start_scan'", ")", "filters", ".", "append", "(", "vts_filter", ")", "vt_selection", "[", "'vt_groups'", "]", "=", "filters", "return", "vt_selection" ]
Receive an XML object with the Vulnerability Tests an their parameters to be use in a scan and return a dictionary. @param: XML element with vt subelements. Each vt has an id attribute. Optional parameters can be included as vt child. Example form: <vt_selection> <vt_single id='vt1' /> <vt_single id='vt2'> <vt_value id='param1'>value</vt_value> </vt_single> <vt_group filter='family=debian'/> <vt_group filter='family=general'/> </vt_selection> @return: Dictionary containing the vts attribute and subelements, like the VT's id and VT's parameters. Example form: {'vt1': {}, 'vt2': {'value_id': 'value'}, 'vt_groups': ['family=debian', 'family=general']}
[ "Receive", "an", "XML", "object", "with", "the", "Vulnerability", "Tests", "an", "their", "parameters", "to", "be", "use", "in", "a", "scan", "and", "return", "a", "dictionary", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L401-L445
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_credentials_elements
def process_credentials_elements(cred_tree): """ Receive an XML object with the credentials to run a scan against a given target. @param: <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> @return: Dictionary containing the credentials for a given target. Example form: {'ssh': {'type': type, 'port': port, 'username': username, 'password': pass, }, 'smb': {'type': type, 'username': username, 'password': pass, }, } """ credentials = {} for credential in cred_tree: service = credential.attrib.get('service') credentials[service] = {} credentials[service]['type'] = credential.attrib.get('type') if service == 'ssh': credentials[service]['port'] = credential.attrib.get('port') for param in credential: credentials[service][param.tag] = param.text return credentials
python
def process_credentials_elements(cred_tree): """ Receive an XML object with the credentials to run a scan against a given target. @param: <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> @return: Dictionary containing the credentials for a given target. Example form: {'ssh': {'type': type, 'port': port, 'username': username, 'password': pass, }, 'smb': {'type': type, 'username': username, 'password': pass, }, } """ credentials = {} for credential in cred_tree: service = credential.attrib.get('service') credentials[service] = {} credentials[service]['type'] = credential.attrib.get('type') if service == 'ssh': credentials[service]['port'] = credential.attrib.get('port') for param in credential: credentials[service][param.tag] = param.text return credentials
[ "def", "process_credentials_elements", "(", "cred_tree", ")", ":", "credentials", "=", "{", "}", "for", "credential", "in", "cred_tree", ":", "service", "=", "credential", ".", "attrib", ".", "get", "(", "'service'", ")", "credentials", "[", "service", "]", "=", "{", "}", "credentials", "[", "service", "]", "[", "'type'", "]", "=", "credential", ".", "attrib", ".", "get", "(", "'type'", ")", "if", "service", "==", "'ssh'", ":", "credentials", "[", "service", "]", "[", "'port'", "]", "=", "credential", ".", "attrib", ".", "get", "(", "'port'", ")", "for", "param", "in", "credential", ":", "credentials", "[", "service", "]", "[", "param", ".", "tag", "]", "=", "param", ".", "text", "return", "credentials" ]
Receive an XML object with the credentials to run a scan against a given target. @param: <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> @return: Dictionary containing the credentials for a given target. Example form: {'ssh': {'type': type, 'port': port, 'username': username, 'password': pass, }, 'smb': {'type': type, 'username': username, 'password': pass, }, }
[ "Receive", "an", "XML", "object", "with", "the", "credentials", "to", "run", "a", "scan", "against", "a", "given", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L448-L487
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.process_targets_element
def process_targets_element(cls, scanner_target): """ Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a comma-separated host list or a network address. <ports> and <credentials> are optional. Therefore each ospd-scanner should check for a valid ones if needed. Example form: <targets> <target> <hosts>localhosts</hosts> <ports>80,443</ports> </target> <target> <hosts>192.168.0.0/24</hosts> <ports>22</ports> <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> </target> </targets> @return: A list of (hosts, port) tuples. Example form: [['localhost', '80,43'], ['192.168.0.0/24', '22', {'smb': {'type': type, 'port': port, 'username': username, 'password': pass, }}]] """ target_list = [] for target in scanner_target: ports = '' credentials = {} for child in target: if child.tag == 'hosts': hosts = child.text if child.tag == 'ports': ports = child.text if child.tag == 'credentials': credentials = cls.process_credentials_elements(child) if hosts: target_list.append([hosts, ports, credentials]) else: raise OSPDError('No target to scan', 'start_scan') return target_list
python
def process_targets_element(cls, scanner_target): """ Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a comma-separated host list or a network address. <ports> and <credentials> are optional. Therefore each ospd-scanner should check for a valid ones if needed. Example form: <targets> <target> <hosts>localhosts</hosts> <ports>80,443</ports> </target> <target> <hosts>192.168.0.0/24</hosts> <ports>22</ports> <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> </target> </targets> @return: A list of (hosts, port) tuples. Example form: [['localhost', '80,43'], ['192.168.0.0/24', '22', {'smb': {'type': type, 'port': port, 'username': username, 'password': pass, }}]] """ target_list = [] for target in scanner_target: ports = '' credentials = {} for child in target: if child.tag == 'hosts': hosts = child.text if child.tag == 'ports': ports = child.text if child.tag == 'credentials': credentials = cls.process_credentials_elements(child) if hosts: target_list.append([hosts, ports, credentials]) else: raise OSPDError('No target to scan', 'start_scan') return target_list
[ "def", "process_targets_element", "(", "cls", ",", "scanner_target", ")", ":", "target_list", "=", "[", "]", "for", "target", "in", "scanner_target", ":", "ports", "=", "''", "credentials", "=", "{", "}", "for", "child", "in", "target", ":", "if", "child", ".", "tag", "==", "'hosts'", ":", "hosts", "=", "child", ".", "text", "if", "child", ".", "tag", "==", "'ports'", ":", "ports", "=", "child", ".", "text", "if", "child", ".", "tag", "==", "'credentials'", ":", "credentials", "=", "cls", ".", "process_credentials_elements", "(", "child", ")", "if", "hosts", ":", "target_list", ".", "append", "(", "[", "hosts", ",", "ports", ",", "credentials", "]", ")", "else", ":", "raise", "OSPDError", "(", "'No target to scan'", ",", "'start_scan'", ")", "return", "target_list" ]
Receive an XML object with the target, ports and credentials to run a scan against. @param: XML element with target subelements. Each target has <hosts> and <ports> subelements. Hosts can be a single host, a host range, a comma-separated host list or a network address. <ports> and <credentials> are optional. Therefore each ospd-scanner should check for a valid ones if needed. Example form: <targets> <target> <hosts>localhosts</hosts> <ports>80,443</ports> </target> <target> <hosts>192.168.0.0/24</hosts> <ports>22</ports> <credentials> <credential type="up" service="ssh" port="22"> <username>scanuser</username> <password>mypass</password> </credential> <credential type="up" service="smb"> <username>smbuser</username> <password>mypass</password> </credential> </credentials> </target> </targets> @return: A list of (hosts, port) tuples. Example form: [['localhost', '80,43'], ['192.168.0.0/24', '22', {'smb': {'type': type, 'port': port, 'username': username, 'password': pass, }}]]
[ "Receive", "an", "XML", "object", "with", "the", "target", "ports", "and", "credentials", "to", "run", "a", "scan", "against", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L490-L548
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.finish_scan
def finish_scan(self, scan_id): """ Sets a scan as finished. """ self.set_scan_progress(scan_id, 100) self.set_scan_status(scan_id, ScanStatus.FINISHED) logger.info("%s: Scan finished.", scan_id)
python
def finish_scan(self, scan_id): """ Sets a scan as finished. """ self.set_scan_progress(scan_id, 100) self.set_scan_status(scan_id, ScanStatus.FINISHED) logger.info("%s: Scan finished.", scan_id)
[ "def", "finish_scan", "(", "self", ",", "scan_id", ")", ":", "self", ".", "set_scan_progress", "(", "scan_id", ",", "100", ")", "self", ".", "set_scan_status", "(", "scan_id", ",", "ScanStatus", ".", "FINISHED", ")", "logger", ".", "info", "(", "\"%s: Scan finished.\"", ",", "scan_id", ")" ]
Sets a scan as finished.
[ "Sets", "a", "scan", "as", "finished", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L661-L665
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_type
def get_scanner_param_type(self, param): """ Returns type of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('type')
python
def get_scanner_param_type(self, param): """ Returns type of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('type')
[ "def", "get_scanner_param_type", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "None", "return", "entry", ".", "get", "(", "'type'", ")" ]
Returns type of a scanner parameter.
[ "Returns", "type", "of", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L675-L681
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_mandatory
def get_scanner_param_mandatory(self, param): """ Returns if a scanner parameter is mandatory. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get('mandatory')
python
def get_scanner_param_mandatory(self, param): """ Returns if a scanner parameter is mandatory. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return False return entry.get('mandatory')
[ "def", "get_scanner_param_mandatory", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "False", "return", "entry", ".", "get", "(", "'mandatory'", ")" ]
Returns if a scanner parameter is mandatory.
[ "Returns", "if", "a", "scanner", "parameter", "is", "mandatory", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L683-L689
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_param_default
def get_scanner_param_default(self, param): """ Returns default value of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('default')
python
def get_scanner_param_default(self, param): """ Returns default value of a scanner parameter. """ assert isinstance(param, str) entry = self.scanner_params.get(param) if not entry: return None return entry.get('default')
[ "def", "get_scanner_param_default", "(", "self", ",", "param", ")", ":", "assert", "isinstance", "(", "param", ",", "str", ")", "entry", "=", "self", ".", "scanner_params", ".", "get", "(", "param", ")", "if", "not", "entry", ":", "return", "None", "return", "entry", ".", "get", "(", "'default'", ")" ]
Returns default value of a scanner parameter.
[ "Returns", "default", "value", "of", "a", "scanner", "parameter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L691-L697
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scanner_params_xml
def get_scanner_params_xml(self): """ Returns the OSP Daemon's scanner params in xml format. """ scanner_params = Element('scanner_params') for param_id, param in self.scanner_params.items(): param_xml = SubElement(scanner_params, 'scanner_param') for name, value in [('id', param_id), ('type', param['type'])]: param_xml.set(name, value) for name, value in [('name', param['name']), ('description', param['description']), ('default', param['default']), ('mandatory', param['mandatory'])]: elem = SubElement(param_xml, name) elem.text = str(value) return scanner_params
python
def get_scanner_params_xml(self): """ Returns the OSP Daemon's scanner params in xml format. """ scanner_params = Element('scanner_params') for param_id, param in self.scanner_params.items(): param_xml = SubElement(scanner_params, 'scanner_param') for name, value in [('id', param_id), ('type', param['type'])]: param_xml.set(name, value) for name, value in [('name', param['name']), ('description', param['description']), ('default', param['default']), ('mandatory', param['mandatory'])]: elem = SubElement(param_xml, name) elem.text = str(value) return scanner_params
[ "def", "get_scanner_params_xml", "(", "self", ")", ":", "scanner_params", "=", "Element", "(", "'scanner_params'", ")", "for", "param_id", ",", "param", "in", "self", ".", "scanner_params", ".", "items", "(", ")", ":", "param_xml", "=", "SubElement", "(", "scanner_params", ",", "'scanner_param'", ")", "for", "name", ",", "value", "in", "[", "(", "'id'", ",", "param_id", ")", ",", "(", "'type'", ",", "param", "[", "'type'", "]", ")", "]", ":", "param_xml", ".", "set", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "[", "(", "'name'", ",", "param", "[", "'name'", "]", ")", ",", "(", "'description'", ",", "param", "[", "'description'", "]", ")", ",", "(", "'default'", ",", "param", "[", "'default'", "]", ")", ",", "(", "'mandatory'", ",", "param", "[", "'mandatory'", "]", ")", "]", ":", "elem", "=", "SubElement", "(", "param_xml", ",", "name", ")", "elem", ".", "text", "=", "str", "(", "value", ")", "return", "scanner_params" ]
Returns the OSP Daemon's scanner params in xml format.
[ "Returns", "the", "OSP", "Daemon", "s", "scanner", "params", "in", "xml", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L699-L713
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.new_client_stream
def new_client_stream(self, sock): """ Returns a new ssl client stream from bind_socket. """ assert sock newsocket, fromaddr = sock.accept() logger.debug("New connection from" " %s:%s", fromaddr[0], fromaddr[1]) # NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest # protocol version that both the client and server support. In modern # Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3 # being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for # PROTOCOL_TLS which should be used once compatibility with Python 3.4 # is no longer desired. try: ssl_socket = ssl.wrap_socket(newsocket, cert_reqs=ssl.CERT_REQUIRED, server_side=True, certfile=self.certs['cert_file'], keyfile=self.certs['key_file'], ca_certs=self.certs['ca_file'], ssl_version=ssl.PROTOCOL_SSLv23) except (ssl.SSLError, socket.error) as message: logger.error(message) return None return ssl_socket
python
def new_client_stream(self, sock): """ Returns a new ssl client stream from bind_socket. """ assert sock newsocket, fromaddr = sock.accept() logger.debug("New connection from" " %s:%s", fromaddr[0], fromaddr[1]) # NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest # protocol version that both the client and server support. In modern # Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3 # being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for # PROTOCOL_TLS which should be used once compatibility with Python 3.4 # is no longer desired. try: ssl_socket = ssl.wrap_socket(newsocket, cert_reqs=ssl.CERT_REQUIRED, server_side=True, certfile=self.certs['cert_file'], keyfile=self.certs['key_file'], ca_certs=self.certs['ca_file'], ssl_version=ssl.PROTOCOL_SSLv23) except (ssl.SSLError, socket.error) as message: logger.error(message) return None return ssl_socket
[ "def", "new_client_stream", "(", "self", ",", "sock", ")", ":", "assert", "sock", "newsocket", ",", "fromaddr", "=", "sock", ".", "accept", "(", ")", "logger", ".", "debug", "(", "\"New connection from\"", "\" %s:%s\"", ",", "fromaddr", "[", "0", "]", ",", "fromaddr", "[", "1", "]", ")", "# NB: Despite the name, ssl.PROTOCOL_SSLv23 selects the highest", "# protocol version that both the client and server support. In modern", "# Python versions (>= 3.4) it supports TLS >= 1.0 with SSLv2 and SSLv3", "# being disabled. For Python >=3.5, PROTOCOL_SSLv23 is an alias for", "# PROTOCOL_TLS which should be used once compatibility with Python 3.4", "# is no longer desired.", "try", ":", "ssl_socket", "=", "ssl", ".", "wrap_socket", "(", "newsocket", ",", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", ",", "server_side", "=", "True", ",", "certfile", "=", "self", ".", "certs", "[", "'cert_file'", "]", ",", "keyfile", "=", "self", ".", "certs", "[", "'key_file'", "]", ",", "ca_certs", "=", "self", ".", "certs", "[", "'ca_file'", "]", ",", "ssl_version", "=", "ssl", ".", "PROTOCOL_SSLv23", ")", "except", "(", "ssl", ".", "SSLError", ",", "socket", ".", "error", ")", "as", "message", ":", "logger", ".", "error", "(", "message", ")", "return", "None", "return", "ssl_socket" ]
Returns a new ssl client stream from bind_socket.
[ "Returns", "a", "new", "ssl", "client", "stream", "from", "bind_socket", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L715-L738
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.write_to_stream
def write_to_stream(stream, response, block_len=1024): """ Send the response in blocks of the given len using the passed method dependending on the socket type. """ try: i_start = 0 i_end = block_len while True: if i_end > len(response): stream(response[i_start:]) break stream(response[i_start:i_end]) i_start = i_end i_end += block_len except (socket.timeout, socket.error) as exception: logger.debug('Error sending response to the client: %s', exception)
python
def write_to_stream(stream, response, block_len=1024): """ Send the response in blocks of the given len using the passed method dependending on the socket type. """ try: i_start = 0 i_end = block_len while True: if i_end > len(response): stream(response[i_start:]) break stream(response[i_start:i_end]) i_start = i_end i_end += block_len except (socket.timeout, socket.error) as exception: logger.debug('Error sending response to the client: %s', exception)
[ "def", "write_to_stream", "(", "stream", ",", "response", ",", "block_len", "=", "1024", ")", ":", "try", ":", "i_start", "=", "0", "i_end", "=", "block_len", "while", "True", ":", "if", "i_end", ">", "len", "(", "response", ")", ":", "stream", "(", "response", "[", "i_start", ":", "]", ")", "break", "stream", "(", "response", "[", "i_start", ":", "i_end", "]", ")", "i_start", "=", "i_end", "i_end", "+=", "block_len", "except", "(", "socket", ".", "timeout", ",", "socket", ".", "error", ")", "as", "exception", ":", "logger", ".", "debug", "(", "'Error sending response to the client: %s'", ",", "exception", ")" ]
Send the response in blocks of the given len using the passed method dependending on the socket type.
[ "Send", "the", "response", "in", "blocks", "of", "the", "given", "len", "using", "the", "passed", "method", "dependending", "on", "the", "socket", "type", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L741-L757
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_client_stream
def handle_client_stream(self, stream, is_unix=False): """ Handles stream of data received from client. """ assert stream data = [] stream.settimeout(2) while True: try: if is_unix: buf = stream.recv(1024) else: buf = stream.read(1024) if not buf: break data.append(buf) except (AttributeError, ValueError) as message: logger.error(message) return except (ssl.SSLError) as exception: logger.debug('Error: %s', exception[0]) break except (socket.timeout) as exception: logger.debug('Error: %s', exception) break data = b''.join(data) if len(data) <= 0: logger.debug("Empty client stream") return try: response = self.handle_command(data) except OSPDError as exception: response = exception.as_xml() logger.debug('Command error: %s', exception.message) except Exception: logger.exception('While handling client command:') exception = OSPDError('Fatal error', 'error') response = exception.as_xml() if is_unix: send_method = stream.send else: send_method = stream.write self.write_to_stream(send_method, response)
python
def handle_client_stream(self, stream, is_unix=False): """ Handles stream of data received from client. """ assert stream data = [] stream.settimeout(2) while True: try: if is_unix: buf = stream.recv(1024) else: buf = stream.read(1024) if not buf: break data.append(buf) except (AttributeError, ValueError) as message: logger.error(message) return except (ssl.SSLError) as exception: logger.debug('Error: %s', exception[0]) break except (socket.timeout) as exception: logger.debug('Error: %s', exception) break data = b''.join(data) if len(data) <= 0: logger.debug("Empty client stream") return try: response = self.handle_command(data) except OSPDError as exception: response = exception.as_xml() logger.debug('Command error: %s', exception.message) except Exception: logger.exception('While handling client command:') exception = OSPDError('Fatal error', 'error') response = exception.as_xml() if is_unix: send_method = stream.send else: send_method = stream.write self.write_to_stream(send_method, response)
[ "def", "handle_client_stream", "(", "self", ",", "stream", ",", "is_unix", "=", "False", ")", ":", "assert", "stream", "data", "=", "[", "]", "stream", ".", "settimeout", "(", "2", ")", "while", "True", ":", "try", ":", "if", "is_unix", ":", "buf", "=", "stream", ".", "recv", "(", "1024", ")", "else", ":", "buf", "=", "stream", ".", "read", "(", "1024", ")", "if", "not", "buf", ":", "break", "data", ".", "append", "(", "buf", ")", "except", "(", "AttributeError", ",", "ValueError", ")", "as", "message", ":", "logger", ".", "error", "(", "message", ")", "return", "except", "(", "ssl", ".", "SSLError", ")", "as", "exception", ":", "logger", ".", "debug", "(", "'Error: %s'", ",", "exception", "[", "0", "]", ")", "break", "except", "(", "socket", ".", "timeout", ")", "as", "exception", ":", "logger", ".", "debug", "(", "'Error: %s'", ",", "exception", ")", "break", "data", "=", "b''", ".", "join", "(", "data", ")", "if", "len", "(", "data", ")", "<=", "0", ":", "logger", ".", "debug", "(", "\"Empty client stream\"", ")", "return", "try", ":", "response", "=", "self", ".", "handle_command", "(", "data", ")", "except", "OSPDError", "as", "exception", ":", "response", "=", "exception", ".", "as_xml", "(", ")", "logger", ".", "debug", "(", "'Command error: %s'", ",", "exception", ".", "message", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "'While handling client command:'", ")", "exception", "=", "OSPDError", "(", "'Fatal error'", ",", "'error'", ")", "response", "=", "exception", ".", "as_xml", "(", ")", "if", "is_unix", ":", "send_method", "=", "stream", ".", "send", "else", ":", "send_method", "=", "stream", ".", "write", "self", ".", "write_to_stream", "(", "send_method", ",", "response", ")" ]
Handles stream of data received from client.
[ "Handles", "stream", "of", "data", "received", "from", "client", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L759-L800
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.parallel_scan
def parallel_scan(self, scan_id, target): """ Starts the scan with scan_id. """ try: ret = self.exec_scan(scan_id, target) if ret == 0: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='0') elif ret == 1: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='1') elif ret == 2: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='2') else: logger.debug('%s: No host status returned', target) except Exception as e: self.add_scan_error(scan_id, name='', host=target, value='Host process failure (%s).' % e) logger.exception('While scanning %s:', target) else: logger.info("%s: Host scan finished.", target)
python
def parallel_scan(self, scan_id, target): """ Starts the scan with scan_id. """ try: ret = self.exec_scan(scan_id, target) if ret == 0: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='0') elif ret == 1: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='1') elif ret == 2: self.add_scan_host_detail(scan_id, name='host_status', host=target, value='2') else: logger.debug('%s: No host status returned', target) except Exception as e: self.add_scan_error(scan_id, name='', host=target, value='Host process failure (%s).' % e) logger.exception('While scanning %s:', target) else: logger.info("%s: Host scan finished.", target)
[ "def", "parallel_scan", "(", "self", ",", "scan_id", ",", "target", ")", ":", "try", ":", "ret", "=", "self", ".", "exec_scan", "(", "scan_id", ",", "target", ")", "if", "ret", "==", "0", ":", "self", ".", "add_scan_host_detail", "(", "scan_id", ",", "name", "=", "'host_status'", ",", "host", "=", "target", ",", "value", "=", "'0'", ")", "elif", "ret", "==", "1", ":", "self", ".", "add_scan_host_detail", "(", "scan_id", ",", "name", "=", "'host_status'", ",", "host", "=", "target", ",", "value", "=", "'1'", ")", "elif", "ret", "==", "2", ":", "self", ".", "add_scan_host_detail", "(", "scan_id", ",", "name", "=", "'host_status'", ",", "host", "=", "target", ",", "value", "=", "'2'", ")", "else", ":", "logger", ".", "debug", "(", "'%s: No host status returned'", ",", "target", ")", "except", "Exception", "as", "e", ":", "self", ".", "add_scan_error", "(", "scan_id", ",", "name", "=", "''", ",", "host", "=", "target", ",", "value", "=", "'Host process failure (%s).'", "%", "e", ")", "logger", ".", "exception", "(", "'While scanning %s:'", ",", "target", ")", "else", ":", "logger", ".", "info", "(", "\"%s: Host scan finished.\"", ",", "target", ")" ]
Starts the scan with scan_id.
[ "Starts", "the", "scan", "with", "scan_id", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L802-L822
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.calculate_progress
def calculate_progress(self, scan_id): """ Calculate the total scan progress from the partial target progress. """ t_prog = dict() for target in self.get_scan_target(scan_id): t_prog[target] = self.get_scan_target_progress(scan_id, target) return sum(t_prog.values())/len(t_prog)
python
def calculate_progress(self, scan_id): """ Calculate the total scan progress from the partial target progress. """ t_prog = dict() for target in self.get_scan_target(scan_id): t_prog[target] = self.get_scan_target_progress(scan_id, target) return sum(t_prog.values())/len(t_prog)
[ "def", "calculate_progress", "(", "self", ",", "scan_id", ")", ":", "t_prog", "=", "dict", "(", ")", "for", "target", "in", "self", ".", "get_scan_target", "(", "scan_id", ")", ":", "t_prog", "[", "target", "]", "=", "self", ".", "get_scan_target_progress", "(", "scan_id", ",", "target", ")", "return", "sum", "(", "t_prog", ".", "values", "(", ")", ")", "/", "len", "(", "t_prog", ")" ]
Calculate the total scan progress from the partial target progress.
[ "Calculate", "the", "total", "scan", "progress", "from", "the", "partial", "target", "progress", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L848-L855
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.start_scan
def start_scan(self, scan_id, targets, parallel=1): """ Handle N parallel scans if 'parallel' is greater than 1. """ os.setsid() multiscan_proc = [] logger.info("%s: Scan started.", scan_id) target_list = targets if target_list is None or not target_list: raise OSPDError('Erroneous targets list', 'start_scan') for index, target in enumerate(target_list): while len(multiscan_proc) >= parallel: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) time.sleep(1) #If the scan status is stopped, does not launch anymore target scans if self.get_scan_status(scan_id) == ScanStatus.STOPPED: return logger.info("%s: Host scan started on ports %s.", target[0], target[1]) scan_process = multiprocessing.Process(target=self.parallel_scan, args=(scan_id, target[0])) multiscan_proc.append((scan_process, target[0])) scan_process.start() self.set_scan_status(scan_id, ScanStatus.RUNNING) # Wait until all single target were scanned while multiscan_proc: multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) if multiscan_proc: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) time.sleep(1) # Only set the scan as finished if the scan was not stopped. if self.get_scan_status(scan_id) != ScanStatus.STOPPED: self.finish_scan(scan_id)
python
def start_scan(self, scan_id, targets, parallel=1): """ Handle N parallel scans if 'parallel' is greater than 1. """ os.setsid() multiscan_proc = [] logger.info("%s: Scan started.", scan_id) target_list = targets if target_list is None or not target_list: raise OSPDError('Erroneous targets list', 'start_scan') for index, target in enumerate(target_list): while len(multiscan_proc) >= parallel: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) time.sleep(1) #If the scan status is stopped, does not launch anymore target scans if self.get_scan_status(scan_id) == ScanStatus.STOPPED: return logger.info("%s: Host scan started on ports %s.", target[0], target[1]) scan_process = multiprocessing.Process(target=self.parallel_scan, args=(scan_id, target[0])) multiscan_proc.append((scan_process, target[0])) scan_process.start() self.set_scan_status(scan_id, ScanStatus.RUNNING) # Wait until all single target were scanned while multiscan_proc: multiscan_proc = self.check_pending_target(scan_id, multiscan_proc) if multiscan_proc: progress = self.calculate_progress(scan_id) self.set_scan_progress(scan_id, progress) time.sleep(1) # Only set the scan as finished if the scan was not stopped. if self.get_scan_status(scan_id) != ScanStatus.STOPPED: self.finish_scan(scan_id)
[ "def", "start_scan", "(", "self", ",", "scan_id", ",", "targets", ",", "parallel", "=", "1", ")", ":", "os", ".", "setsid", "(", ")", "multiscan_proc", "=", "[", "]", "logger", ".", "info", "(", "\"%s: Scan started.\"", ",", "scan_id", ")", "target_list", "=", "targets", "if", "target_list", "is", "None", "or", "not", "target_list", ":", "raise", "OSPDError", "(", "'Erroneous targets list'", ",", "'start_scan'", ")", "for", "index", ",", "target", "in", "enumerate", "(", "target_list", ")", ":", "while", "len", "(", "multiscan_proc", ")", ">=", "parallel", ":", "progress", "=", "self", ".", "calculate_progress", "(", "scan_id", ")", "self", ".", "set_scan_progress", "(", "scan_id", ",", "progress", ")", "multiscan_proc", "=", "self", ".", "check_pending_target", "(", "scan_id", ",", "multiscan_proc", ")", "time", ".", "sleep", "(", "1", ")", "#If the scan status is stopped, does not launch anymore target scans", "if", "self", ".", "get_scan_status", "(", "scan_id", ")", "==", "ScanStatus", ".", "STOPPED", ":", "return", "logger", ".", "info", "(", "\"%s: Host scan started on ports %s.\"", ",", "target", "[", "0", "]", ",", "target", "[", "1", "]", ")", "scan_process", "=", "multiprocessing", ".", "Process", "(", "target", "=", "self", ".", "parallel_scan", ",", "args", "=", "(", "scan_id", ",", "target", "[", "0", "]", ")", ")", "multiscan_proc", ".", "append", "(", "(", "scan_process", ",", "target", "[", "0", "]", ")", ")", "scan_process", ".", "start", "(", ")", "self", ".", "set_scan_status", "(", "scan_id", ",", "ScanStatus", ".", "RUNNING", ")", "# Wait until all single target were scanned", "while", "multiscan_proc", ":", "multiscan_proc", "=", "self", ".", "check_pending_target", "(", "scan_id", ",", "multiscan_proc", ")", "if", "multiscan_proc", ":", "progress", "=", "self", ".", "calculate_progress", "(", "scan_id", ")", "self", ".", "set_scan_progress", "(", "scan_id", ",", "progress", ")", "time", ".", "sleep", "(", "1", ")", "# Only set the scan as finished if the scan was not stopped.", "if", "self", ".", "get_scan_status", "(", "scan_id", ")", "!=", "ScanStatus", ".", "STOPPED", ":", "self", ".", "finish_scan", "(", "scan_id", ")" ]
Handle N parallel scans if 'parallel' is greater than 1.
[ "Handle", "N", "parallel", "scans", "if", "parallel", "is", "greater", "than", "1", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L857-L896
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.dry_run_scan
def dry_run_scan(self, scan_id, targets): """ Dry runs a scan. """ os.setsid() for _, target in enumerate(targets): host = resolve_hostname(target[0]) if host is None: logger.info("Couldn't resolve %s.", target[0]) continue port = self.get_scan_ports(scan_id, target=target[0]) logger.info("%s:%s: Dry run mode.", host, port) self.add_scan_log(scan_id, name='', host=host, value='Dry run result') self.finish_scan(scan_id)
python
def dry_run_scan(self, scan_id, targets): """ Dry runs a scan. """ os.setsid() for _, target in enumerate(targets): host = resolve_hostname(target[0]) if host is None: logger.info("Couldn't resolve %s.", target[0]) continue port = self.get_scan_ports(scan_id, target=target[0]) logger.info("%s:%s: Dry run mode.", host, port) self.add_scan_log(scan_id, name='', host=host, value='Dry run result') self.finish_scan(scan_id)
[ "def", "dry_run_scan", "(", "self", ",", "scan_id", ",", "targets", ")", ":", "os", ".", "setsid", "(", ")", "for", "_", ",", "target", "in", "enumerate", "(", "targets", ")", ":", "host", "=", "resolve_hostname", "(", "target", "[", "0", "]", ")", "if", "host", "is", "None", ":", "logger", ".", "info", "(", "\"Couldn't resolve %s.\"", ",", "target", "[", "0", "]", ")", "continue", "port", "=", "self", ".", "get_scan_ports", "(", "scan_id", ",", "target", "=", "target", "[", "0", "]", ")", "logger", ".", "info", "(", "\"%s:%s: Dry run mode.\"", ",", "host", ",", "port", ")", "self", ".", "add_scan_log", "(", "scan_id", ",", "name", "=", "''", ",", "host", "=", "host", ",", "value", "=", "'Dry run result'", ")", "self", ".", "finish_scan", "(", "scan_id", ")" ]
Dry runs a scan.
[ "Dry", "runs", "a", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L898-L911
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_timeout
def handle_timeout(self, scan_id, host): """ Handles scanner reaching timeout error. """ self.add_scan_error(scan_id, host=host, name="Timeout", value="{0} exec timeout." .format(self.get_scanner_name()))
python
def handle_timeout(self, scan_id, host): """ Handles scanner reaching timeout error. """ self.add_scan_error(scan_id, host=host, name="Timeout", value="{0} exec timeout." .format(self.get_scanner_name()))
[ "def", "handle_timeout", "(", "self", ",", "scan_id", ",", "host", ")", ":", "self", ".", "add_scan_error", "(", "scan_id", ",", "host", "=", "host", ",", "name", "=", "\"Timeout\"", ",", "value", "=", "\"{0} exec timeout.\"", ".", "format", "(", "self", ".", "get_scanner_name", "(", ")", ")", ")" ]
Handles scanner reaching timeout error.
[ "Handles", "scanner", "reaching", "timeout", "error", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L913-L917
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_scan_target_progress
def set_scan_target_progress( self, scan_id, target, host, progress): """ Sets host's progress which is part of target. """ self.scan_collection.set_target_progress( scan_id, target, host, progress)
python
def set_scan_target_progress( self, scan_id, target, host, progress): """ Sets host's progress which is part of target. """ self.scan_collection.set_target_progress( scan_id, target, host, progress)
[ "def", "set_scan_target_progress", "(", "self", ",", "scan_id", ",", "target", ",", "host", ",", "progress", ")", ":", "self", ".", "scan_collection", ".", "set_target_progress", "(", "scan_id", ",", "target", ",", "host", ",", "progress", ")" ]
Sets host's progress which is part of target.
[ "Sets", "host", "s", "progress", "which", "is", "part", "of", "target", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L928-L932
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_help_text
def get_help_text(self): """ Returns the help output in plain text format.""" txt = str('\n') for name, info in self.commands.items(): command_txt = "\t{0: <22} {1}\n".format(name, info['description']) if info['attributes']: command_txt = ''.join([command_txt, "\t Attributes:\n"]) for attrname, attrdesc in info['attributes'].items(): attr_txt = "\t {0: <22} {1}\n".format(attrname, attrdesc) command_txt = ''.join([command_txt, attr_txt]) if info['elements']: command_txt = ''.join([command_txt, "\t Elements:\n", self.elements_as_text(info['elements'])]) txt = ''.join([txt, command_txt]) return txt
python
def get_help_text(self): """ Returns the help output in plain text format.""" txt = str('\n') for name, info in self.commands.items(): command_txt = "\t{0: <22} {1}\n".format(name, info['description']) if info['attributes']: command_txt = ''.join([command_txt, "\t Attributes:\n"]) for attrname, attrdesc in info['attributes'].items(): attr_txt = "\t {0: <22} {1}\n".format(attrname, attrdesc) command_txt = ''.join([command_txt, attr_txt]) if info['elements']: command_txt = ''.join([command_txt, "\t Elements:\n", self.elements_as_text(info['elements'])]) txt = ''.join([txt, command_txt]) return txt
[ "def", "get_help_text", "(", "self", ")", ":", "txt", "=", "str", "(", "'\\n'", ")", "for", "name", ",", "info", "in", "self", ".", "commands", ".", "items", "(", ")", ":", "command_txt", "=", "\"\\t{0: <22} {1}\\n\"", ".", "format", "(", "name", ",", "info", "[", "'description'", "]", ")", "if", "info", "[", "'attributes'", "]", ":", "command_txt", "=", "''", ".", "join", "(", "[", "command_txt", ",", "\"\\t Attributes:\\n\"", "]", ")", "for", "attrname", ",", "attrdesc", "in", "info", "[", "'attributes'", "]", ".", "items", "(", ")", ":", "attr_txt", "=", "\"\\t {0: <22} {1}\\n\"", ".", "format", "(", "attrname", ",", "attrdesc", ")", "command_txt", "=", "''", ".", "join", "(", "[", "command_txt", ",", "attr_txt", "]", ")", "if", "info", "[", "'elements'", "]", ":", "command_txt", "=", "''", ".", "join", "(", "[", "command_txt", ",", "\"\\t Elements:\\n\"", ",", "self", ".", "elements_as_text", "(", "info", "[", "'elements'", "]", ")", "]", ")", "txt", "=", "''", ".", "join", "(", "[", "txt", ",", "command_txt", "]", ")", "return", "txt" ]
Returns the help output in plain text format.
[ "Returns", "the", "help", "output", "in", "plain", "text", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1023-L1038
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.elements_as_text
def elements_as_text(self, elems, indent=2): """ Returns the elems dictionary as formatted plain text. """ assert elems text = "" for elename, eledesc in elems.items(): if isinstance(eledesc, dict): desc_txt = self.elements_as_text(eledesc, indent + 2) desc_txt = ''.join(['\n', desc_txt]) elif isinstance(eledesc, str): desc_txt = ''.join([eledesc, '\n']) else: assert False, "Only string or dictionary" ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename, desc_txt) text = ''.join([text, ele_txt]) return text
python
def elements_as_text(self, elems, indent=2): """ Returns the elems dictionary as formatted plain text. """ assert elems text = "" for elename, eledesc in elems.items(): if isinstance(eledesc, dict): desc_txt = self.elements_as_text(eledesc, indent + 2) desc_txt = ''.join(['\n', desc_txt]) elif isinstance(eledesc, str): desc_txt = ''.join([eledesc, '\n']) else: assert False, "Only string or dictionary" ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename, desc_txt) text = ''.join([text, ele_txt]) return text
[ "def", "elements_as_text", "(", "self", ",", "elems", ",", "indent", "=", "2", ")", ":", "assert", "elems", "text", "=", "\"\"", "for", "elename", ",", "eledesc", "in", "elems", ".", "items", "(", ")", ":", "if", "isinstance", "(", "eledesc", ",", "dict", ")", ":", "desc_txt", "=", "self", ".", "elements_as_text", "(", "eledesc", ",", "indent", "+", "2", ")", "desc_txt", "=", "''", ".", "join", "(", "[", "'\\n'", ",", "desc_txt", "]", ")", "elif", "isinstance", "(", "eledesc", ",", "str", ")", ":", "desc_txt", "=", "''", ".", "join", "(", "[", "eledesc", ",", "'\\n'", "]", ")", "else", ":", "assert", "False", ",", "\"Only string or dictionary\"", "ele_txt", "=", "\"\\t{0}{1: <22} {2}\"", ".", "format", "(", "' '", "*", "indent", ",", "elename", ",", "desc_txt", ")", "text", "=", "''", ".", "join", "(", "[", "text", ",", "ele_txt", "]", ")", "return", "text" ]
Returns the elems dictionary as formatted plain text.
[ "Returns", "the", "elems", "dictionary", "as", "formatted", "plain", "text", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1040-L1055
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.delete_scan
def delete_scan(self, scan_id): """ Deletes scan_id scan from collection. @return: 1 if scan deleted, 0 otherwise. """ if self.get_scan_status(scan_id) == ScanStatus.RUNNING: return 0 try: del self.scan_processes[scan_id] except KeyError: logger.debug('Scan process for %s not found', scan_id) return self.scan_collection.delete_scan(scan_id)
python
def delete_scan(self, scan_id): """ Deletes scan_id scan from collection. @return: 1 if scan deleted, 0 otherwise. """ if self.get_scan_status(scan_id) == ScanStatus.RUNNING: return 0 try: del self.scan_processes[scan_id] except KeyError: logger.debug('Scan process for %s not found', scan_id) return self.scan_collection.delete_scan(scan_id)
[ "def", "delete_scan", "(", "self", ",", "scan_id", ")", ":", "if", "self", ".", "get_scan_status", "(", "scan_id", ")", "==", "ScanStatus", ".", "RUNNING", ":", "return", "0", "try", ":", "del", "self", ".", "scan_processes", "[", "scan_id", "]", "except", "KeyError", ":", "logger", ".", "debug", "(", "'Scan process for %s not found'", ",", "scan_id", ")", "return", "self", ".", "scan_collection", ".", "delete_scan", "(", "scan_id", ")" ]
Deletes scan_id scan from collection. @return: 1 if scan deleted, 0 otherwise.
[ "Deletes", "scan_id", "scan", "from", "collection", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1075-L1087
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scan_results_xml
def get_scan_results_xml(self, scan_id, pop_res): """ Gets scan_id scan's results in XML format. @return: String of scan results in xml. """ results = Element('results') for result in self.scan_collection.results_iterator(scan_id, pop_res): results.append(get_result_xml(result)) logger.info('Returning %d results', len(results)) return results
python
def get_scan_results_xml(self, scan_id, pop_res): """ Gets scan_id scan's results in XML format. @return: String of scan results in xml. """ results = Element('results') for result in self.scan_collection.results_iterator(scan_id, pop_res): results.append(get_result_xml(result)) logger.info('Returning %d results', len(results)) return results
[ "def", "get_scan_results_xml", "(", "self", ",", "scan_id", ",", "pop_res", ")", ":", "results", "=", "Element", "(", "'results'", ")", "for", "result", "in", "self", ".", "scan_collection", ".", "results_iterator", "(", "scan_id", ",", "pop_res", ")", ":", "results", ".", "append", "(", "get_result_xml", "(", "result", ")", ")", "logger", ".", "info", "(", "'Returning %d results'", ",", "len", "(", "results", ")", ")", "return", "results" ]
Gets scan_id scan's results in XML format. @return: String of scan results in xml.
[ "Gets", "scan_id", "scan", "s", "results", "in", "XML", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1089-L1099
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_xml_str
def get_xml_str(self, data): """ Creates a string in XML Format using the provided data structure. @param: Dictionary of xml tags and their elements. @return: String of data in xml format. """ responses = [] for tag, value in data.items(): elem = Element(tag) if isinstance(value, dict): for value in self.get_xml_str(value): elem.append(value) elif isinstance(value, list): value = ', '.join([m for m in value]) elem.text = value else: elem.text = value responses.append(elem) return responses
python
def get_xml_str(self, data): """ Creates a string in XML Format using the provided data structure. @param: Dictionary of xml tags and their elements. @return: String of data in xml format. """ responses = [] for tag, value in data.items(): elem = Element(tag) if isinstance(value, dict): for value in self.get_xml_str(value): elem.append(value) elif isinstance(value, list): value = ', '.join([m for m in value]) elem.text = value else: elem.text = value responses.append(elem) return responses
[ "def", "get_xml_str", "(", "self", ",", "data", ")", ":", "responses", "=", "[", "]", "for", "tag", ",", "value", "in", "data", ".", "items", "(", ")", ":", "elem", "=", "Element", "(", "tag", ")", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "for", "value", "in", "self", ".", "get_xml_str", "(", "value", ")", ":", "elem", ".", "append", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", ":", "value", "=", "', '", ".", "join", "(", "[", "m", "for", "m", "in", "value", "]", ")", "elem", ".", "text", "=", "value", "else", ":", "elem", ".", "text", "=", "value", "responses", ".", "append", "(", "elem", ")", "return", "responses" ]
Creates a string in XML Format using the provided data structure. @param: Dictionary of xml tags and their elements. @return: String of data in xml format.
[ "Creates", "a", "string", "in", "XML", "Format", "using", "the", "provided", "data", "structure", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1101-L1121
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_scan_xml
def get_scan_xml(self, scan_id, detailed=True, pop_res=False): """ Gets scan in XML format. @return: String of scan in XML format. """ if not scan_id: return Element('scan') target = ','.join(self.get_scan_target(scan_id)) progress = self.get_scan_progress(scan_id) status = self.get_scan_status(scan_id) start_time = self.get_scan_start_time(scan_id) end_time = self.get_scan_end_time(scan_id) response = Element('scan') for name, value in [('id', scan_id), ('target', target), ('progress', progress), ('status', status.name.lower()), ('start_time', start_time), ('end_time', end_time)]: response.set(name, str(value)) if detailed: response.append(self.get_scan_results_xml(scan_id, pop_res)) return response
python
def get_scan_xml(self, scan_id, detailed=True, pop_res=False): """ Gets scan in XML format. @return: String of scan in XML format. """ if not scan_id: return Element('scan') target = ','.join(self.get_scan_target(scan_id)) progress = self.get_scan_progress(scan_id) status = self.get_scan_status(scan_id) start_time = self.get_scan_start_time(scan_id) end_time = self.get_scan_end_time(scan_id) response = Element('scan') for name, value in [('id', scan_id), ('target', target), ('progress', progress), ('status', status.name.lower()), ('start_time', start_time), ('end_time', end_time)]: response.set(name, str(value)) if detailed: response.append(self.get_scan_results_xml(scan_id, pop_res)) return response
[ "def", "get_scan_xml", "(", "self", ",", "scan_id", ",", "detailed", "=", "True", ",", "pop_res", "=", "False", ")", ":", "if", "not", "scan_id", ":", "return", "Element", "(", "'scan'", ")", "target", "=", "','", ".", "join", "(", "self", ".", "get_scan_target", "(", "scan_id", ")", ")", "progress", "=", "self", ".", "get_scan_progress", "(", "scan_id", ")", "status", "=", "self", ".", "get_scan_status", "(", "scan_id", ")", "start_time", "=", "self", ".", "get_scan_start_time", "(", "scan_id", ")", "end_time", "=", "self", ".", "get_scan_end_time", "(", "scan_id", ")", "response", "=", "Element", "(", "'scan'", ")", "for", "name", ",", "value", "in", "[", "(", "'id'", ",", "scan_id", ")", ",", "(", "'target'", ",", "target", ")", ",", "(", "'progress'", ",", "progress", ")", ",", "(", "'status'", ",", "status", ".", "name", ".", "lower", "(", ")", ")", ",", "(", "'start_time'", ",", "start_time", ")", ",", "(", "'end_time'", ",", "end_time", ")", "]", ":", "response", ".", "set", "(", "name", ",", "str", "(", "value", ")", ")", "if", "detailed", ":", "response", ".", "append", "(", "self", ".", "get_scan_results_xml", "(", "scan_id", ",", "pop_res", ")", ")", "return", "response" ]
Gets scan in XML format. @return: String of scan in XML format.
[ "Gets", "scan", "in", "XML", "format", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1123-L1146
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.get_vts_xml
def get_vts_xml(self, vt_id=None, filtered_vts=None): """ Gets collection of vulnerability test information in XML format. If vt_id is specified, the collection will contain only this vt, if found. If no vt_id is specified, the collection will contain all vts or those passed in filtered_vts. Arguments: vt_id (vt_id, optional): ID of the vt to get. filtered_vts (dict, optional): Filtered VTs collection. Return: String of collection of vulnerability test information in XML format. """ vts_xml = Element('vts') if vt_id: vts_xml.append(self.get_vt_xml(vt_id)) elif filtered_vts: for vt_id in filtered_vts: vts_xml.append(self.get_vt_xml(vt_id)) else: for vt_id in self.vts: vts_xml.append(self.get_vt_xml(vt_id)) return vts_xml
python
def get_vts_xml(self, vt_id=None, filtered_vts=None): """ Gets collection of vulnerability test information in XML format. If vt_id is specified, the collection will contain only this vt, if found. If no vt_id is specified, the collection will contain all vts or those passed in filtered_vts. Arguments: vt_id (vt_id, optional): ID of the vt to get. filtered_vts (dict, optional): Filtered VTs collection. Return: String of collection of vulnerability test information in XML format. """ vts_xml = Element('vts') if vt_id: vts_xml.append(self.get_vt_xml(vt_id)) elif filtered_vts: for vt_id in filtered_vts: vts_xml.append(self.get_vt_xml(vt_id)) else: for vt_id in self.vts: vts_xml.append(self.get_vt_xml(vt_id)) return vts_xml
[ "def", "get_vts_xml", "(", "self", ",", "vt_id", "=", "None", ",", "filtered_vts", "=", "None", ")", ":", "vts_xml", "=", "Element", "(", "'vts'", ")", "if", "vt_id", ":", "vts_xml", ".", "append", "(", "self", ".", "get_vt_xml", "(", "vt_id", ")", ")", "elif", "filtered_vts", ":", "for", "vt_id", "in", "filtered_vts", ":", "vts_xml", ".", "append", "(", "self", ".", "get_vt_xml", "(", "vt_id", ")", ")", "else", ":", "for", "vt_id", "in", "self", ".", "vts", ":", "vts_xml", ".", "append", "(", "self", ".", "get_vt_xml", "(", "vt_id", ")", ")", "return", "vts_xml" ]
Gets collection of vulnerability test information in XML format. If vt_id is specified, the collection will contain only this vt, if found. If no vt_id is specified, the collection will contain all vts or those passed in filtered_vts. Arguments: vt_id (vt_id, optional): ID of the vt to get. filtered_vts (dict, optional): Filtered VTs collection. Return: String of collection of vulnerability test information in XML format.
[ "Gets", "collection", "of", "vulnerability", "test", "information", "in", "XML", "format", ".", "If", "vt_id", "is", "specified", "the", "collection", "will", "contain", "only", "this", "vt", "if", "found", ".", "If", "no", "vt_id", "is", "specified", "the", "collection", "will", "contain", "all", "vts", "or", "those", "passed", "in", "filtered_vts", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1415-L1442
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.handle_command
def handle_command(self, command): """ Handles an osp command in a string. @return: OSP Response to command. """ try: tree = secET.fromstring(command) except secET.ParseError: logger.debug("Erroneous client input: %s", command) raise OSPDError('Invalid data') if not self.command_exists(tree.tag) and tree.tag != "authenticate": raise OSPDError('Bogus command name') if tree.tag == "get_version": return self.handle_get_version_command() elif tree.tag == "start_scan": return self.handle_start_scan_command(tree) elif tree.tag == "stop_scan": return self.handle_stop_scan_command(tree) elif tree.tag == "get_scans": return self.handle_get_scans_command(tree) elif tree.tag == "get_vts": return self.handle_get_vts_command(tree) elif tree.tag == "delete_scan": return self.handle_delete_scan_command(tree) elif tree.tag == "help": return self.handle_help_command(tree) elif tree.tag == "get_scanner_details": return self.handle_get_scanner_details() else: assert False, "Unhandled command: {0}".format(tree.tag)
python
def handle_command(self, command): """ Handles an osp command in a string. @return: OSP Response to command. """ try: tree = secET.fromstring(command) except secET.ParseError: logger.debug("Erroneous client input: %s", command) raise OSPDError('Invalid data') if not self.command_exists(tree.tag) and tree.tag != "authenticate": raise OSPDError('Bogus command name') if tree.tag == "get_version": return self.handle_get_version_command() elif tree.tag == "start_scan": return self.handle_start_scan_command(tree) elif tree.tag == "stop_scan": return self.handle_stop_scan_command(tree) elif tree.tag == "get_scans": return self.handle_get_scans_command(tree) elif tree.tag == "get_vts": return self.handle_get_vts_command(tree) elif tree.tag == "delete_scan": return self.handle_delete_scan_command(tree) elif tree.tag == "help": return self.handle_help_command(tree) elif tree.tag == "get_scanner_details": return self.handle_get_scanner_details() else: assert False, "Unhandled command: {0}".format(tree.tag)
[ "def", "handle_command", "(", "self", ",", "command", ")", ":", "try", ":", "tree", "=", "secET", ".", "fromstring", "(", "command", ")", "except", "secET", ".", "ParseError", ":", "logger", ".", "debug", "(", "\"Erroneous client input: %s\"", ",", "command", ")", "raise", "OSPDError", "(", "'Invalid data'", ")", "if", "not", "self", ".", "command_exists", "(", "tree", ".", "tag", ")", "and", "tree", ".", "tag", "!=", "\"authenticate\"", ":", "raise", "OSPDError", "(", "'Bogus command name'", ")", "if", "tree", ".", "tag", "==", "\"get_version\"", ":", "return", "self", ".", "handle_get_version_command", "(", ")", "elif", "tree", ".", "tag", "==", "\"start_scan\"", ":", "return", "self", ".", "handle_start_scan_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"stop_scan\"", ":", "return", "self", ".", "handle_stop_scan_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"get_scans\"", ":", "return", "self", ".", "handle_get_scans_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"get_vts\"", ":", "return", "self", ".", "handle_get_vts_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"delete_scan\"", ":", "return", "self", ".", "handle_delete_scan_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"help\"", ":", "return", "self", ".", "handle_help_command", "(", "tree", ")", "elif", "tree", ".", "tag", "==", "\"get_scanner_details\"", ":", "return", "self", ".", "handle_get_scanner_details", "(", ")", "else", ":", "assert", "False", ",", "\"Unhandled command: {0}\"", ".", "format", "(", "tree", ".", "tag", ")" ]
Handles an osp command in a string. @return: OSP Response to command.
[ "Handles", "an", "osp", "command", "in", "a", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1487-L1518
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.run
def run(self, address, port, unix_path): """ Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise. """ assert address or unix_path if unix_path: sock = bind_unix_socket(unix_path) else: sock = bind_socket(address, port) if sock is None: return False sock.setblocking(False) inputs = [sock] outputs = [] try: while True: readable, _, _ = select.select( inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD) for r_socket in readable: if unix_path and r_socket is sock: client_stream, _ = sock.accept() logger.debug("New connection from %s", unix_path) self.handle_client_stream(client_stream, True) else: client_stream = self.new_client_stream(sock) if client_stream is None: continue self.handle_client_stream(client_stream, False) close_client_stream(client_stream, unix_path) self.scheduler() except KeyboardInterrupt: logger.info("Received Ctrl-C shutting-down ...") finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
python
def run(self, address, port, unix_path): """ Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise. """ assert address or unix_path if unix_path: sock = bind_unix_socket(unix_path) else: sock = bind_socket(address, port) if sock is None: return False sock.setblocking(False) inputs = [sock] outputs = [] try: while True: readable, _, _ = select.select( inputs, outputs, inputs, SCHEDULER_CHECK_PERIOD) for r_socket in readable: if unix_path and r_socket is sock: client_stream, _ = sock.accept() logger.debug("New connection from %s", unix_path) self.handle_client_stream(client_stream, True) else: client_stream = self.new_client_stream(sock) if client_stream is None: continue self.handle_client_stream(client_stream, False) close_client_stream(client_stream, unix_path) self.scheduler() except KeyboardInterrupt: logger.info("Received Ctrl-C shutting-down ...") finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
[ "def", "run", "(", "self", ",", "address", ",", "port", ",", "unix_path", ")", ":", "assert", "address", "or", "unix_path", "if", "unix_path", ":", "sock", "=", "bind_unix_socket", "(", "unix_path", ")", "else", ":", "sock", "=", "bind_socket", "(", "address", ",", "port", ")", "if", "sock", "is", "None", ":", "return", "False", "sock", ".", "setblocking", "(", "False", ")", "inputs", "=", "[", "sock", "]", "outputs", "=", "[", "]", "try", ":", "while", "True", ":", "readable", ",", "_", ",", "_", "=", "select", ".", "select", "(", "inputs", ",", "outputs", ",", "inputs", ",", "SCHEDULER_CHECK_PERIOD", ")", "for", "r_socket", "in", "readable", ":", "if", "unix_path", "and", "r_socket", "is", "sock", ":", "client_stream", ",", "_", "=", "sock", ".", "accept", "(", ")", "logger", ".", "debug", "(", "\"New connection from %s\"", ",", "unix_path", ")", "self", ".", "handle_client_stream", "(", "client_stream", ",", "True", ")", "else", ":", "client_stream", "=", "self", ".", "new_client_stream", "(", "sock", ")", "if", "client_stream", "is", "None", ":", "continue", "self", ".", "handle_client_stream", "(", "client_stream", ",", "False", ")", "close_client_stream", "(", "client_stream", ",", "unix_path", ")", "self", ".", "scheduler", "(", ")", "except", "KeyboardInterrupt", ":", "logger", ".", "info", "(", "\"Received Ctrl-C shutting-down ...\"", ")", "finally", ":", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "sock", ".", "close", "(", ")" ]
Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise.
[ "Starts", "the", "Daemon", "handling", "commands", "until", "interrupted", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1524-L1560
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.create_scan
def create_scan(self, scan_id, targets, options, vts): """ Creates a new scan. @target: Target to scan. @options: Miscellaneous scan options. @return: New scan's ID. """ if self.scan_exists(scan_id): logger.info("Scan %s exists. Resuming scan.", scan_id) return self.scan_collection.create_scan(scan_id, targets, options, vts)
python
def create_scan(self, scan_id, targets, options, vts): """ Creates a new scan. @target: Target to scan. @options: Miscellaneous scan options. @return: New scan's ID. """ if self.scan_exists(scan_id): logger.info("Scan %s exists. Resuming scan.", scan_id) return self.scan_collection.create_scan(scan_id, targets, options, vts)
[ "def", "create_scan", "(", "self", ",", "scan_id", ",", "targets", ",", "options", ",", "vts", ")", ":", "if", "self", ".", "scan_exists", "(", "scan_id", ")", ":", "logger", ".", "info", "(", "\"Scan %s exists. Resuming scan.\"", ",", "scan_id", ")", "return", "self", ".", "scan_collection", ".", "create_scan", "(", "scan_id", ",", "targets", ",", "options", ",", "vts", ")" ]
Creates a new scan. @target: Target to scan. @options: Miscellaneous scan options. @return: New scan's ID.
[ "Creates", "a", "new", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1566-L1577
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.set_scan_option
def set_scan_option(self, scan_id, name, value): """ Sets a scan's option to a provided value. """ return self.scan_collection.set_option(scan_id, name, value)
python
def set_scan_option(self, scan_id, name, value): """ Sets a scan's option to a provided value. """ return self.scan_collection.set_option(scan_id, name, value)
[ "def", "set_scan_option", "(", "self", ",", "scan_id", ",", "name", ",", "value", ")", ":", "return", "self", ".", "scan_collection", ".", "set_option", "(", "scan_id", ",", "name", ",", "value", ")" ]
Sets a scan's option to a provided value.
[ "Sets", "a", "scan", "s", "option", "to", "a", "provided", "value", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1583-L1585
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.check_scan_process
def check_scan_process(self, scan_id): """ Check the scan's process, and terminate the scan if not alive. """ scan_process = self.scan_processes[scan_id] progress = self.get_scan_progress(scan_id) if progress < 100 and not scan_process.is_alive(): self.set_scan_status(scan_id, ScanStatus.STOPPED) self.add_scan_error(scan_id, name="", host="", value="Scan process failure.") logger.info("%s: Scan stopped with errors.", scan_id) elif progress == 100: scan_process.join()
python
def check_scan_process(self, scan_id): """ Check the scan's process, and terminate the scan if not alive. """ scan_process = self.scan_processes[scan_id] progress = self.get_scan_progress(scan_id) if progress < 100 and not scan_process.is_alive(): self.set_scan_status(scan_id, ScanStatus.STOPPED) self.add_scan_error(scan_id, name="", host="", value="Scan process failure.") logger.info("%s: Scan stopped with errors.", scan_id) elif progress == 100: scan_process.join()
[ "def", "check_scan_process", "(", "self", ",", "scan_id", ")", ":", "scan_process", "=", "self", ".", "scan_processes", "[", "scan_id", "]", "progress", "=", "self", ".", "get_scan_progress", "(", "scan_id", ")", "if", "progress", "<", "100", "and", "not", "scan_process", ".", "is_alive", "(", ")", ":", "self", ".", "set_scan_status", "(", "scan_id", ",", "ScanStatus", ".", "STOPPED", ")", "self", ".", "add_scan_error", "(", "scan_id", ",", "name", "=", "\"\"", ",", "host", "=", "\"\"", ",", "value", "=", "\"Scan process failure.\"", ")", "logger", ".", "info", "(", "\"%s: Scan stopped with errors.\"", ",", "scan_id", ")", "elif", "progress", "==", "100", ":", "scan_process", ".", "join", "(", ")" ]
Check the scan's process, and terminate the scan if not alive.
[ "Check", "the", "scan", "s", "process", "and", "terminate", "the", "scan", "if", "not", "alive", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1587-L1597
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_log
def add_scan_log(self, scan_id, host='', name='', value='', port='', test_id='', qod=''): """ Adds a log result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.LOG, host, name, value, port, test_id, 0.0, qod)
python
def add_scan_log(self, scan_id, host='', name='', value='', port='', test_id='', qod=''): """ Adds a log result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.LOG, host, name, value, port, test_id, 0.0, qod)
[ "def", "add_scan_log", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "qod", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", ".", "LOG", ",", "host", ",", "name", ",", "value", ",", "port", ",", "test_id", ",", "0.0", ",", "qod", ")" ]
Adds a log result to scan_id scan.
[ "Adds", "a", "log", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1632-L1636
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_error
def add_scan_error(self, scan_id, host='', name='', value='', port=''): """ Adds an error result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name, value, port)
python
def add_scan_error(self, scan_id, host='', name='', value='', port=''): """ Adds an error result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name, value, port)
[ "def", "add_scan_error", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", ".", "ERROR", ",", "host", ",", "name", ",", "value", ",", "port", ")" ]
Adds an error result to scan_id scan.
[ "Adds", "an", "error", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1638-L1641
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_host_detail
def add_scan_host_detail(self, scan_id, host='', name='', value=''): """ Adds a host detail result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host, name, value)
python
def add_scan_host_detail(self, scan_id, host='', name='', value=''): """ Adds a host detail result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host, name, value)
[ "def", "add_scan_host_detail", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", ".", "HOST_DETAIL", ",", "host", ",", "name", ",", "value", ")" ]
Adds a host detail result to scan_id scan.
[ "Adds", "a", "host", "detail", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1643-L1646
train
greenbone/ospd
ospd/ospd.py
OSPDaemon.add_scan_alarm
def add_scan_alarm(self, scan_id, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Adds an alarm result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name, value, port, test_id, severity, qod)
python
def add_scan_alarm(self, scan_id, host='', name='', value='', port='', test_id='', severity='', qod=''): """ Adds an alarm result to scan_id scan. """ self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name, value, port, test_id, severity, qod)
[ "def", "add_scan_alarm", "(", "self", ",", "scan_id", ",", "host", "=", "''", ",", "name", "=", "''", ",", "value", "=", "''", ",", "port", "=", "''", ",", "test_id", "=", "''", ",", "severity", "=", "''", ",", "qod", "=", "''", ")", ":", "self", ".", "scan_collection", ".", "add_result", "(", "scan_id", ",", "ResultType", ".", "ALARM", ",", "host", ",", "name", ",", "value", ",", "port", ",", "test_id", ",", "severity", ",", "qod", ")" ]
Adds an alarm result to scan_id scan.
[ "Adds", "an", "alarm", "result", "to", "scan_id", "scan", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/ospd.py#L1648-L1652
train
greenbone/ospd
ospd/vtfilter.py
VtsFilter.parse_filters
def parse_filters(self, vt_filter): """ Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator, value] """ filter_list = vt_filter.split(';') filters = list() for single_filter in filter_list: filter_aux = re.split('(\W)', single_filter, 1) if len(filter_aux) < 3: raise OSPDError("Invalid number of argument in the filter", "get_vts") _element, _oper, _val = filter_aux if _element not in self.allowed_filter: raise OSPDError("Invalid filter element", "get_vts") if _oper not in self.filter_operator: raise OSPDError("Invalid filter operator", "get_vts") filters.append(filter_aux) return filters
python
def parse_filters(self, vt_filter): """ Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator, value] """ filter_list = vt_filter.split(';') filters = list() for single_filter in filter_list: filter_aux = re.split('(\W)', single_filter, 1) if len(filter_aux) < 3: raise OSPDError("Invalid number of argument in the filter", "get_vts") _element, _oper, _val = filter_aux if _element not in self.allowed_filter: raise OSPDError("Invalid filter element", "get_vts") if _oper not in self.filter_operator: raise OSPDError("Invalid filter operator", "get_vts") filters.append(filter_aux) return filters
[ "def", "parse_filters", "(", "self", ",", "vt_filter", ")", ":", "filter_list", "=", "vt_filter", ".", "split", "(", "';'", ")", "filters", "=", "list", "(", ")", "for", "single_filter", "in", "filter_list", ":", "filter_aux", "=", "re", ".", "split", "(", "'(\\W)'", ",", "single_filter", ",", "1", ")", "if", "len", "(", "filter_aux", ")", "<", "3", ":", "raise", "OSPDError", "(", "\"Invalid number of argument in the filter\"", ",", "\"get_vts\"", ")", "_element", ",", "_oper", ",", "_val", "=", "filter_aux", "if", "_element", "not", "in", "self", ".", "allowed_filter", ":", "raise", "OSPDError", "(", "\"Invalid filter element\"", ",", "\"get_vts\"", ")", "if", "_oper", "not", "in", "self", ".", "filter_operator", ":", "raise", "OSPDError", "(", "\"Invalid filter operator\"", ",", "\"get_vts\"", ")", "filters", ".", "append", "(", "filter_aux", ")", "return", "filters" ]
Parse a string containing one or more filters and return a list of filters Arguments: vt_filter (string): String containing filters separated with semicolon. Return: List with filters. Each filters is a list with 3 elements e.g. [arg, operator, value]
[ "Parse", "a", "string", "containing", "one", "or", "more", "filters", "and", "return", "a", "list", "of", "filters" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L41-L67
train
greenbone/ospd
ospd/vtfilter.py
VtsFilter.format_filter_value
def format_filter_value(self, element, value): """ Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value. """ format_func = self.allowed_filter.get(element) return format_func(value)
python
def format_filter_value(self, element, value): """ Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value. """ format_func = self.allowed_filter.get(element) return format_func(value)
[ "def", "format_filter_value", "(", "self", ",", "element", ",", "value", ")", ":", "format_func", "=", "self", ".", "allowed_filter", ".", "get", "(", "element", ")", "return", "format_func", "(", "value", ")" ]
Calls the specific function to format value, depending on the given element. Arguments: element (string): The element of the VT to be formatted. value (dictionary): The element value. Returns: Returns a formatted value.
[ "Calls", "the", "specific", "function", "to", "format", "value", "depending", "on", "the", "given", "element", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L81-L94
train
greenbone/ospd
ospd/vtfilter.py
VtsFilter.get_filtered_vts_list
def get_filtered_vts_list(self, vts, vt_filter): """ Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests. """ if not vt_filter: raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if not filters: return None _vts_aux = vts.copy() for _element, _oper, _filter_val in filters: for vt_id in _vts_aux.copy(): if not _vts_aux[vt_id].get(_element): _vts_aux.pop(vt_id) continue _elem_val = _vts_aux[vt_id].get(_element) _val = self.format_filter_value(_element, _elem_val) if self.filter_operator[_oper](_val, _filter_val): continue else: _vts_aux.pop(vt_id) return _vts_aux
python
def get_filtered_vts_list(self, vts, vt_filter): """ Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests. """ if not vt_filter: raise RequiredArgument('vt_filter: A valid filter is required.') filters = self.parse_filters(vt_filter) if not filters: return None _vts_aux = vts.copy() for _element, _oper, _filter_val in filters: for vt_id in _vts_aux.copy(): if not _vts_aux[vt_id].get(_element): _vts_aux.pop(vt_id) continue _elem_val = _vts_aux[vt_id].get(_element) _val = self.format_filter_value(_element, _elem_val) if self.filter_operator[_oper](_val, _filter_val): continue else: _vts_aux.pop(vt_id) return _vts_aux
[ "def", "get_filtered_vts_list", "(", "self", ",", "vts", ",", "vt_filter", ")", ":", "if", "not", "vt_filter", ":", "raise", "RequiredArgument", "(", "'vt_filter: A valid filter is required.'", ")", "filters", "=", "self", ".", "parse_filters", "(", "vt_filter", ")", "if", "not", "filters", ":", "return", "None", "_vts_aux", "=", "vts", ".", "copy", "(", ")", "for", "_element", ",", "_oper", ",", "_filter_val", "in", "filters", ":", "for", "vt_id", "in", "_vts_aux", ".", "copy", "(", ")", ":", "if", "not", "_vts_aux", "[", "vt_id", "]", ".", "get", "(", "_element", ")", ":", "_vts_aux", ".", "pop", "(", "vt_id", ")", "continue", "_elem_val", "=", "_vts_aux", "[", "vt_id", "]", ".", "get", "(", "_element", ")", "_val", "=", "self", ".", "format_filter_value", "(", "_element", ",", "_elem_val", ")", "if", "self", ".", "filter_operator", "[", "_oper", "]", "(", "_val", ",", "_filter_val", ")", ":", "continue", "else", ":", "_vts_aux", ".", "pop", "(", "vt_id", ")", "return", "_vts_aux" ]
Gets a collection of vulnerability test from the vts dictionary, which match the filter. Arguments: vt_filter (string): Filter to apply to the vts collection. vts (dictionary): The complete vts collection. Returns: Dictionary with filtered vulnerability tests.
[ "Gets", "a", "collection", "of", "vulnerability", "test", "from", "the", "vts", "dictionary", "which", "match", "the", "filter", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/vtfilter.py#L96-L127
train
greenbone/ospd
ospd/misc.py
inet_pton
def inet_pton(address_family, ip_string): """ A platform independent version of inet_pton """ global __inet_pton if __inet_pton is None: if hasattr(socket, 'inet_pton'): __inet_pton = socket.inet_pton else: from ospd import win_socket __inet_pton = win_socket.inet_pton return __inet_pton(address_family, ip_string)
python
def inet_pton(address_family, ip_string): """ A platform independent version of inet_pton """ global __inet_pton if __inet_pton is None: if hasattr(socket, 'inet_pton'): __inet_pton = socket.inet_pton else: from ospd import win_socket __inet_pton = win_socket.inet_pton return __inet_pton(address_family, ip_string)
[ "def", "inet_pton", "(", "address_family", ",", "ip_string", ")", ":", "global", "__inet_pton", "if", "__inet_pton", "is", "None", ":", "if", "hasattr", "(", "socket", ",", "'inet_pton'", ")", ":", "__inet_pton", "=", "socket", ".", "inet_pton", "else", ":", "from", "ospd", "import", "win_socket", "__inet_pton", "=", "win_socket", ".", "inet_pton", "return", "__inet_pton", "(", "address_family", ",", "ip_string", ")" ]
A platform independent version of inet_pton
[ "A", "platform", "independent", "version", "of", "inet_pton" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L365-L375
train
greenbone/ospd
ospd/misc.py
inet_ntop
def inet_ntop(address_family, packed_ip): """ A platform independent version of inet_ntop """ global __inet_ntop if __inet_ntop is None: if hasattr(socket, 'inet_ntop'): __inet_ntop = socket.inet_ntop else: from ospd import win_socket __inet_ntop = win_socket.inet_ntop return __inet_ntop(address_family, packed_ip)
python
def inet_ntop(address_family, packed_ip): """ A platform independent version of inet_ntop """ global __inet_ntop if __inet_ntop is None: if hasattr(socket, 'inet_ntop'): __inet_ntop = socket.inet_ntop else: from ospd import win_socket __inet_ntop = win_socket.inet_ntop return __inet_ntop(address_family, packed_ip)
[ "def", "inet_ntop", "(", "address_family", ",", "packed_ip", ")", ":", "global", "__inet_ntop", "if", "__inet_ntop", "is", "None", ":", "if", "hasattr", "(", "socket", ",", "'inet_ntop'", ")", ":", "__inet_ntop", "=", "socket", ".", "inet_ntop", "else", ":", "from", "ospd", "import", "win_socket", "__inet_ntop", "=", "win_socket", ".", "inet_ntop", "return", "__inet_ntop", "(", "address_family", ",", "packed_ip", ")" ]
A platform independent version of inet_ntop
[ "A", "platform", "independent", "version", "of", "inet_ntop" ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L381-L391
train
greenbone/ospd
ospd/misc.py
ipv4_range_to_list
def ipv4_range_to_list(start_packed, end_packed): """ Return a list of IPv4 entries from start_packed to end_packed. """ new_list = list() start = struct.unpack('!L', start_packed)[0] end = struct.unpack('!L', end_packed)[0] for value in range(start, end + 1): new_ip = socket.inet_ntoa(struct.pack('!L', value)) new_list.append(new_ip) return new_list
python
def ipv4_range_to_list(start_packed, end_packed): """ Return a list of IPv4 entries from start_packed to end_packed. """ new_list = list() start = struct.unpack('!L', start_packed)[0] end = struct.unpack('!L', end_packed)[0] for value in range(start, end + 1): new_ip = socket.inet_ntoa(struct.pack('!L', value)) new_list.append(new_ip) return new_list
[ "def", "ipv4_range_to_list", "(", "start_packed", ",", "end_packed", ")", ":", "new_list", "=", "list", "(", ")", "start", "=", "struct", ".", "unpack", "(", "'!L'", ",", "start_packed", ")", "[", "0", "]", "end", "=", "struct", ".", "unpack", "(", "'!L'", ",", "end_packed", ")", "[", "0", "]", "for", "value", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "new_ip", "=", "socket", ".", "inet_ntoa", "(", "struct", ".", "pack", "(", "'!L'", ",", "value", ")", ")", "new_list", ".", "append", "(", "new_ip", ")", "return", "new_list" ]
Return a list of IPv4 entries from start_packed to end_packed.
[ "Return", "a", "list", "of", "IPv4", "entries", "from", "start_packed", "to", "end_packed", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L414-L423
train
greenbone/ospd
ospd/misc.py
target_to_ipv4_short
def target_to_ipv4_short(target): """ Attempt to return a IPv4 short range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_value = int(splitted[1]) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(bytes(start_packed[3])), 16) if end_value < 0 or end_value > 255 or end_value < start_value: return None end_packed = start_packed[0:3] + struct.pack('B', end_value) return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_short(target): """ Attempt to return a IPv4 short range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_value = int(splitted[1]) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(bytes(start_packed[3])), 16) if end_value < 0 or end_value > 255 or end_value < start_value: return None end_packed = start_packed[0:3] + struct.pack('B', end_value) return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_short", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET", ",", "splitted", "[", "0", "]", ")", "end_value", "=", "int", "(", "splitted", "[", "1", "]", ")", "except", "(", "socket", ".", "error", ",", "ValueError", ")", ":", "return", "None", "start_value", "=", "int", "(", "binascii", ".", "hexlify", "(", "bytes", "(", "start_packed", "[", "3", "]", ")", ")", ",", "16", ")", "if", "end_value", "<", "0", "or", "end_value", ">", "255", "or", "end_value", "<", "start_value", ":", "return", "None", "end_packed", "=", "start_packed", "[", "0", ":", "3", "]", "+", "struct", ".", "pack", "(", "'B'", ",", "end_value", ")", "return", "ipv4_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv4 short range list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "short", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L426-L441
train
greenbone/ospd
ospd/misc.py
target_to_ipv4_cidr
def target_to_ipv4_cidr(target): """ Attempt to return a IPv4 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 30: return None start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block) start_value = (start_value << (32 - block)) + 1 end_value = (start_value | (0xffffffff >> block)) - 1 start_packed = struct.pack('!I', start_value) end_packed = struct.pack('!I', end_value) return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_cidr(target): """ Attempt to return a IPv4 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 30: return None start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block) start_value = (start_value << (32 - block)) + 1 end_value = (start_value | (0xffffffff >> block)) - 1 start_packed = struct.pack('!I', start_value) end_packed = struct.pack('!I', end_value) return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_cidr", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'/'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET", ",", "splitted", "[", "0", "]", ")", "block", "=", "int", "(", "splitted", "[", "1", "]", ")", "except", "(", "socket", ".", "error", ",", "ValueError", ")", ":", "return", "None", "if", "block", "<=", "0", "or", "block", ">", "30", ":", "return", "None", "start_value", "=", "int", "(", "binascii", ".", "hexlify", "(", "start_packed", ")", ",", "16", ")", ">>", "(", "32", "-", "block", ")", "start_value", "=", "(", "start_value", "<<", "(", "32", "-", "block", ")", ")", "+", "1", "end_value", "=", "(", "start_value", "|", "(", "0xffffffff", ">>", "block", ")", ")", "-", "1", "start_packed", "=", "struct", ".", "pack", "(", "'!I'", ",", "start_value", ")", "end_packed", "=", "struct", ".", "pack", "(", "'!I'", ",", "end_value", ")", "return", "ipv4_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv4 CIDR list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "CIDR", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L444-L462
train
greenbone/ospd
ospd/misc.py
target_to_ipv6_cidr
def target_to_ipv6_cidr(target): """ Attempt to return a IPv6 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 126: return None start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block) start_value = (start_value << (128 - block)) + 1 end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1 high = start_value >> 64 low = start_value & ((1 << 64) - 1) start_packed = struct.pack('!QQ', high, low) high = end_value >> 64 low = end_value & ((1 << 64) - 1) end_packed = struct.pack('!QQ', high, low) return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_cidr(target): """ Attempt to return a IPv6 CIDR list from a target string. """ splitted = target.split('/') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) block = int(splitted[1]) except (socket.error, ValueError): return None if block <= 0 or block > 126: return None start_value = int(binascii.hexlify(start_packed), 16) >> (128 - block) start_value = (start_value << (128 - block)) + 1 end_value = (start_value | (int('ff' * 16, 16) >> block)) - 1 high = start_value >> 64 low = start_value & ((1 << 64) - 1) start_packed = struct.pack('!QQ', high, low) high = end_value >> 64 low = end_value & ((1 << 64) - 1) end_packed = struct.pack('!QQ', high, low) return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_cidr", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'/'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "splitted", "[", "0", "]", ")", "block", "=", "int", "(", "splitted", "[", "1", "]", ")", "except", "(", "socket", ".", "error", ",", "ValueError", ")", ":", "return", "None", "if", "block", "<=", "0", "or", "block", ">", "126", ":", "return", "None", "start_value", "=", "int", "(", "binascii", ".", "hexlify", "(", "start_packed", ")", ",", "16", ")", ">>", "(", "128", "-", "block", ")", "start_value", "=", "(", "start_value", "<<", "(", "128", "-", "block", ")", ")", "+", "1", "end_value", "=", "(", "start_value", "|", "(", "int", "(", "'ff'", "*", "16", ",", "16", ")", ">>", "block", ")", ")", "-", "1", "high", "=", "start_value", ">>", "64", "low", "=", "start_value", "&", "(", "(", "1", "<<", "64", ")", "-", "1", ")", "start_packed", "=", "struct", ".", "pack", "(", "'!QQ'", ",", "high", ",", "low", ")", "high", "=", "end_value", ">>", "64", "low", "=", "end_value", "&", "(", "(", "1", "<<", "64", ")", "-", "1", ")", "end_packed", "=", "struct", ".", "pack", "(", "'!QQ'", ",", "high", ",", "low", ")", "return", "ipv6_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv6 CIDR list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "CIDR", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L465-L487
train
greenbone/ospd
ospd/misc.py
target_to_ipv4_long
def target_to_ipv4_long(target): """ Attempt to return a IPv4 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv4_range_to_list(start_packed, end_packed)
python
def target_to_ipv4_long(target): """ Attempt to return a IPv4 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET, splitted[0]) end_packed = inet_pton(socket.AF_INET, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv4_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv4_long", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET", ",", "splitted", "[", "0", "]", ")", "end_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET", ",", "splitted", "[", "1", "]", ")", "except", "socket", ".", "error", ":", "return", "None", "if", "end_packed", "<", "start_packed", ":", "return", "None", "return", "ipv4_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv4 long-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv4", "long", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L490-L503
train
greenbone/ospd
ospd/misc.py
ipv6_range_to_list
def ipv6_range_to_list(start_packed, end_packed): """ Return a list of IPv6 entries from start_packed to end_packed. """ new_list = list() start = int(binascii.hexlify(start_packed), 16) end = int(binascii.hexlify(end_packed), 16) for value in range(start, end + 1): high = value >> 64 low = value & ((1 << 64) - 1) new_ip = inet_ntop(socket.AF_INET6, struct.pack('!2Q', high, low)) new_list.append(new_ip) return new_list
python
def ipv6_range_to_list(start_packed, end_packed): """ Return a list of IPv6 entries from start_packed to end_packed. """ new_list = list() start = int(binascii.hexlify(start_packed), 16) end = int(binascii.hexlify(end_packed), 16) for value in range(start, end + 1): high = value >> 64 low = value & ((1 << 64) - 1) new_ip = inet_ntop(socket.AF_INET6, struct.pack('!2Q', high, low)) new_list.append(new_ip) return new_list
[ "def", "ipv6_range_to_list", "(", "start_packed", ",", "end_packed", ")", ":", "new_list", "=", "list", "(", ")", "start", "=", "int", "(", "binascii", ".", "hexlify", "(", "start_packed", ")", ",", "16", ")", "end", "=", "int", "(", "binascii", ".", "hexlify", "(", "end_packed", ")", ",", "16", ")", "for", "value", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "high", "=", "value", ">>", "64", "low", "=", "value", "&", "(", "(", "1", "<<", "64", ")", "-", "1", ")", "new_ip", "=", "inet_ntop", "(", "socket", ".", "AF_INET6", ",", "struct", ".", "pack", "(", "'!2Q'", ",", "high", ",", "low", ")", ")", "new_list", ".", "append", "(", "new_ip", ")", "return", "new_list" ]
Return a list of IPv6 entries from start_packed to end_packed.
[ "Return", "a", "list", "of", "IPv6", "entries", "from", "start_packed", "to", "end_packed", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L506-L518
train
greenbone/ospd
ospd/misc.py
target_to_ipv6_short
def target_to_ipv6_short(target): """ Attempt to return a IPv6 short-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(start_packed[14:]), 16) if end_value < 0 or end_value > 0xffff or end_value < start_value: return None end_packed = start_packed[:14] + struct.pack('!H', end_value) return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_short(target): """ Attempt to return a IPv6 short-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_value = int(splitted[1], 16) except (socket.error, ValueError): return None start_value = int(binascii.hexlify(start_packed[14:]), 16) if end_value < 0 or end_value > 0xffff or end_value < start_value: return None end_packed = start_packed[:14] + struct.pack('!H', end_value) return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_short", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "splitted", "[", "0", "]", ")", "end_value", "=", "int", "(", "splitted", "[", "1", "]", ",", "16", ")", "except", "(", "socket", ".", "error", ",", "ValueError", ")", ":", "return", "None", "start_value", "=", "int", "(", "binascii", ".", "hexlify", "(", "start_packed", "[", "14", ":", "]", ")", ",", "16", ")", "if", "end_value", "<", "0", "or", "end_value", ">", "0xffff", "or", "end_value", "<", "start_value", ":", "return", "None", "end_packed", "=", "start_packed", "[", ":", "14", "]", "+", "struct", ".", "pack", "(", "'!H'", ",", "end_value", ")", "return", "ipv6_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv6 short-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "short", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L521-L536
train
greenbone/ospd
ospd/misc.py
target_to_ipv6_long
def target_to_ipv6_long(target): """ Attempt to return a IPv6 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_packed = inet_pton(socket.AF_INET6, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv6_range_to_list(start_packed, end_packed)
python
def target_to_ipv6_long(target): """ Attempt to return a IPv6 long-range list from a target string. """ splitted = target.split('-') if len(splitted) != 2: return None try: start_packed = inet_pton(socket.AF_INET6, splitted[0]) end_packed = inet_pton(socket.AF_INET6, splitted[1]) except socket.error: return None if end_packed < start_packed: return None return ipv6_range_to_list(start_packed, end_packed)
[ "def", "target_to_ipv6_long", "(", "target", ")", ":", "splitted", "=", "target", ".", "split", "(", "'-'", ")", "if", "len", "(", "splitted", ")", "!=", "2", ":", "return", "None", "try", ":", "start_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "splitted", "[", "0", "]", ")", "end_packed", "=", "inet_pton", "(", "socket", ".", "AF_INET6", ",", "splitted", "[", "1", "]", ")", "except", "socket", ".", "error", ":", "return", "None", "if", "end_packed", "<", "start_packed", ":", "return", "None", "return", "ipv6_range_to_list", "(", "start_packed", ",", "end_packed", ")" ]
Attempt to return a IPv6 long-range list from a target string.
[ "Attempt", "to", "return", "a", "IPv6", "long", "-", "range", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L539-L552
train
greenbone/ospd
ospd/misc.py
target_to_hostname
def target_to_hostname(target): """ Attempt to return a single hostname list from a target string. """ if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
python
def target_to_hostname(target): """ Attempt to return a single hostname list from a target string. """ if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
[ "def", "target_to_hostname", "(", "target", ")", ":", "if", "len", "(", "target", ")", "==", "0", "or", "len", "(", "target", ")", ">", "255", ":", "return", "None", "if", "not", "re", ".", "match", "(", "r'^[\\w.-]+$'", ",", "target", ")", ":", "return", "None", "return", "[", "target", "]" ]
Attempt to return a single hostname list from a target string.
[ "Attempt", "to", "return", "a", "single", "hostname", "list", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L555-L562
train
greenbone/ospd
ospd/misc.py
target_to_list
def target_to_list(target): """ Attempt to return a list of single hosts from a target string. """ # Is it an IPv4 address ? new_list = target_to_ipv4(target) # Is it an IPv6 address ? if not new_list: new_list = target_to_ipv6(target) # Is it an IPv4 CIDR ? if not new_list: new_list = target_to_ipv4_cidr(target) # Is it an IPv6 CIDR ? if not new_list: new_list = target_to_ipv6_cidr(target) # Is it an IPv4 short-range ? if not new_list: new_list = target_to_ipv4_short(target) # Is it an IPv4 long-range ? if not new_list: new_list = target_to_ipv4_long(target) # Is it an IPv6 short-range ? if not new_list: new_list = target_to_ipv6_short(target) # Is it an IPv6 long-range ? if not new_list: new_list = target_to_ipv6_long(target) # Is it a hostname ? if not new_list: new_list = target_to_hostname(target) return new_list
python
def target_to_list(target): """ Attempt to return a list of single hosts from a target string. """ # Is it an IPv4 address ? new_list = target_to_ipv4(target) # Is it an IPv6 address ? if not new_list: new_list = target_to_ipv6(target) # Is it an IPv4 CIDR ? if not new_list: new_list = target_to_ipv4_cidr(target) # Is it an IPv6 CIDR ? if not new_list: new_list = target_to_ipv6_cidr(target) # Is it an IPv4 short-range ? if not new_list: new_list = target_to_ipv4_short(target) # Is it an IPv4 long-range ? if not new_list: new_list = target_to_ipv4_long(target) # Is it an IPv6 short-range ? if not new_list: new_list = target_to_ipv6_short(target) # Is it an IPv6 long-range ? if not new_list: new_list = target_to_ipv6_long(target) # Is it a hostname ? if not new_list: new_list = target_to_hostname(target) return new_list
[ "def", "target_to_list", "(", "target", ")", ":", "# Is it an IPv4 address ?", "new_list", "=", "target_to_ipv4", "(", "target", ")", "# Is it an IPv6 address ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv6", "(", "target", ")", "# Is it an IPv4 CIDR ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv4_cidr", "(", "target", ")", "# Is it an IPv6 CIDR ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv6_cidr", "(", "target", ")", "# Is it an IPv4 short-range ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv4_short", "(", "target", ")", "# Is it an IPv4 long-range ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv4_long", "(", "target", ")", "# Is it an IPv6 short-range ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv6_short", "(", "target", ")", "# Is it an IPv6 long-range ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_ipv6_long", "(", "target", ")", "# Is it a hostname ?", "if", "not", "new_list", ":", "new_list", "=", "target_to_hostname", "(", "target", ")", "return", "new_list" ]
Attempt to return a list of single hosts from a target string.
[ "Attempt", "to", "return", "a", "list", "of", "single", "hosts", "from", "a", "target", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L565-L594
train
greenbone/ospd
ospd/misc.py
target_str_to_list
def target_str_to_list(target_str): """ Parses a targets string into a list of individual targets. """ new_list = list() for target in target_str.split(','): target = target.strip() target_list = target_to_list(target) if target_list: new_list.extend(target_list) else: LOGGER.info("{0}: Invalid target value".format(target)) return None return list(collections.OrderedDict.fromkeys(new_list))
python
def target_str_to_list(target_str): """ Parses a targets string into a list of individual targets. """ new_list = list() for target in target_str.split(','): target = target.strip() target_list = target_to_list(target) if target_list: new_list.extend(target_list) else: LOGGER.info("{0}: Invalid target value".format(target)) return None return list(collections.OrderedDict.fromkeys(new_list))
[ "def", "target_str_to_list", "(", "target_str", ")", ":", "new_list", "=", "list", "(", ")", "for", "target", "in", "target_str", ".", "split", "(", "','", ")", ":", "target", "=", "target", ".", "strip", "(", ")", "target_list", "=", "target_to_list", "(", "target", ")", "if", "target_list", ":", "new_list", ".", "extend", "(", "target_list", ")", "else", ":", "LOGGER", ".", "info", "(", "\"{0}: Invalid target value\"", ".", "format", "(", "target", ")", ")", "return", "None", "return", "list", "(", "collections", ".", "OrderedDict", ".", "fromkeys", "(", "new_list", ")", ")" ]
Parses a targets string into a list of individual targets.
[ "Parses", "a", "targets", "string", "into", "a", "list", "of", "individual", "targets", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L597-L608
train
greenbone/ospd
ospd/misc.py
port_range_expand
def port_range_expand(portrange): """ Receive a port range and expands it in individual ports. @input Port range. e.g. "4-8" @return List of integers. e.g. [4, 5, 6, 7, 8] """ if not portrange or '-' not in portrange: LOGGER.info("Invalid port range format") return None port_list = list() for single_port in range(int(portrange[:portrange.index('-')]), int(portrange[portrange.index('-') + 1:]) + 1): port_list.append(single_port) return port_list
python
def port_range_expand(portrange): """ Receive a port range and expands it in individual ports. @input Port range. e.g. "4-8" @return List of integers. e.g. [4, 5, 6, 7, 8] """ if not portrange or '-' not in portrange: LOGGER.info("Invalid port range format") return None port_list = list() for single_port in range(int(portrange[:portrange.index('-')]), int(portrange[portrange.index('-') + 1:]) + 1): port_list.append(single_port) return port_list
[ "def", "port_range_expand", "(", "portrange", ")", ":", "if", "not", "portrange", "or", "'-'", "not", "in", "portrange", ":", "LOGGER", ".", "info", "(", "\"Invalid port range format\"", ")", "return", "None", "port_list", "=", "list", "(", ")", "for", "single_port", "in", "range", "(", "int", "(", "portrange", "[", ":", "portrange", ".", "index", "(", "'-'", ")", "]", ")", ",", "int", "(", "portrange", "[", "portrange", ".", "index", "(", "'-'", ")", "+", "1", ":", "]", ")", "+", "1", ")", ":", "port_list", ".", "append", "(", "single_port", ")", "return", "port_list" ]
Receive a port range and expands it in individual ports. @input Port range. e.g. "4-8" @return List of integers. e.g. [4, 5, 6, 7, 8]
[ "Receive", "a", "port", "range", "and", "expands", "it", "in", "individual", "ports", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L621-L638
train
greenbone/ospd
ospd/misc.py
ports_str_check_failed
def ports_str_check_failed(port_str): """ Check if the port string is well formed. Return True if fail, False other case. """ pattern = r'[^TU:0-9, \-]' if ( re.search(pattern, port_str) or port_str.count('T') > 1 or port_str.count('U') > 1 or port_str.count(':') < (port_str.count('T') + port_str.count('U')) ): return True return False
python
def ports_str_check_failed(port_str): """ Check if the port string is well formed. Return True if fail, False other case. """ pattern = r'[^TU:0-9, \-]' if ( re.search(pattern, port_str) or port_str.count('T') > 1 or port_str.count('U') > 1 or port_str.count(':') < (port_str.count('T') + port_str.count('U')) ): return True return False
[ "def", "ports_str_check_failed", "(", "port_str", ")", ":", "pattern", "=", "r'[^TU:0-9, \\-]'", "if", "(", "re", ".", "search", "(", "pattern", ",", "port_str", ")", "or", "port_str", ".", "count", "(", "'T'", ")", ">", "1", "or", "port_str", ".", "count", "(", "'U'", ")", ">", "1", "or", "port_str", ".", "count", "(", "':'", ")", "<", "(", "port_str", ".", "count", "(", "'T'", ")", "+", "port_str", ".", "count", "(", "'U'", ")", ")", ")", ":", "return", "True", "return", "False" ]
Check if the port string is well formed. Return True if fail, False other case.
[ "Check", "if", "the", "port", "string", "is", "well", "formed", ".", "Return", "True", "if", "fail", "False", "other", "case", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L653-L667
train
greenbone/ospd
ospd/misc.py
ports_as_list
def ports_as_list(port_str): """ Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively. """ if not port_str: LOGGER.info("Invalid port value") return [None, None] if ports_str_check_failed(port_str): LOGGER.info("{0}: Port list malformed.") return [None, None] tcp_list = list() udp_list = list() ports = port_str.replace(' ', '') b_tcp = ports.find("T") b_udp = ports.find("U") if ports[b_tcp - 1] == ',': ports = ports[:b_tcp - 1] + ports[b_tcp:] if ports[b_udp - 1] == ',': ports = ports[:b_udp - 1] + ports[b_udp:] ports = port_str_arrange(ports) tports = '' uports = '' # TCP ports listed first, then UDP ports if b_udp != -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:ports.index('U:')] uports = ports[ports.index('U:') + 2:] # Only UDP ports elif b_tcp == -1 and b_udp != -1: uports = ports[ports.index('U:') + 2:] # Only TCP ports elif b_udp == -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:] else: tports = ports if tports: for port in tports.split(','): if '-' in port: tcp_list.extend(port_range_expand(port)) else: tcp_list.append(int(port)) tcp_list.sort() if uports: for port in uports.split(','): if '-' in port: udp_list.extend(port_range_expand(port)) else: udp_list.append(int(port)) udp_list.sort() return (tcp_list, udp_list)
python
def ports_as_list(port_str): """ Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively. """ if not port_str: LOGGER.info("Invalid port value") return [None, None] if ports_str_check_failed(port_str): LOGGER.info("{0}: Port list malformed.") return [None, None] tcp_list = list() udp_list = list() ports = port_str.replace(' ', '') b_tcp = ports.find("T") b_udp = ports.find("U") if ports[b_tcp - 1] == ',': ports = ports[:b_tcp - 1] + ports[b_tcp:] if ports[b_udp - 1] == ',': ports = ports[:b_udp - 1] + ports[b_udp:] ports = port_str_arrange(ports) tports = '' uports = '' # TCP ports listed first, then UDP ports if b_udp != -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:ports.index('U:')] uports = ports[ports.index('U:') + 2:] # Only UDP ports elif b_tcp == -1 and b_udp != -1: uports = ports[ports.index('U:') + 2:] # Only TCP ports elif b_udp == -1 and b_tcp != -1: tports = ports[ports.index('T:') + 2:] else: tports = ports if tports: for port in tports.split(','): if '-' in port: tcp_list.extend(port_range_expand(port)) else: tcp_list.append(int(port)) tcp_list.sort() if uports: for port in uports.split(','): if '-' in port: udp_list.extend(port_range_expand(port)) else: udp_list.append(int(port)) udp_list.sort() return (tcp_list, udp_list)
[ "def", "ports_as_list", "(", "port_str", ")", ":", "if", "not", "port_str", ":", "LOGGER", ".", "info", "(", "\"Invalid port value\"", ")", "return", "[", "None", ",", "None", "]", "if", "ports_str_check_failed", "(", "port_str", ")", ":", "LOGGER", ".", "info", "(", "\"{0}: Port list malformed.\"", ")", "return", "[", "None", ",", "None", "]", "tcp_list", "=", "list", "(", ")", "udp_list", "=", "list", "(", ")", "ports", "=", "port_str", ".", "replace", "(", "' '", ",", "''", ")", "b_tcp", "=", "ports", ".", "find", "(", "\"T\"", ")", "b_udp", "=", "ports", ".", "find", "(", "\"U\"", ")", "if", "ports", "[", "b_tcp", "-", "1", "]", "==", "','", ":", "ports", "=", "ports", "[", ":", "b_tcp", "-", "1", "]", "+", "ports", "[", "b_tcp", ":", "]", "if", "ports", "[", "b_udp", "-", "1", "]", "==", "','", ":", "ports", "=", "ports", "[", ":", "b_udp", "-", "1", "]", "+", "ports", "[", "b_udp", ":", "]", "ports", "=", "port_str_arrange", "(", "ports", ")", "tports", "=", "''", "uports", "=", "''", "# TCP ports listed first, then UDP ports", "if", "b_udp", "!=", "-", "1", "and", "b_tcp", "!=", "-", "1", ":", "tports", "=", "ports", "[", "ports", ".", "index", "(", "'T:'", ")", "+", "2", ":", "ports", ".", "index", "(", "'U:'", ")", "]", "uports", "=", "ports", "[", "ports", ".", "index", "(", "'U:'", ")", "+", "2", ":", "]", "# Only UDP ports", "elif", "b_tcp", "==", "-", "1", "and", "b_udp", "!=", "-", "1", ":", "uports", "=", "ports", "[", "ports", ".", "index", "(", "'U:'", ")", "+", "2", ":", "]", "# Only TCP ports", "elif", "b_udp", "==", "-", "1", "and", "b_tcp", "!=", "-", "1", ":", "tports", "=", "ports", "[", "ports", ".", "index", "(", "'T:'", ")", "+", "2", ":", "]", "else", ":", "tports", "=", "ports", "if", "tports", ":", "for", "port", "in", "tports", ".", "split", "(", "','", ")", ":", "if", "'-'", "in", "port", ":", "tcp_list", ".", "extend", "(", "port_range_expand", "(", "port", ")", ")", "else", ":", "tcp_list", ".", "append", "(", "int", "(", "port", ")", ")", "tcp_list", ".", "sort", "(", ")", "if", "uports", ":", "for", "port", "in", "uports", ".", "split", "(", "','", ")", ":", "if", "'-'", "in", "port", ":", "udp_list", ".", "extend", "(", "port_range_expand", "(", "port", ")", ")", "else", ":", "udp_list", ".", "append", "(", "int", "(", "port", ")", ")", "udp_list", ".", "sort", "(", ")", "return", "(", "tcp_list", ",", "udp_list", ")" ]
Parses a ports string into two list of individual tcp and udp ports. @input string containing a port list e.g. T:1,2,3,5-8 U:22,80,600-1024 @return two list of sorted integers, for tcp and udp ports respectively.
[ "Parses", "a", "ports", "string", "into", "two", "list", "of", "individual", "tcp", "and", "udp", "ports", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L670-L729
train
greenbone/ospd
ospd/misc.py
port_list_compress
def port_list_compress(port_list): """ Compress a port list and return a string. """ if not port_list or len(port_list) == 0: LOGGER.info("Invalid or empty port list.") return '' port_list = sorted(set(port_list)) compressed_list = [] for key, group in itertools.groupby(enumerate(port_list), lambda t: t[1] - t[0]): group = list(group) if group[0][1] == group[-1][1]: compressed_list.append(str(group[0][1])) else: compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1])) return ','.join(compressed_list)
python
def port_list_compress(port_list): """ Compress a port list and return a string. """ if not port_list or len(port_list) == 0: LOGGER.info("Invalid or empty port list.") return '' port_list = sorted(set(port_list)) compressed_list = [] for key, group in itertools.groupby(enumerate(port_list), lambda t: t[1] - t[0]): group = list(group) if group[0][1] == group[-1][1]: compressed_list.append(str(group[0][1])) else: compressed_list.append(str(group[0][1]) + '-' + str(group[-1][1])) return ','.join(compressed_list)
[ "def", "port_list_compress", "(", "port_list", ")", ":", "if", "not", "port_list", "or", "len", "(", "port_list", ")", "==", "0", ":", "LOGGER", ".", "info", "(", "\"Invalid or empty port list.\"", ")", "return", "''", "port_list", "=", "sorted", "(", "set", "(", "port_list", ")", ")", "compressed_list", "=", "[", "]", "for", "key", ",", "group", "in", "itertools", ".", "groupby", "(", "enumerate", "(", "port_list", ")", ",", "lambda", "t", ":", "t", "[", "1", "]", "-", "t", "[", "0", "]", ")", ":", "group", "=", "list", "(", "group", ")", "if", "group", "[", "0", "]", "[", "1", "]", "==", "group", "[", "-", "1", "]", "[", "1", "]", ":", "compressed_list", ".", "append", "(", "str", "(", "group", "[", "0", "]", "[", "1", "]", ")", ")", "else", ":", "compressed_list", ".", "append", "(", "str", "(", "group", "[", "0", "]", "[", "1", "]", ")", "+", "'-'", "+", "str", "(", "group", "[", "-", "1", "]", "[", "1", "]", ")", ")", "return", "','", ".", "join", "(", "compressed_list", ")" ]
Compress a port list and return a string.
[ "Compress", "a", "port", "list", "and", "return", "a", "string", "." ]
cef773166b15a19c17764721d3fe404fa0e107bf
https://github.com/greenbone/ospd/blob/cef773166b15a19c17764721d3fe404fa0e107bf/ospd/misc.py#L742-L759
train