25 Commits
v1.0 ... main

Author SHA1 Message Date
5689189c8c feat: added android/arm64 build target 2025-09-04 21:09:11 +02:00
95486e86e1 chore: bump version to 1.2 2025-09-03 23:20:45 +02:00
0edc734766 feat: add case-sensitive sorting for file list 2025-09-03 23:17:24 +02:00
419a7e5c1a feat: let the server crash fast when the data folder becomes unavailable 2025-09-03 22:51:49 +02:00
62064721d0 +DeleteFile(); +GetFileListOfDataFolder() 2025-09-03 22:50:30 +02:00
7b6db3c5b4 fix: handling of the ‘path’ flag has been improved; directories are now created including all parent directories 2025-09-03 21:55:51 +02:00
5c0800b5ce refactor: unify error handling even more 2025-09-03 21:28:45 +02:00
863171f66b refactor: unify error handling 2025-09-03 21:09:42 +02:00
6db6127522 feat: make the dropzone responsive 2025-09-01 00:08:11 +02:00
3172f90999 refactor: rename functions and restructure them 2025-08-31 23:51:20 +02:00
f07defc814 chore: bump version to 1.1 2025-08-30 01:18:38 +02:00
0c6f6b65ef refactored sanitizeFilename() 2025-08-30 01:10:23 +02:00
ccefdd23f3 Global variables consolidated into the ‘state’ object 2025-08-30 01:05:35 +02:00
5a3551a0f5 added DEFAULT_DROPZONE_TEXT 2025-08-30 00:57:04 +02:00
7773ab1b9c refacatored showError() and showSuccess() 2025-08-30 00:53:38 +02:00
e7a58dcead added filename to success message when file gets deleted 2025-08-30 00:48:36 +02:00
f2f6f0f24c refactored uploadFiles() 2025-08-30 00:45:12 +02:00
9d1d2b3299 refactored fetchFiles() 2025-08-30 00:39:05 +02:00
673d15b1b1 simplified getBanner() after testing it on windows 2025-08-28 23:54:07 +02:00
b6b4b720df added user feedback for actions like uploading or deleting 2025-08-28 23:36:50 +02:00
c8af56f1dc upgraded the startup banner 2025-08-28 22:54:31 +02:00
3f0b9fa625 renamed the upload folder 2025-08-28 22:31:00 +02:00
2b0597db0b fix: close upload file before rename to avoid locking issues 2025-08-27 22:52:09 +02:00
9fc8b370d0 moved whole UI to JavaScript 2025-08-27 22:30:00 +02:00
da0dfeab46 + build.sh 2025-08-27 22:21:01 +02:00
13 changed files with 686 additions and 376 deletions

View File

