From 6ffabb016782b497116070e9273645d59e62633f Mon Sep 17 00:00:00 2001 From: iamnotcj <69222710+iamnotcj@users.noreply.github.com> Date: Wed, 6 Aug 2025 16:42:26 -0500 Subject: [PATCH 1/2] Garak API --- garak/__main__.py | 6 +++++- garak/api.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 garak/api.py diff --git a/garak/__main__.py b/garak/__main__.py index 923bbebdc..bbdb52b12 100644 --- a/garak/__main__.py +++ b/garak/__main__.py @@ -3,10 +3,14 @@ import sys from garak import cli +from garak import api def main(): - cli.main(sys.argv[1:]) + if "--remote" in sys.argv: + api.run() + else: + cli.main(sys.argv[1:]) if __name__ == "__main__": diff --git a/garak/api.py b/garak/api.py new file mode 100644 index 000000000..c816eb5c9 --- /dev/null +++ b/garak/api.py @@ -0,0 +1,36 @@ +from garak.cli import main +from socket import socket, AF_INET, SOCK_STREAM +import sys + +# 2 sockets, one that receives the arguments, and another that is dedicated to sending the output as a client. + +ADDRESS = "localhost" +PORT = 45345 + + +def run(): + garak_socket = socket(AF_INET, SOCK_STREAM) + garak_socket.bind((ADDRESS, PORT)) + garak_socket.listen() + # Client needs to tell the api which port to send the output to. + while True: + client_socket, client = garak_socket.accept() + + arguments = client_socket.recv(1024).decode() + arguments = arguments.split() + + client_address = client[0] + client_port = int(arguments[0]) + + # This just makes sure that the output of the cli is returned to the client. + def redirectOut(port=0, host=0): + if port == 0 or host == 0: + raise ValueError("Client port or address weren't found") + sock = socket(AF_INET, SOCK_STREAM) + sock.connect((host, port)) + with sock.makefile("w") as file: + sys.stdout = file + main(arguments[1:]) + return sock # if caller needs to access it raw + + redirectOut(client_port, client_address) From cc1cc7bbf2df57183a36cc4c1d8eb097cc9a58d9 Mon Sep 17 00:00:00 2001 From: CJ Anih <69222710+iamnotcj@users.noreply.github.com> Date: Wed, 6 Aug 2025 16:45:26 -0500 Subject: [PATCH 2/2] Update api.py Signed-off-by: CJ Anih <69222710+iamnotcj@users.noreply.github.com> --- garak/api.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/garak/api.py b/garak/api.py index c816eb5c9..b5e25169d 100644 --- a/garak/api.py +++ b/garak/api.py @@ -2,12 +2,9 @@ from socket import socket, AF_INET, SOCK_STREAM import sys -# 2 sockets, one that receives the arguments, and another that is dedicated to sending the output as a client. - ADDRESS = "localhost" PORT = 45345 - def run(): garak_socket = socket(AF_INET, SOCK_STREAM) garak_socket.bind((ADDRESS, PORT)) @@ -31,6 +28,6 @@ def redirectOut(port=0, host=0): with sock.makefile("w") as file: sys.stdout = file main(arguments[1:]) - return sock # if caller needs to access it raw + return sock redirectOut(client_port, client_address)