Removes docker support

This commit is contained in:
2023-01-17 17:15:41 -05:00
parent 96b20048a4
commit 11bccecc32
10 changed files with 8 additions and 457 deletions

View File

@@ -2,4 +2,4 @@
Welcome to the README for this website's source code. I host the source code of my website so others can look at my website and learn from it.
The link to a hosted version is at [Link Here](https://lschaefer.xyz)![](https://uptime.lschaefer.xyz/api/badge/1/uptime/720?label=30&labelSuffix=d) You are welcome to use the source code in any of your own projects.
Also this contains the source code for my cookie clicker addon to use this just follow the directions at [Link Here](https://lschaefer.xyz/cookieClicker/).
If you want to recreate this use the docker container and run it on an RPI4. The docker container with steps on how to use it is [here](https://github.com/Lukasdotcom/dockerWebsite).
If you want to recreate this use the docker container. The docker container with steps on how to use it is [here](https://github.com/Lukasdotcom/dockerWebsite).

View File

@@ -1,105 +0,0 @@
<?php
require_once "api.php";
if (! $PRIVILEGE["docker"] and ! $PRIVILEGE["dockerAdmin"]) { // Makes sure that the person has the right privilege
missingPrivilege($USERNAME);
exit();
}
if (array_key_exists("containers", $_GET)) { // Will list all avaliable containers
if ($PRIVILEGE["dockerAdmin"] and array_key_exists("all", $_GET)) { // Allows for all containers to be returned if that is requested
echo json_encode(dbRequest2("SELECT * FROM docker"));
} else {
echo json_encode(dbRequest2("SELECT * FROM docker WHERE owner='$USERNAME' or action='stopped'"));
}
} else if (array_key_exists("start", $_POST) and array_key_exists("image", $_POST)) { // Used to start a container and will return the password
$id = $_POST["start"];
$image = $OGPOST["image"];
if (! dbRequest2("SELECT * FROM docker WHERE action='stopped' and ID='$id'")) { // Will check if the container can be started
echo "Container does not exist or is used";
http_response_code(404);
} elseif (! dbRequest2("SELECT * FROM dockerImages WHERE realName=?", "*", [$image])) { // Will cheeck if the image exists
echo "Image does not exist";
http_response_code(404);
} else { // Will start the container
$password = $USERNAME;
$password .= rand();
$password = sanitize(substr(sha1($password), 5, 8));
dbCommand("UPDATE docker SET action='starting', image='$image', password='$password', owner='$USERNAME' WHERE ID='$id'");
writeLog(23, "$USERNAME is starting container with $image image and id $id and an IP of $address");
echo $password;
}
} else if (array_key_exists("stop", $_POST)) { // Used to stop a container
$id = $_POST["stop"];
if (! dbRequest2("SELECT * FROM docker WHERE action='started' and ID='$id'")) { // Will check if the container is running
echo "Container is not used";
http_response_code(404);
} else if (!$PRIVILEGE["dockerAdmin"] and ! dbRequest2("SELECT * FROM docker WHERE action='started' and ID='$id' and owner='$USERNAME'")) { // Checks if this is actually the owner or an admin if not gives forbidden result
echo "Container is not yours";
http_response_code(403);
} else { // Will stop the container
dbCommand("UPDATE docker SET action='stopping' WHERE ID='$id'");
writeLog(23, "$USERNAME is stopping container with id $id and an IP of $address");
echo "stopping";
}
} else if (array_key_exists("images", $_GET)) {
echo json_encode(dbRequest2("SELECT * FROM dockerImages")); // Will list all available images
} else if (array_key_exists("deleteContainer", $_POST)) { // Used to delete a container
$id = $_POST["deleteContainer"];
if ($PRIVILEGE["dockerAdmin"]) {
if (dbRequest2("SELECT * FROM docker WHERE ID='$id'")) {
dbCommand("DELETE FROM docker WHERE ID='$id'");
writeLog(28, "$USERNAME deleted container with id $id and with ip $address");
echo "Deleted container";
} else {
http_response_code(404);
echo "Could not find container";
}
} else {
missingPrivilege($USERNAME);
}
} else if (array_key_exists("createContainer", $_POST) and array_key_exists("link", $_POST) and array_key_exists("port", $_POST)) { // Will create a container
if ($PRIVILEGE["dockerAdmin"]) {
$id = $USERNAME;
$id .= rand();
$id = sanitize(substr(sha1($id), 5));
$port = intval($_POST["port"]);
dbCommand("DELETE FROM docker WHERE ID='$id'");
dbCommand("INSERT INTO docker VALUES (?, 'stopped', '', 'ubuntu', '$USERNAME', '$port', '$id')", [htmlspecialchars($OGPOST["link"], $flags=ENT_QUOTES)]);
writeLog(28, "$USERNAME created container with id $id and with ip $address");
echo "Created container with id $id";
} else {
missingPrivilege($USERNAME);
}
} else if (array_key_exists("deleteImage", $_POST)) { // Used to delete a container
$name = $OGPOST["deleteImage"];
$name2 = $_POST["deleteImage"];
if ($PRIVILEGE["dockerAdmin"]) {
if (dbRequest2("SELECT * FROM dockerImages WHERE realName=?", "*", [$name])) {
dbCommand("DELETE FROM dockerImages WHERE realName=?", [$name]);
writeLog(28, "$USERNAME deleted image with name $name2 and with ip $address");
echo "Deleted image";
} else {
http_response_code(404);
echo "Could not find image";
}
} else {
missingPrivilege($USERNAME);
}
} else if (array_key_exists("createImage", $_POST) and array_key_exists("name", $_POST)) { // Will create a container
if ($PRIVILEGE["dockerAdmin"]) {
$name = $_POST["name"];
$realName2 = $_POST["createImage"];
$realName = htmlspecialchars($OGPOST["createImage"]);
dbCommand("DELETE FROM dockerImages WHERE realName=?", [$realName]);
echo $realName;
dbCommand("INSERT INTO dockerImages VALUES (?, '$name')", [$realName]);
writeLog(28, "$USERNAME created image with name $realName2 and with ip $address");
echo "Created image with name $realName2";
} else {
missingPrivilege($USERNAME);
}
} else {
http_response_code(400);
echo "Invalid command";
}

View File

@@ -1,100 +0,0 @@
function deleteContainer(id) { // Used to delete a container
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
updateContainer();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`deleteContainer=${id}&key='${getCookie('user')}'`);
}
function updateContainer() { // Used to update the table
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status == 200) {
let text = "<tr><th>ID</th><th>Status</th><th>Link</th><th>Port</th></tr>";
Object.values(JSON.parse(this.responseText)).forEach(element => {
text += `<tr><td>${element["ID"]}</td><td>${element["action"]}</td><td>${element["link"]}</td><td>${element["port"]}</td>`;
if (element["action"] == "stopped") { // Used to add button to delete container
text += `<td><button onclick='deleteContainer("${element["ID"]}")'>Delete</button></td>`;
}
text += "</tr>"
});
$("#container").html(text);
} else {
JQerror(this.responseText);
}
}
ajax.open("GET", `/api/docker.php?containers=get&all=true&key='${getCookie('user')}'`);
ajax.send();
}
function deleteImage(name) { // Used to delete an image
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
updateImage();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`deleteImage=${name}&key='${getCookie('user')}'`);
}
function updateImage() { // Used to update the table
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status == 200) {
let text = "<tr><th>Docker Image</th><th>Name</th></tr>";
Object.values(JSON.parse(this.responseText)).forEach(element => {
text += `<tr><td>${element["realName"]}</td><td>${element["shortName"]}</td>`;
text += `<td><button onclick='deleteImage("${element["realName"]}")'>Delete</button></td>`;
text += "</tr>"
});
$("#image").html(text);
} else {
JQerror(this.responseText);
}
}
ajax.open("GET", `/api/docker.php?images=get&key='${getCookie('user')}'`);
ajax.send();
}
$(document).ready(function() {
updateContainer();
updateImage();
$("#createContainer").click(function() { // Used to create a container.
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
updateContainer();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`createContainer=true&link=${encodeURI($("#link").val())}&port=${encodeURI($("#port").val())}&key='${getCookie('user')}'`);
});
$("#createImage").click(function() { // Used to create an image
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
updateImage();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`createImage=${encodeURI($("#imageName").val())}&name=${encodeURI($("#name").val())}&key='${getCookie('user')}'`);
});
});

