Skip to content

Commit

Permalink
Merge branch 'develop' into feature/lane_objects_detection
Browse files Browse the repository at this point in the history
Signed-off-by: Keith Homan <[email protected]>
  • Loading branch information
d1scrd authored Sep 30, 2024
2 parents 3e96d0c + 2626c67 commit fb18edf
Show file tree
Hide file tree
Showing 116 changed files with 6,136 additions and 2,784 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ModelsVenv
.svelte-kit
.pnp.*
.yarnrc.yml
package-lock.json

# Python specific
*.py[cod]
Expand Down
Binary file removed Agent/API/Download/885184504/2.mp4
Binary file not shown.
204 changes: 110 additions & 94 deletions Agent/API/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import os
import requests
import json
import multiprocessing

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import load_pem_public_key
Expand All @@ -19,11 +18,14 @@
import json
from dotenv import load_dotenv
import base64
import netifaces

load_dotenv()
app = FastAPI()
RUN_ONCE_FILE = "run_once_flag.txt"

HOST_IP = os.getenv("HOST_IP")


@app.get("/")
def status():
Expand Down Expand Up @@ -58,19 +60,26 @@ def getHardwareInfo():

@app.on_event("startup")
async def startup_event():
if not os.path.exists(RUN_ONCE_FILE):
await install()
# TODO Run initial setup
with open(RUN_ONCE_FILE, "w") as file:
file.write("This file indicates the one-time function has run.")
else:
print("One-time setup function has already run, skipping.")
# if not os.path.exists(RUN_ONCE_FILE):
# await install()
# # TODO Run initial setup
# with open(RUN_ONCE_FILE, "w") as file:
# file.write("This file indicates the one-time function has run.")
# else:
# print("One-time setup function has already run, skipping.")
await install()


# TODO TEST
@app.get("/install")
async def install():
async with httpx.AsyncClient() as client:
# # get my agent details
# response = await client.get('http://' + HOST_IP + ':8006/agent')
# if response.status_code != 200:
# raise HTTPException(status_code=response.status_code, detail="Error fetching external data")
# print("Response:", response.json())

# encrypt my public ecd key
init_elyptic = cerberus.elyptic(True)
agent_public = init_elyptic["public"]
Expand All @@ -90,15 +99,15 @@ async def install():
}
print("JSON data for encryption:", data_to_encrypt)

test = os.getenv("PUBLIC")
test = os.getenv("PUBLIC_TEST")
test = base64.b64decode(test)

encrypted_message = cerberus.encrypt_message(test, data_to_encrypt)
print("Encrypted message: ", encrypted_message)

# Transmit the encrypted data
response2 = await client.post(
"http://127.0.0.1:8006/test",
"http://" + HOST_IP + ":8006/test",
json={"aid": os.getenv("AID"), "message": encrypted_message},
)
if response2.status_code != 200:
Expand All @@ -116,21 +125,29 @@ async def install():
# TODO persist your own pem files and the server's ecdh key.
# This simmulates message passing
session = cerberus.get_session(agent_private, server_ecdh2)
capacity = ""
if os.getenv("AGENT_TYPE") == "S":
capacity = "store"
elif os.getenv("AGENT_TYPE") == "P":
capacity = "process"
else:
capacity = "dual"