@@ -7,7 +7,6 @@ import (
"io"
"log"
"net/http"
"os"
"git.0x0001f346.de/andreas/ablage/config"
"github.com/julienschmidt/httprouter"
@@ -25,7 +24,7 @@ var assetScriptJS []byte
//go:embed assets/style.css
var assetStyleCSS []byte
func Init() {
func Init() error {
router := httprouter.New()
router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -57,16 +56,14 @@ func Init() {
config.PrintStartupBanner()
err := http.ListenAndServe(fmt.Sprintf(":%d", config.GetPortToListenOn()), handler)
if err != nil {
fmt.Fprintf(os.Stderr, "Ablage exited with error:\n%v\n", err)
os.Exit(1)
return fmt.Errorf("Webserver exited with error: %v", err)
}
return
return nil
}
tlsCert, err := tls.X509KeyPair(config.GetTLSCertificate(), config.GetTLSKey())
if err != nil {
fmt.Fprintf(os.Stderr, "Faild to parse PEM encoded public/private key pair:\n%v\n", err)
os.Exit(1)
return fmt.Errorf("Faild to parse PEM encoded public/private key pair: %v", err)
}
server := &http.Server{
@@ -83,9 +80,10 @@ func Init() {
err = server.ListenAndServeTLS("", "")
if err != nil {
fmt.Fprintf(os.Stderr, "Ablage exited with error:\n%v\n", err)
os.Exit(1)
return fmt.Errorf("Webserver exited with error: %v", err)
}
return nil
}
func getClientIP(r *http.Request) string {

View File

@@ -12,29 +12,11 @@
<script src="/script.js"></script>
</head>
<body>
<a href="/" class="logo"><h1>Ablage</h1></a>
<div id="dropzone" style="display: none">
Drag & drop files here or click to select
</div>
<input
type="file"
id="fileInput"
name="uploadfile"
multiple
style="display: none"
/>
<div id="overallProgressContainer" style="display: none">
<div id="currentFileName"></div>
<progress id="overallProgress" value="0" max="100"></progress>
<div id="overallStatus" class="status"></div>
</div>
<ul id="file-list"></ul>
<div id="sinkholeModeInfo" class="sinkholeModeInfo" style="display: none">
- Sinkhole mode enabled, no files will get listed -
</div>
<a href="/" class="logo">
<h1>Ablage</h1>
</a>
<h3 style="color: red; text-align: center; margin-top: 100px">
We will need JavaScript from here on, sorry...
</h3>
</body>
</html>

View File

@@ -1,147 +1,337 @@
(() => {
"use strict";
let AppConfig = null;
let UI = {};
const state = {
config: null,
files: {},
ui: {},
errorTimeout: null,
};
async function appLoop() {
if (AppConfig === null) {
// ===== app ==============================
async function appInit() {
uiBuildElements();
uiCacheElements();
uiBindEvents();
await configLoad();
appUpdate();
setInterval(appUpdate, 5 * 1000);
setInterval(configLoad, 60 * 1000);
}
async function appUpdate() {
if (state.config === null) {
return;
}
updateUI();
fetchFiles();
uiUpdate();
fileListFetch();
}
function updateUI() {
if (AppConfig.Modes.Readonly) {
UI.dropzone.style.display = "none";
} else {
UI.dropzone.style.display = "block";
}
// ===== config ===========================
if (AppConfig.Modes.Sinkhole) {
UI.fileList.style.display = "none";
UI.sinkholeModeInfo.style.display = "block";
} else {
UI.fileList.style.display = "block";
UI.sinkholeModeInfo.style.display = "none";
}
}
async function initApp() {
UI.currentFileName = document.getElementById("currentFileName");
UI.dropzone = document.getElementById("dropzone");
UI.fileInput = document.getElementById("fileInput");
UI.fileList = document.getElementById("file-list");
UI.overallProgress = document.getElementById("overallProgress");
UI.overallStatus = document.getElementById("overallStatus");
UI.overallProgressContainer = document.getElementById(
"overallProgressContainer"
);
UI.sinkholeModeInfo = document.getElementById("sinkholeModeInfo");
UI.dropzone.addEventListener("click", () => UI.fileInput.click());
UI.fileInput.addEventListener("change", () => {
if (UI.fileInput.files.length > 0) uploadFiles(UI.fileInput.files);
});
UI.dropzone.addEventListener("dragover", (e) => {
e.preventDefault();
UI.dropzone.style.borderColor = "#0fff50";
});
UI.dropzone.addEventListener("dragleave", () => {
UI.dropzone.style.borderColor = "#888";
});
UI.dropzone.addEventListener("drop", (e) => {
e.preventDefault();
UI.dropzone.style.borderColor = "#888";
if (e.dataTransfer.files.length > 0) uploadFiles(e.dataTransfer.files);
});
await loadAppConfig();
appLoop();
setInterval(appLoop, 5 * 1000);
setInterval(loadAppConfig, 60 * 1000);
}
async function loadAppConfig() {
async function configLoad() {
try {
const res = await fetch("/config/", { cache: "no-store" });
if (!res.ok) {
console.error("HTTP error:", res.status);
}
AppConfig = await res.json();
state.config = await res.json();
} catch (err) {
console.error("Failed to load config:", err);
AppConfig = null;
state.config = null;
}
}
async function fetchFiles() {
if (AppConfig.Modes.Sinkhole) {
UI.fileList.innerHTML = "";
return;
}
// ===== files ============================
async function fileDeleteClickHandler(event, file) {
event.preventDefault();
if (!confirm(`Do you really want to delete "${file.Name}"?`)) return;
try {
const res = await fetch(AppConfig.Endpoints.Files, { cache: "no-store" });
if (!res.ok) throw new Error("HTTP " + res.status);
const files = await res.json();
if (!UI.fileList) return;
UI.fileList.innerHTML = "";
files.forEach((file) => {
const size = humanReadableSize(file.Size);
const li = document.createElement("li");
const downloadLink = document.createElement("a");
downloadLink.className = "download-link";
downloadLink.href = AppConfig.Endpoints.FilesGet.replace(
":filename",
encodeURIComponent(file.Name)
);
downloadLink.textContent = `${file.Name} (${size})`;
li.appendChild(downloadLink);
if (!AppConfig.Modes.Readonly) {
const deleteLink = document.createElement("a");
deleteLink.className = "delete-link";
deleteLink.href = "#";
deleteLink.textContent = " [Delete]";
deleteLink.title = "Delete file";
deleteLink.addEventListener("click", async (e) => {
e.preventDefault();
if (!confirm(`Do you really want to delete "${file.Name}"?`))
return;
try {
const r = await fetch(
AppConfig.Endpoints.FilesDelete.replace(
const res = await fetch(
state.config.Endpoints.FilesDelete.replace(
":filename",
encodeURIComponent(file.Name)
),
{ method: "GET" }
);
if (!r.ok) throw new Error("Delete failed " + r.status);
fetchFiles();
} catch (err) {
console.error(err);
if (res.ok) {
uiShowSuccess("File deleted: " + file.Name);
} else {
uiShowError("Delete failed");
}
fileListFetch();
} catch (err) {
uiShowError("Delete failed");
}
}
async function fileListFetch() {
if (state.config.Modes.Sinkhole) {
fileListClear();
return;
}
try {
let files = await fileListRequest();
files = fileSortFiles(files, "name-asc");
state.files = {};
fileListClear();
fileListRender(files);
} catch (err) {
console.error("fileListFetch failed:", err);
}
}
async function fileListRequest() {
const res = await fetch(state.config.Endpoints.Files, {
cache: "no-store",
});
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
function fileListClear() {
if (state.ui.fileList) state.ui.fileList.innerHTML = "";
}
function fileListRender(files) {
if (!state.ui.fileList) return;
files.forEach((file) => {
state.files[file.Name] = true;
const li = document.createElement("li");
li.appendChild(uiCreateDownloadLink(file));
if (!state.config.Modes.Readonly) {
li.appendChild(uiCreateDeleteLink(file));
}
state.ui.fileList.appendChild(li);
});
}
function fileSanitizeName(dirtyFilename) {
if (!dirtyFilename || dirtyFilename.trim() === "") {
return "upload.bin";
}
const filenameWithoutPath = dirtyFilename.split(/[\\/]/).pop();
const lastDot = filenameWithoutPath.lastIndexOf(".");
const extension = lastDot !== -1 ? filenameWithoutPath.slice(lastDot) : "";
let nameOnly =
lastDot !== -1
? filenameWithoutPath.slice(0, lastDot)
: filenameWithoutPath;
const charMap = {
Ä: "Ae",
ä: "ae",
Ö: "Oe",
ö: "oe",
Ü: "Ue",
ü: "ue",
ß: "ss",
};
let cleanedFilename = nameOnly.replace(/./g, (char) => {
if (charMap[char]) {
return charMap[char];
}
if (char === " ") {
return "_";
}
return char;
});
li.appendChild(deleteLink);
cleanedFilename = cleanedFilename.replace(/[^a-zA-Z0-9._-]+/g, "_");
while (cleanedFilename.includes("__")) {
cleanedFilename = cleanedFilename.replace(/__+/g, "_");
}
UI.fileList.appendChild(li);
cleanedFilename = cleanedFilename.replace(/^_+|_+$/g, "");
const MAX_LEN = 128;
if (cleanedFilename.length > MAX_LEN) {
cleanedFilename = cleanedFilename.slice(0, MAX_LEN);
}
return cleanedFilename + extension;
}
function fileSortFiles(files, mode = "name-asc") {
function cmpCodePoint(a, b) {
if (a === b) return 0;
return a < b ? -1 : 1;
}
const arr = files.slice();
switch (mode) {
case "name-asc":
arr.sort((a, b) => cmpCodePoint(a.Name, b.Name));
break;
case "name-desc":
arr.sort((a, b) => cmpCodePoint(b.Name, a.Name));
break;
case "size-asc":
arr.sort((a, b) => a.Size - b.Size);
break;
case "size-desc":
arr.sort((a, b) => b.Size - a.Size);
break;
}
return arr;
}
function fileValidateBeforeUpload(files) {
for (const f of files) {
const safeName = fileSanitizeName(f.name);
if (safeName === ".upload") {
uiShowError("Invalid filename: .upload");
return false;
}
if (safeName in state.files) {
uiShowError("File already exists: " + f.name);
return false;
}
}
return true;
}
// ===== ui ===============================
function uiBindEvents() {
window.addEventListener(
"resize",
() => (state.ui.dropzone.innerHTML = uiGetDropzoneText())
);
state.ui.dropzone.addEventListener("click", () =>
state.ui.fileInput.click()
);
state.ui.dropzone.addEventListener("dragover", (e) => {
e.preventDefault();
state.ui.dropzone.style.borderColor = "#0fff50";
});
state.ui.dropzone.addEventListener("dragleave", () => {
state.ui.dropzone.style.borderColor = "#888";
});
state.ui.dropzone.addEventListener("drop", (e) => {
e.preventDefault();
state.ui.dropzone.style.borderColor = "#888";
if (e.dataTransfer.files.length > 0) uploadStart(e.dataTransfer.files);
});
state.ui.fileInput.addEventListener("change", () => {
if (state.ui.fileInput.files.length > 0)
uploadStart(state.ui.fileInput.files);
});
} catch (err) {
console.error("fetchFiles failed:", err);
}
}
function humanReadableSize(bytes) {
function uiBuildElements() {
document.body.innerHTML = "";
const aLogo = document.createElement("a");
aLogo.href = "/";
aLogo.className = "logo";
const h1Logo = document.createElement("h1");
h1Logo.textContent = "Ablage";
aLogo.appendChild(h1Logo);
document.body.appendChild(aLogo);
const divDropzone = document.createElement("div");
divDropzone.className = "dropzone";
divDropzone.id = "dropzone";
divDropzone.innerHTML = uiGetDropzoneText();
divDropzone.style.display = "none";
document.body.appendChild(divDropzone);
const fileInput = document.createElement("input");
fileInput.type = "file";
fileInput.id = "fileInput";
fileInput.name = "uploadfile";
fileInput.multiple = true;
fileInput.style.display = "none";
document.body.appendChild(fileInput);
const divOverallProgressContainer = document.createElement("div");
divOverallProgressContainer.id = "overallProgressContainer";
divOverallProgressContainer.style.display = "none";
const divCurrentFileName = document.createElement("div");
divCurrentFileName.id = "currentFileName";
const progressOverall = document.createElement("progress");
progressOverall.id = "overallProgress";
progressOverall.value = 0;
progressOverall.max = 100;
const divOverallStatus = document.createElement("div");
divOverallStatus.id = "overallStatus";
divOverallStatus.className = "status";
divOverallProgressContainer.appendChild(divCurrentFileName);
divOverallProgressContainer.appendChild(progressOverall);
divOverallProgressContainer.appendChild(divOverallStatus);
document.body.appendChild(divOverallProgressContainer);
const ulFileList = document.createElement("ul");
ulFileList.id = "file-list";
document.body.appendChild(ulFileList);
const divSinkholeModeInfo = document.createElement("div");
divSinkholeModeInfo.id = "sinkholeModeInfo";
divSinkholeModeInfo.className = "sinkholeModeInfo";
divSinkholeModeInfo.style.display = "none";
divSinkholeModeInfo.textContent =
"- Sinkhole mode enabled, no files will get listed -";
document.body.appendChild(divSinkholeModeInfo);
}
function uiCacheElements() {
state.ui.currentFileName = document.getElementById("currentFileName");
state.ui.dropzone = document.getElementById("dropzone");
state.ui.fileInput = document.getElementById("fileInput");
state.ui.fileList = document.getElementById("file-list");
state.ui.overallProgress = document.getElementById("overallProgress");
state.ui.overallStatus = document.getElementById("overallStatus");
state.ui.overallProgressContainer = document.getElementById(
"overallProgressContainer"
);
state.ui.sinkholeModeInfo = document.getElementById("sinkholeModeInfo");
}
function uiCreateDeleteLink(file) {
const link = document.createElement("a");
link.className = "delete-link";
link.href = "#";
link.textContent = " [Delete]";
link.title = "Delete file";
link.addEventListener("click", (e) => fileDeleteClickHandler(e, file));
return link;
}
function uiCreateDownloadLink(file) {
const size = uiFormatSize(file.Size);
const link = document.createElement("a");
link.className = "download-link";
link.href = state.config.Endpoints.FilesGet.replace(
":filename",
encodeURIComponent(file.Name)
);
link.textContent = `${file.Name} (${size})`;
return link;
}
function uiFormatSize(bytes) {
const units = ["B", "KB", "MB", "GB", "TB"];
let i = 0;
while (bytes >= 1024 && i < units.length - 1) {
@@ -151,7 +341,7 @@
return `${bytes.toFixed(1)} ${units[i]}`;
}
function humanReadableSpeed(bytesPerSec) {
function uiFormatSpeed(bytesPerSec) {
if (!isFinite(bytesPerSec) || bytesPerSec <= 0) return "—";
if (bytesPerSec < 1024) return bytesPerSec.toFixed(0) + " B/s";
if (bytesPerSec < 1024 * 1024)
@@ -159,85 +349,156 @@
return (bytesPerSec / (1024 * 1024)).toFixed(2) + " MB/s";
}
function uploadFiles(fileListLike) {
const files = Array.from(fileListLike);
if (files.length === 0) return;
UI.overallProgressContainer.style.display = "block";
UI.overallProgress.value = 0;
UI.overallStatus.textContent = "";
UI.currentFileName.textContent = "";
const totalSize = files.reduce((sum, f) => sum + f.size, 0);
let uploadedBytes = 0;
const t0 = Date.now();
let idx = 0;
const uploadNext = () => {
if (idx >= files.length) {
UI.overallProgressContainer.style.display = "none";
UI.overallProgress.value = 0;
UI.overallStatus.textContent = "";
UI.currentFileName.textContent = "";
fetchFiles();
return;
function uiGetDropzoneText() {
if (window.innerWidth <= 480) {
return "Tap to upload files";
}
const file = files[idx];
UI.currentFileName.textContent = file.name;
return "Drag & drop files here or click to upload";
}
const xhr = new XMLHttpRequest();
const form = new FormData();
form.append("uploadfile", file);
function uiInitProgress() {
state.ui.overallProgressContainer.style.display = "block";
state.ui.overallProgress.value = 0;
state.ui.overallStatus.textContent = "";
state.ui.currentFileName.textContent = "";
}
xhr.upload.addEventListener("progress", (e) => {
if (!e.lengthComputable) return;
function uiShowError(msg) {
uiShowMessage(msg, "error", 2000);
}
const totalUploaded = uploadedBytes + e.loaded;
function uiShowMessage(msg, type, duration = 2000) {
state.ui.dropzone.innerHTML = msg;
state.ui.dropzone.classList.add(type);
if (state.errorTimeout) clearTimeout(state.errorTimeout);
state.errorTimeout = setTimeout(() => {
state.ui.dropzone.innerHTML = uiGetDropzoneText();
state.ui.dropzone.classList.remove(type);
state.errorTimeout = null;
}, duration);
}
function uiShowSuccess(msg) {
uiShowMessage(msg, "success", 1500);
}
function uiUpdate() {
if (state.config.Modes.Readonly) {
state.ui.dropzone.style.display = "none";
} else {
state.ui.dropzone.style.display = "block";
}
if (state.config.Modes.Sinkhole) {
state.ui.fileList.style.display = "none";
state.ui.sinkholeModeInfo.style.display = "block";
} else {
state.ui.fileList.style.display = "block";
state.ui.sinkholeModeInfo.style.display = "none";
}
}
function uiUpdateProgress(totalUploaded, totalSize, startTime) {
const percent = (totalUploaded / totalSize) * 100;
UI.overallProgress.value = percent;
state.ui.overallProgress.value = percent;
const elapsed = (Date.now() - t0) / 1000;
const elapsed = (Date.now() - startTime) / 1000;
const speed = totalUploaded / elapsed;
const speedStr = humanReadableSpeed(speed);
const speedStr = uiFormatSpeed(speed);
const remainingBytes = totalSize - totalUploaded;
const etaSec = speed > 0 ? remainingBytes / speed : Infinity;
const min = Math.floor(etaSec / 60);
const sec = Math.floor(etaSec % 60);
UI.overallStatus.textContent =
state.ui.overallStatus.textContent =
`${percent.toFixed(1)}% (${(totalSize / 1024 / 1024).toFixed(
1
)} MB total) — ` +
`Speed: ${speedStr}, Est. time left: ${
isFinite(etaSec) ? `${min}m ${sec}s` : "calculating…"
}`;
}
// ===== upload ===========================
function uploadFinish(success) {
state.ui.overallProgressContainer.style.display = "none";
state.ui.overallProgress.value = 0;
state.ui.overallStatus.textContent = "";
state.ui.currentFileName.textContent = "";
fileListFetch();
if (success) {
uiShowSuccess("Upload successful");
}
}
function uploadStart(fileListLike) {
const files = Array.from(fileListLike);
if (files.length === 0) return;
if (!fileValidateBeforeUpload(files)) return;
uiInitProgress();
const totalSize = files.reduce((sum, f) => sum + f.size, 0);
let uploadedBytes = 0;
let currentIndex = 0;
const startTime = Date.now();
let allSuccessful = true;
function uploadNext() {
if (currentIndex >= files.length) {
uploadFinish(allSuccessful);
return;
}
const file = files[currentIndex];
state.ui.currentFileName.textContent = file.name;
const xhr = new XMLHttpRequest();
const form = new FormData();
form.append("uploadfile", file);
xhr.upload.addEventListener("progress", (e) => {
if (e.lengthComputable) {
uiUpdateProgress(uploadedBytes + e.loaded, totalSize, startTime);
}
});
xhr.addEventListener("load", () => {
if (xhr.status === 200) {
uploadedBytes += file.size;
} else if (xhr.status === 409) {
uiShowError("File already exists: " + file.name);
allSuccessful = false;
} else {
console.error("Upload failed with status", xhr.status);
uiShowError("Upload failed: " + file.name);
allSuccessful = false;
}
idx++;
currentIndex++;
uploadNext();
});
xhr.addEventListener("error", () => {
console.error("Network/server error during upload.");
idx++;
uiShowError("Network or server error during upload.");
allSuccessful = false;
currentIndex++;
uploadNext();
});
xhr.open("POST", AppConfig.Endpoints.Upload);
xhr.open("POST", state.config.Endpoints.Upload);
xhr.send(form);
};
}
fetchFiles();
fileListFetch();
uploadNext();
}
document.addEventListener("DOMContentLoaded", initApp);
// ===== init ============================
document.addEventListener("DOMContentLoaded", appInit);
})();

View File

@@ -9,7 +9,7 @@ body {
}
/* Dropzone */
#dropzone {
.dropzone {
border: 2px dashed #888;
border-radius: 10px;
color: #fefefe;
@@ -20,10 +20,22 @@ body {
transition: all 0.3s ease;
}
#dropzone:hover {
.dropzone:hover {
color: #0fff50;
}
.dropzone.error {
border: 2px solid #ff4d4d;
color: #ff4d4d;
font-weight: bold;
}
.dropzone.success {
border: 2px solid #0fff50;
color: #0fff50;
font-weight: bold;
}
/* File list */
#file-list {
list-style: none;

View File

@@ -82,32 +82,25 @@ func httpGetFiles(w http.ResponseWriter, r *http.Request, ps httprouter.Params)
json.NewEncoder(w).Encode([]FileInfo{})
}
entries, err := os.ReadDir(config.GetPathDataFolder())
files, err := filesystem.GetFileListOfDataFolder()
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
log.Fatalf("[Error] %v", err)
}
files := make([]FileInfo, 0, len(entries))
fileInfos := make([]FileInfo, 0, len(files))
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
files = append(files, FileInfo{
Name: info.Name(),
Size: info.Size(),
})
for filename, sizeInBytes := range files {
fileInfos = append(
fileInfos,
FileInfo{
Name: filename,
Size: sizeInBytes,
},
)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(files)
json.NewEncoder(w).Encode(fileInfos)
}
func httpGetFilesDeleteFilename(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
@@ -121,25 +114,10 @@ func httpGetFilesDeleteFilename(w http.ResponseWriter, r *http.Request, ps httpr
return
}
entries, err := os.ReadDir(config.GetPathDataFolder())
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
files := map[string]int64{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
continue
}
files[info.Name()] = info.Size()
}
filename := ps.ByName("filename")
files, err := filesystem.GetFileListOfDataFolder()
sizeInBytes, fileExists := files[filename]
if !fileExists {
w.Header().Set("Content-Type", "application/json")
@@ -147,8 +125,7 @@ func httpGetFilesDeleteFilename(w http.ResponseWriter, r *http.Request, ps httpr
return
}
fullPath := filepath.Join(config.GetPathDataFolder(), filename)
err = os.Remove(fullPath)
err = filesystem.DeleteFile(filename)
if err != nil {
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
@@ -167,15 +144,19 @@ func httpGetFilesGetFilename(w http.ResponseWriter, r *http.Request, ps httprout
}
filename := ps.ByName("filename")
filePath := filepath.Join(config.GetPathDataFolder(), filename)
info, err := os.Stat(filePath)
if err != nil || info.IsDir() {
files, err := filesystem.GetFileListOfDataFolder()
if err != nil {
log.Fatalf("[Error] %v", err)
}
sizeInBytes, fileExists := files[filename]
if !fileExists {
http.Error(w, "404 File Not Found", http.StatusNotFound)
return
}
log.Printf("| Download | %-21s | %-10s | %s\n", getClientIP(r), filesystem.GetHumanReadableSize(info.Size()), filename)
log.Printf("| Download | %-21s | %-10s | %s\n", getClientIP(r), filesystem.GetHumanReadableSize(sizeInBytes), filename)
extension := strings.ToLower(filepath.Ext(filename))
mimeType := mime.TypeByExtension(extension)
@@ -190,7 +171,7 @@ func httpGetFilesGetFilename(w http.ResponseWriter, r *http.Request, ps httprout
w.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
}
http.ServeFile(w, r, filePath)
http.ServeFile(w, r, filepath.Join(config.GetPathDataFolder(), filename))
}
func httpGetRoot(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
@@ -214,6 +195,11 @@ func httpPostUpload(w http.ResponseWriter, r *http.Request, ps httprouter.Params
return
}
_, err := filesystem.GetFileListOfDataFolder()
if err != nil {
log.Fatalf("[Error] %v", err)
}
reader, err := r.MultipartReader()
if err != nil {
http.Error(w, fmt.Sprintf("Could not get multipart reader: %v", err), http.StatusBadRequest)
@@ -253,9 +239,9 @@ func httpPostUpload(w http.ResponseWriter, r *http.Request, ps httprouter.Params
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
defer uploadFile.Close()
bytesWritten, err := io.Copy(uploadFile, part)
uploadFile.Close()
if err != nil {
_ = os.Remove(pathToFileInUploadFolder)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)

3
build.sh Executable file
View File

@@ -0,0 +1,3 @@
GOOS=android GOARCH=arm64 go build -o build/ablage-android-arm64 .
GOOS=linux GOARCH=amd64 go build -o build/ablage-linux-amd64 .
GOOS=windows GOARCH=amd64 go build -o build/ablage-windows-amd64.exe .

66
config/banner.go Normal file
View File

@@ -0,0 +1,66 @@
package config
import (
"fmt"
"math"
"strings"
"unicode/utf8"
)
func PrintStartupBanner() {
fmt.Println(getBanner() + "\n")
fmt.Printf("Basic Auth mode: %v\n", GetBasicAuthMode())
fmt.Printf("HTTP mode : %v\n", GetHttpMode())
fmt.Printf("Readonly mode : %v\n", GetReadonlyMode())
fmt.Printf("Sinkhole mode : %v\n", GetSinkholeMode())
fmt.Printf("Path : %s\n", GetPathDataFolder())
if GetBasicAuthMode() {
fmt.Printf("Username : %s\n", GetBasicAuthUsername())
fmt.Printf("Password : %s\n", GetBasicAuthPassword())
}
if GetHttpMode() {
fmt.Printf("Listening on : http://0.0.0.0:%d\n", GetPortToListenOn())
} else {
if pathTLSCertFile == "" || pathTLSKeyFile == "" {
fmt.Printf("TLS cert : self-signed\n")
fmt.Printf("TLS key : self-signed\n")
} else {
fmt.Printf("TLS cert : %s\n", pathTLSCertFile)
fmt.Printf("TLS key : %s\n", pathTLSKeyFile)
}
fmt.Printf("Listening on : https://0.0.0.0:%d\n", GetPortToListenOn())
}
fmt.Println("")
}
func centerTextWithWhitespaces(text string, maxWidth int) string {
textLength := utf8.RuneCountInString(text)
if textLength >= maxWidth {
return text
}
totalPadding := maxWidth - textLength
leftPadding := int(math.Ceil((float64(totalPadding) / 2.0)))
rightPadding := totalPadding - leftPadding
return strings.Repeat(" ", leftPadding) + text + strings.Repeat(" ", rightPadding)
}
func getBanner() string {
return strings.Join(
[]string{
"┌──────────────────────────────────────┐",
"│ Ablage │",
fmt.Sprintf(
"│%s│",
centerTextWithWhitespaces("v"+VersionString, 38),
),
"└──────────────────────────────────────┘",
},
"\n",
)
}

View File

@@ -50,13 +50,13 @@ func generateSelfSignedTLSCertificate() error {
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return err
return fmt.Errorf("Failed to create new x509 certificate: %v", err)
}
cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
key, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return err
return fmt.Errorf("Failed to marshal EC private key: %v", err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: key})
@@ -77,17 +77,17 @@ func loadOrGenerateTLSCertificate() error {
_, err := tls.LoadX509KeyPair(pathTLSCertFile, pathTLSKeyFile)
if err != nil {
return fmt.Errorf("Error: Failed to load TLS certificate or key: %w", err)
return fmt.Errorf("Failed to load TLS certificate or key: %w", err)
}
certData, err := os.ReadFile(pathTLSCertFile)
if err != nil {
return fmt.Errorf("Error: Failed to read TLS certificate file: %w", err)
return fmt.Errorf("Failed to read TLS certificate file: %w", err)
}
keyData, err := os.ReadFile(pathTLSKeyFile)
if err != nil {
return fmt.Errorf("Error: Failed to read TLS key file: %w", err)
return fmt.Errorf("Failed to read TLS key file: %w", err)
}
selfSignedTLSCertificate = certData

View File

@@ -2,67 +2,36 @@ package config
import (
"fmt"
"os"
)
const DefaultBasicAuthUsername string = "ablage"
const DefaultNameDataFolder string = "data"
const DefaultNameUploadFolder string = "upload"
const DefaultNameUploadFolder string = ".upload"
const DefaultPortToListenOn int = 13692
const LengthOfRandomBasicAuthPassword int = 16
const VersionString string = "1.0"
const VersionString string = "1.2"
var randomBasicAuthPassword string = generateRandomPassword()
func Init() {
func Init() error {
err := gatherDefaultPaths()
if err != nil {
panic(err)
return err
}
parseFlags()
err = parseFlags()
if err != nil {
return err
}
if GetReadonlyMode() && GetSinkholeMode() {
fmt.Println("Error: Cannot enable both readonly and sinkhole modes at the same time.")
os.Exit(1)
return fmt.Errorf("Cannot enable both readonly and sinkhole modes at the same time.")
}
err = loadOrGenerateTLSCertificate()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
return err
}
}
func PrintStartupBanner() {
fmt.Println("****************************************")
fmt.Println("* Ablage *")
fmt.Println("****************************************")
fmt.Printf("Version : %s\n", VersionString)
fmt.Printf("Basic Auth mode: %v\n", GetBasicAuthMode())
fmt.Printf("HTTP mode : %v\n", GetHttpMode())
fmt.Printf("Readonly mode : %v\n", GetReadonlyMode())
fmt.Printf("Sinkhole mode : %v\n", GetSinkholeMode())
fmt.Printf("Path : %s\n", GetPathDataFolder())
if GetBasicAuthMode() {
fmt.Printf("Username : %s\n", GetBasicAuthUsername())
fmt.Printf("Password : %s\n", GetBasicAuthPassword())
}
if GetHttpMode() {
fmt.Printf("Listening on : http://0.0.0.0:%d\n", GetPortToListenOn())
} else {
if pathTLSCertFile == "" || pathTLSKeyFile == "" {
fmt.Printf("TLS cert : self-signed\n")
fmt.Printf("TLS key : self-signed\n")
} else {
fmt.Printf("TLS cert : %s\n", pathTLSCertFile)
fmt.Printf("TLS key : %s\n", pathTLSKeyFile)
}
fmt.Printf("Listening on : https://0.0.0.0:%d\n", GetPortToListenOn())
}
fmt.Println("")
return nil
}

View File

@@ -12,7 +12,7 @@ var defaultPathUploadFolder string = ""
func gatherDefaultPaths() error {
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("[Error] Could not determine binary path: %v", err)
return fmt.Errorf("Could not determine binary path: %v", err)
}
defaultPathDataFolder = filepath.Join(filepath.Dir(execPath), DefaultNameDataFolder)

View File

@@ -73,7 +73,7 @@ func generateRandomPassword() string {
return base64.RawURLEncoding.EncodeToString(b)[:LengthOfRandomBasicAuthPassword]
}
func parseFlags() {
func parseFlags() error {
flag.BoolVar(&basicAuthMode, "auth", false, "Enable basic authentication.")
flag.BoolVar(&httpMode, "http", false, "Enable http mode. Nothing will be encrypted.")
flag.BoolVar(&readonlyMode, "readonly", false, "Enable readonly mode. No files can be uploaded or deleted.")
@@ -87,10 +87,25 @@ func parseFlags() {
flag.Parse()
parseFlagValueBasicAuthPassword()
parseFlagValuePortToListenOn()
err := parseFlagValuePortToListenOn()
if err != nil {
return err
}
parseFlagValuePathDataFolder()
parseFlagValuePathTLSCertFile()
parseFlagValuePathTLSKeyFile()
err = parseFlagValuePathTLSCertFile()
if err != nil {
return err
}
err = parseFlagValuePathTLSKeyFile()
if err != nil {
return err
}
return nil
}
func parseFlagValueBasicAuthPassword() {
@@ -106,60 +121,56 @@ func parseFlagValuePathDataFolder() {
return
}
info, err := os.Stat(pathDataFolder)
if err != nil {
pathDataFolder = defaultPathDataFolder
pathUploadFolder = defaultPathUploadFolder
return
}
if !info.IsDir() {
pathDataFolder = defaultPathDataFolder
pathUploadFolder = defaultPathUploadFolder
return
}
pathUploadFolder = filepath.Join(pathDataFolder, DefaultNameUploadFolder)
}
func parseFlagValuePortToListenOn() {
func parseFlagValuePortToListenOn() error {
if portToListenOn < 1 || portToListenOn > 65535 {
portToListenOn = DefaultPortToListenOn
return fmt.Errorf("The port must be between 1 and 65535 (both ports included).")
}
return nil
}
func parseFlagValuePathTLSCertFile() {
func parseFlagValuePathTLSCertFile() error {
if pathTLSCertFile == "" {
pathTLSKeyFile = ""
return
if pathTLSKeyFile != "" {
return fmt.Errorf("Both a certificate and the corresponding key must be provided.")
}
return nil
}
info, err := os.Stat(pathTLSCertFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: Failed to read cert: %v\n", err)
os.Exit(1)
return fmt.Errorf("Failed to read cert: %v", err)
}
if info.IsDir() {
fmt.Fprintf(os.Stderr, "Error: Cert must be a file\n")
os.Exit(1)
return fmt.Errorf("Cert must be a valid file.")
}
return nil
}
func parseFlagValuePathTLSKeyFile() {
func parseFlagValuePathTLSKeyFile() error {
if pathTLSKeyFile == "" {
pathTLSCertFile = ""
return
if pathTLSCertFile != "" {
return fmt.Errorf("Both a certificate and the corresponding key must be provided.")
}
return nil
}
info, err := os.Stat(pathTLSKeyFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: Failed to read key: %v\n", err)
os.Exit(1)
return fmt.Errorf("Failed to read key: %v", err)
}
if info.IsDir() {
fmt.Fprintf(os.Stderr, "Error: Key must be a file\n")
os.Exit(1)
return fmt.Errorf("Key must be a valid file.")
}
return nil
}

View File

@@ -2,6 +2,7 @@ package filesystem
import (
"fmt"
"log"
"os"
"path/filepath"
"regexp"
@@ -10,18 +11,55 @@ import (
"git.0x0001f346.de/andreas/ablage/config"
)
func Init() {
err := prepareDataFolder()
func Init() error {
err := createWriteableFolder(config.GetPathDataFolder())
if err != nil {
fmt.Println("err")
os.Exit(1)
return err
}
err = prepareUploadDir()
err = os.RemoveAll(config.GetPathUploadFolder())
if err != nil {
fmt.Println("err")
os.Exit(1)
return fmt.Errorf("Could not delete upload folder '%s': %v", config.GetPathUploadFolder(), err)
}
err = createWriteableFolder(config.GetPathUploadFolder())
if err != nil {
return err
}
return nil
}
func DeleteFile(filename string) error {
return os.Remove(filepath.Join(config.GetPathDataFolder(), filename))
}
func GetFileListOfDataFolder() (map[string]int64, error) {
entries, err := os.ReadDir(config.GetPathDataFolder())
if err != nil {
return map[string]int64{}, fmt.Errorf(
"Data folder '%s' became unavailable: %v",
config.GetPathDataFolder(),
err,
)
}
files := map[string]int64{}
for _, entry := range entries {
if entry.IsDir() {
continue
}
info, err := entry.Info()
if err != nil {
log.Printf("WARN: Could not read info for '%s': %v", entry.Name(), err)
continue
}
files[info.Name()] = info.Size()
}
return files, nil
}
func GetHumanReadableSize(bytes int64) string {
@@ -77,60 +115,27 @@ func SanitizeFilename(dirtyFilename string) string {
return cleanedFilename + extension
}
func prepareDataFolder() error {
info, err := os.Stat(config.GetPathDataFolder())
func createWriteableFolder(path string) error {
info, err := os.Stat(path)
if os.IsNotExist(err) {
if err := os.Mkdir(config.GetPathDataFolder(), 0755); err != nil {
return fmt.Errorf("Error: Could not create folder '%s': %v", config.GetPathDataFolder(), err)
if err := os.MkdirAll(path, 0755); err != nil {
return fmt.Errorf("Could not create folder '%s': %v", path, err)
}
} else if err != nil {
return fmt.Errorf("Error: Could not access '%s': %v", config.GetPathDataFolder(), err)
return fmt.Errorf("Could not access '%s': %v", path, err)
} else if !info.IsDir() {
return fmt.Errorf("Error: '%s' exists but is not a directory", config.GetPathDataFolder())
return fmt.Errorf("'%s' exists but is not a directory", path)
}
pathTestFile := filepath.Join(config.GetPathDataFolder(), ".write_test")
pathTestFile := filepath.Join(path, ".write_test")
err = os.WriteFile(pathTestFile, []byte("test"), 0644)
if err != nil {
return fmt.Errorf("Error: Could not create test file '%s': %v", pathTestFile, err)
return fmt.Errorf("Could not create test file '%s': %v", pathTestFile, err)
}
err = os.Remove(pathTestFile)
if err != nil {
return fmt.Errorf("Error: Could not delete test file '%s': %v", pathTestFile, err)
}
return nil
}
func prepareUploadDir() error {
info, err := os.Stat(config.GetPathUploadFolder())
if err == nil {
if !info.IsDir() {
return fmt.Errorf("%s exists, but is not a folder", config.GetPathUploadFolder())
}
err = os.RemoveAll(config.GetPathUploadFolder())
if err != nil {
return fmt.Errorf("Error: Could not delete upload folder '%s': %v", config.GetPathUploadFolder(), err)
}
} else if !os.IsNotExist(err) {
return fmt.Errorf("Error: '%s' exists but is somewhat broken", config.GetPathUploadFolder())
}
if err := os.MkdirAll(config.GetPathUploadFolder(), 0755); err != nil {
return fmt.Errorf("Error: Could not create upload folder '%s': %v", config.GetPathUploadFolder(), err)
}
pathTestFile := filepath.Join(config.GetPathUploadFolder(), ".write_test")
err = os.WriteFile(pathTestFile, []byte("test"), 0644)
if err != nil {
return fmt.Errorf("Error: Could not create test file '%s': %v", pathTestFile, err)
}
err = os.Remove(pathTestFile)
if err != nil {
return fmt.Errorf("Error: Could not delete test file '%s': %v", pathTestFile, err)
return fmt.Errorf("Could not delete test file '%s': %v", pathTestFile, err)
}
return nil

23
main.go
View File

@@ -1,13 +1,30 @@
package main
import (
"fmt"
"os"
"git.0x0001f346.de/andreas/ablage/app"
"git.0x0001f346.de/andreas/ablage/config"
"git.0x0001f346.de/andreas/ablage/filesystem"
)
func main() {
config.Init()
filesystem.Init()
app.Init()
err := config.Init()
if err != nil {
fmt.Fprintf(os.Stderr, "[Error] %v\n", err)
os.Exit(1)
}
err = filesystem.Init()
if err != nil {
fmt.Fprintf(os.Stderr, "[Error] %v\n", err)
os.Exit(1)
}
err = app.Init()
if err != nil {
fmt.Fprintf(os.Stderr, "[Error] %v\n", err)
os.Exit(1)
}
}