View File

@@ -1,78 +0,0 @@
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>
Manage Containers
</title>
<?php
$DESCRIPTION = "A way to manage the docker containers and which ones can be used.";
require_once '../include/all.php';
?>
</head>
<body>
<?php
include '../include/menu.php';
echo "<div class='main'>";
if (! $USERNAME) {
echo "<h2>You are not logged in redirecting...</h2>";
header("Refresh:3; url=/login.php", true);
http_response_code(401);
} else if (! $PRIVILEGE["dockerAdmin"]) {
http_response_code(403);
header("Refresh:3; url=/index.php", true);
echo "<h2>Forbidden redirecting...</h2>";
} else {
$images = dbRequest2("SELECT * FROM dockerImages");
echo "<script>var images=JSON.parse('";
echo json_encode($images);
echo "')</script>";
?>
<script type='text/javascript' src='admin.js'></script>
<h1>Containers</h1>
<table>
<tbody id='container'>
<tr>
<th>ID</th><th>Status</th><th>Link</th><th>Port</th>
</tr>
</tbody>
</table>
<br>
<label for="link">Link for the server: </label><input id='link'>
<br>
<label for="port">The port to be used: </label><input type='number' id='port'>
<br>
<button id='createContainer'>Create</button>
<h1>Images</h1>
<table>
<tbody id='image'>
<tr>
<th>Docker Image</th><th>Name</th>
</tr>
</tbody>
</table>
<br>
<label for="imageName">Image: </label><input id='imageName'>
<br>
<label for="name">Easy name: </label><input id='name'>
<br>
<button id='createImage'>Create</button>
<h3>List of official images</h3>
<ul>
<li>Simple Desktop - lukasdotcom/docker-desktop</li>
<li>Firefox - lukasdotcom/firefox</li>
<li>VScode - lscr.io/linuxserver/code-server</li>
<li>Dekstop v2 - lscr.io/linuxserver/webtop</li>
<li>Firefox v2 - lscr.io/linuxserver/firefox</li>
</ul>
<h3>How to create Image?</h3>
<p>All you have to do to create a valid image for this is have a docker image that accepts an enviromental variable called VNC_PASSWD that is the password for the web interface and that exposes port 80 as a way to access the web interface. Then just publish it on dockerhub and pull it onto the device you are running this on.</p>
<?php
}
?>
</div>
</body>
</html>