message = cerberus.elyptic_encryptor(
session,
json.dumps(
{
"aip": "127.0.0.1",
"aip": findOpenPort()[0], # This will now be the public IP
"aport": 8010,
"capacity": "dual",
"capacity": capacity,
"storage": 290.4,
"identifier": "ACDC",
}
),
)
response3 = await client.post(
"http://127.0.0.1:8006/handshake",
json={"aid": os.getenv("AID"), "message": message},
"http://" + HOST_IP + ":8006/handshake",
json={"aid": os.getenv("AID"), "corporation": os.getenv("CORPORATION_NAME"), "message": message},
)
if response3.status_code != 200:
raise HTTPException(
Expand All @@ -140,22 +157,33 @@ async def install():
print(server_ecdh)
return {"message": "success"}


@app.get("/findOpenPort")
def findOpenPort():
port = 8002
ip = socket.gethostbyname(socket.gethostname())
# ip = "127.0.0.1"

# Try to get the public IP address
try:
ip = requests.get('https://api.ipify.org').text.strip()
print(f"Public IP address: {ip}")
except Exception as e:
print(f"Error getting public IP: {e}")
# If we can't get the public IP, we'll use a placeholder
ip = '0.0.0.0'
print("Using placeholder IP: 0.0.0.0")

# Find an open port
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
result = s.connect_ex((ip, port))
result = s.connect_ex(('localhost', port))
if result == 0:
port += 1
else:
break

return ip, port


def startFTP(ip: str, port: int, old_uid: str, old_size: str, old_token: str):
def startFTP(ip, port, old_uid, old_size, old_token):
def receive_until_null(conn):
data = b""
while True:
Expand All @@ -166,96 +194,81 @@ def receive_until_null(conn):
return data.decode()

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen()
print(f"Server started and listening on {ip}:{port}")
while True:
conn, addr = s.accept()
try:
with conn:
data = receive_until_null(conn)
data = json.loads(data)
print(f"DATA: {data}")

uid = data.get('uid')
size = data['size']
token = data['token']
command = data['command']
mid = data['mid']

directory = f"./Download/{uid}/"
os.makedirs(directory, exist_ok=True)
print(f"Directory {directory} created to store information.")

print(f"Connected by {addr}")

if command == "SEND":
filename = receive_until_null(conn)
print(f"File name: {filename}")

if not mid:
break
filepath = os.path.join(directory, mid)
filepath = filepath + '.mp4'

with open(filepath, "wb") as f:
print(f"Receiving file {filename}...")
with conn:
data = receive_until_null(conn)
data = json.loads(data)
print(f"DATA: {data}")

uid = data["uid"]
mid = data["mid"]
size = data["size"]
token = data["token"]
command = data["command"]

directory = f"./Download/{uid}/"
os.makedirs(directory, exist_ok=True)
print(f"Directory {directory} created to store information.")

print(f"Connected by {addr}")

if command == "SEND":
filename = receive_until_null(conn).strip('"').strip("'")
print(f"Received filename: '{filename}'")

if not filename:
break
filepath = os.path.join(directory, filename)

with open(filepath, "wb") as f:
print(f"Receiving file {filename}...")
while True:
data = conn.recv(1024)
if not data:
break
f.write(data)
print(f"File {filename} received and saved to {filepath}")

elif command == "RETR":
filename = receive_until_null(conn).strip('"').strip("'")
print(f"Received filename: '{filename}'")

if not filename:
break
filepath = os.path.join(directory, filename)

if os.path.exists(filepath):
with open(filepath, "rb") as f:
print(f"Sending file {filename}...")
while True:
data = conn.recv(1024)
data = f.read(1024)
if not data:
break
f.write(data)
print(f"File {filename} received and saved to {filepath}")

elif command == "RETR":
filename = receive_until_null(conn)
print(f"File name: {filename}")

if not mid:
break
filepath = os.path.join(directory, mid)
filepath = filepath + '.mp4'

if os.path.exists(filepath):
with open(filepath, "rb") as f:
print(f"Sending file {filename}...")
while True:
data = f.read(1024)
if not data:
break
conn.sendall(data)
print(f"File {filename} sent successfully.")
else:
print(f"File {filename} does not exist.")
except Exception as e:
print(f"Error during connection handling: {e}")
finally:
conn.close()
print("Connection closed")
break

print("Exiting loop, closing socket.")
s.close()
print("Socket closed")
conn.sendall(data)
print(f"File {filename} sent successfully.")
else:
print(f"File {filename} does not exist.")

s.close()
return "Operation completed successfully."


@app.post("/startupFTPListener/")
async def startupFTPListener(background_tasks: BackgroundTasks, request: Request):
async def startupFTPListener(backgroundTasks: BackgroundTasks, request: Request):
ip, port = findOpenPort()
body = await request.json()
print(f"Body: \n{body}")
aid = os.getenv("AID")
size = "STUMPED"
utoken = "STUMPED"
background_tasks.add_task(startFTP, ip, port, aid, size, utoken)
# process = multiprocessing.Process(target=startFTP, args=(ip, port, aid, size, utoken))
# process.start()
backgroundTasks.add_task(startFTP, ip, port, aid, size, utoken)
return {"aip": ip, "aport": port, "aid": aid}



@app.post("/process/")
async def process(request: Request):
# gets the name from the request
Expand All @@ -272,14 +285,17 @@ async def process(request: Request):
except:
return JSONResponse(status_code=400, content={"message": "Invalid request"})


def verifyOTP(otp):
otp = "1234"
if otp == "1234":
return True
else:
return False


@app.post("/listen")
async def listen(request: Request):
message = await request.json()
print(message)
return {"message": "ill start listening thanks"}


# if __name__ == "__main__":
# multiprocessing.freeze_support()
# import uvicorn
# uvicorn.run(app, host="0.0.0.0", port=8001)
7 changes: 6 additions & 1 deletion Agent/API/broker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from fastapi import FastAPI, BackgroundTasks, Request
import requests
import uvicorn
import os
from dotenv import load_dotenv
load_dotenv()

HOST_IP = os.getenv("HOST_IP")

app = FastAPI()

Expand All @@ -14,7 +19,7 @@ def getAgentIp():
# Here we would use a database lookup to get the IP
# Then get the port from a request
if(checkVerified()):
url = "http://127.0.0.1:8001/startup/"
url = "http://" + HOST_IP + ":8001/startup/"
print("Sending request to: ", url)
response = requests.get(url)

Expand Down
Loading

0 comments on commit fb18edf

Please sign in to comment.