View File

@@ -1,79 +0,0 @@
function start(id) { // Used to start a container
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
update();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`start=${id}&image=${$(`#${id}image`).val()}&key='${getCookie('user')}'`);
}
function stop(id) { // Used to stop a container
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status != 200) {
JQerror(this.responseText);
}
update();
}
ajax.open("POST", `/api/docker.php`);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(`stop=${id}&key='${getCookie('user')}'`);
}
function update() { // Used to update the table
const ajax = new XMLHttpRequest();
ajax.onload = function() {
if (ajax.status == 200) {
let text = "<tr><th>ID</th><th>Status</th><th>Image</th><th>Password</th><th>Link</th></tr>";
Object.values(JSON.parse(this.responseText)).forEach(element => {
let password = "";
let image = "";
if (element["action"] == "started") {
password = element["password"];
}
if (element["action"] == "started") { // Used to find the Human Readable name of the image
image = "unknown";
Object.values(images).forEach(element2 => {
if (element2["realName"] == element["image"]) {
image = element2["shortName"];
}
});
} else if (element["action"] == "stopped") {
image = `<select id='${element["ID"]}image'>`;
Object.values(images).forEach(element2 => {
let selected = "";
if ($(`#${element["ID"]}image`).val() == element2["realName"]) {
selected = 'selected="selected"';
}
image += `<option value='${element2["realName"]}' ${selected}>${element2["shortName"]}</option>`;
});
image += "</select>";
}
text += `<tr><td>${element["ID"]}</td><td>${element["action"]}</td><td>${image}</td><td>${password}</td><td>${element["link"]}</td>`;
if (element["action"] == "stopped") { // Used to add button to start container
text += `<td><button onclick='start("${element["ID"]}")'>Start</button></td>`;
} else if (element["action"] == "started") {
text += `<td><button onclick='stop("${element["ID"]}")'>Stop</button></td>`;
}
text += "</tr>"
});
$("#docker").html(text);
} else {
JQerror(this.responseText);
}
}
ajax.open("GET", `/api/docker.php?containers=get&all=true&key='${getCookie('user')}'`);
ajax.send();
}
$(document).ready(function() {
update();
setInterval(update, 5000);
});

View File

@@ -1,49 +0,0 @@
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<title>
Containers
</title>
<?php
$DESCRIPTION = "A way to start a few VM and access them in a web browser";
require_once '../include/all.php';
?>
</head>
<body>
<?php
include '../include/menu.php';
echo "<div class='main'>";
if (! $USERNAME) {
echo "<h2>You are not logged in redirecting...</h2>";
header("Refresh:3; url=/login.php", true);
http_response_code(401);
} else if (! $PRIVILEGE["docker"]) {
http_response_code(403);
header("Refresh:3; url=/index.php", true);
echo "<h2>Forbidden redirecting...</h2>";
} else {
$images = dbRequest2("SELECT * FROM dockerImages");
echo "<script>var images=JSON.parse('";
echo json_encode($images);
echo "')</script>";
?>
<script type='text/javascript' src='index.js'></script>
<h1>Run Containers</h1>
<p>If a username is needed it will always be abc</p>
<table>
<tbody id='docker'>
<tr>
<th>ID</th><th>Status</th><th>Image</th><th>Password</th><th>Link</th>
</tr>
</tbody>
</table>
<?php
}
?>
</div>
</body>
</html>

View File

@@ -301,7 +301,7 @@ foreach ($_COOKIE as $pointer => $value) {
// Removes all expired cookies from the database
$Time = time();
dbCommand("DELETE FROM cookies WHERE expire < $Time and expire != 0");
$PRIVILEGELIST = ["root", "internet", "editUser", "deleteUser", "deleteElectricity", "deleteLog", "viewLog", "changeCredintials", "deleteElectricity", "deleteError", "restartServer", "updateServer", "serverStatus", "viewBackup", "restore", "docker", "dockerAdmin", "mail"]; // A List of all possible privileges
$PRIVILEGELIST = ["root", "internet", "editUser", "deleteUser", "deleteElectricity", "deleteLog", "viewLog", "changeCredintials", "deleteElectricity", "deleteError", "restartServer", "updateServer", "serverStatus", "viewBackup", "restore", "mail"]; // A List of all possible privileges
function noUser() { # Used to set everything up as if no yser is logged in
global $USERNAME, $PRIVILEGE, $PRIVILEGELIST;
$USERNAME = "";

View File

@@ -9,8 +9,6 @@ $MENUITEMS = [["Main Page", "/index.php"],
["Truth Trees", "/logic/index.php"],
["Floppy", "/floppy.php"],
["Soccer", "/soccer.php"],
["privilege", "docker", "/docker/index.php", "Docker Containers"],
["privilege", "dockerAdmin", "/docker/admin.php", "Docker Admin"],
["Electricity Log", "/electricity.php"],
["privilege", "viewLog", "/log/index.php", "Server Log"],
["privilege", "viewBackup", "/backup/index.php", "Backups"],

View File

@@ -168,8 +168,6 @@ def repair(): # Repairs all tables or updates them if needed
"golfGamePlayers" : [["gameID", 1], ["multiplier", 1], ["user", 0], ["points", 1], ["orderID", 1], ["lastMode", 0], ["upToDate", 6], ["turnsSkipped", 1]],
"golfGameCards" : [["gameID", 1], ["user", 0], ["card", 1], ["cardPlacement", 1], ["faceUp", 6]],
"golfGame" : [["ID", 5], ["deck", 4], ["discard", 4], ["cardNumber", 1], ["flipNumber", 1], ["multiplierForFlip", 1], ["pointsToEnd", 1], ["name", 0], ["password", 0], ["players", 1], ["playersToStart", 1], ["currentPlayer", 1], ["turnStartTime", 1], ["locked", 6], ["decks", 1], ["skipTime", 1], ["timeLeft", 1], ["skipTurns", 1], ["resetPoints", 1]],
"docker" : [["link", 0], ["action", 0], ["image", 0], ["password", 0], ["owner", 0], ["port", 1], ["ID", 0]],
"dockerImages" : [["realName", 0], ["shortName", 0]]
}
changedTables = []
for x in databaseDict:
@@ -270,6 +268,12 @@ def repair(): # Repairs all tables or updates them if needed
command("UPDATE golfGame SET resetPoints='0'")
version = "v2.4"
updatedVersions.append("v2.4")
if version == "v2.4": # Drops support for docker
command("DROP TABLE docker")
command("DROP TABLE dockerImages")
command("DELETE FROM privileges WHERE privilege='docker' OR privilege='dockerAdmin'")
version = "v2.5"
updatedVersions.append("v2.5")
# Fixes the version if it is invalid to the latest version
if version != latest_version:
version = latest_version

View File

@@ -17,12 +17,6 @@ import sys
import glob
import string
whitelist = set(string.ascii_letters + string.digits + "/" + "@" + "." + "-" + "_")
try:
import docker
dockerClient = docker.from_env()
skipDocker = False
except:
skipDocker = True
def sanitize(txt): # Is a very simple sanitizer that allows all ascii_letters numbers and the / and @
if type(txt) == type(1) or type(txt) == type(True): # Makes sure that if it is an int or a bool it will not be sanitized because that is not neccessary.
@@ -292,8 +286,6 @@ Deny from all""")
# Will add to log if a library could not be connected to
if skipGPIO:
writeLog("Could not import GPIO library", 9)
if skipDocker:
writeLog("Could not connect to docker", 9)
while True: # will wait until connected to internet
try:
urllib.request.urlopen("https://google.com")
@@ -387,38 +379,6 @@ Deny from all""")
# Will check every 2 seconds if the button is pressed and when it is show it on the led and then wait another second to verify that it is an actual press
while True:
time.sleep(2)
# Will check if a docker container should be started or stopped.
if not skipDocker:
dockerList = database.trueSearch("SELECT * FROM docker")
for x in dockerList:
# Will check if the container has already been stopped
id = x[6]
if x[1] == "started":
try:
dockerClient.containers.get(id)
except Exception:
database.command(f"UPDATE docker SET action='stopped' WHERE ID='{id}'")
writeLog(f"Container with id of {id} was stopped", 24)
elif x[1] == "starting": # Will start all containers that are neccessary
# Will pull the image and delete all untagged images
dockerClient.images.pull(x[2])
dockerClient.images.prune(filters={"dangling":1})
password = x[3]
if x[2] == "lscr.io/linuxserver/code-server": # Special case for code server.
newID = dockerClient.containers.run(x[2], detach=True, ports={'8443/tcp':x[5]}, remove=True, environment=["PUID=1000", "PGID=1000", "TZ=America/Detroit", f"PASSWORD={password}", f"SUDO_PASSWORD={password}", "DEFAULT_WORKSPACE=/config/workspace"]).attrs["Id"]
elif x[2][0:8] == "lscr.io/": # Is the default code for all linuxserver images.
newID = dockerClient.containers.run(x[2], detach=True, ports={'3000/tcp':x[5]}, remove=True, environment=["PUID=1000", "PGID=1000", "TZ=America/Detroit", "AUTO_LOGIN=false"], shm_size="1gb").attrs["Id"]
# Makes sure that the container has the right password
execID = dockerClient.api.exec_create(newID, f'bash -c "echo \"abc:{password}\" | chpasswd"', user="root")["Id"]
dockerClient.api.exec_start(execID)
else: # Default case
newID = dockerClient.containers.run(x[2], detach=True, ports={'80/tcp':x[5]}, remove=True, environment=[f"VNC_PASSWD={password}"]).attrs["Id"]
database.command(f"UPDATE docker SET action='started', id='{newID}' WHERE ID='{id}'")
writeLog(f"Container with id of {id} which changed to {newID} was started", 23)
elif x[1] == "stopping": # Stops all containers that need to be stopped.
dockerClient.containers.get(id).stop()
database.command(f"UPDATE docker SET action='stopped' WHERE ID='{id}'")
writeLog(f"Container with id of {id} was stopped", 24)
if os.path.isfile(location + "restart.json"): # Used to restart the server
writeLog("Server is being restarted", 12)
os.remove(location + "restart.json")