forked from neri/datatrash
Compare commits
147 Commits
Author | SHA1 | Date |
---|---|---|
neri | 6362f3bd0b | |
neri | 5d02c4beef | |
neri | bb35dd97a2 | |
neri | 3de209ec2e | |
neri | b56f053e50 | |
neri | 9b397ee26a | |
neri | c88a900979 | |
neri | 215bca866f | |
neri | 48fa99002a | |
neri | 40fba9992a | |
neri | 701c86f64c | |
neri | 42a8cb3e0a | |
neri | bcf21b4c79 | |
neri | eaf28f78f0 | |
neri | fbb8f5a7c5 | |
neri | aef400ff51 | |
neri | 6e5892a209 | |
neri | 2ab33b82d0 | |
neri | 804a4fc7ae | |
neri | a221d4e618 | |
neri | 99c3f3694b | |
neri | b28d83a481 | |
neri | af59c099dd | |
neri | 39e72a8eb6 | |
neri | bf2e91a2c5 | |
neri | c33cece59e | |
neri | 0a469ae367 | |
neri | 4cd3cead88 | |
neri | 95c867eb38 | |
neri | 9aa0fff2e2 | |
neri | f7cc3db25a | |
neri | 24c4307ce5 | |
neri | 3da9f1117e | |
neri | 8f0cfdc91b | |
neri | 900d9ac449 | |
neri | e538d93d80 | |
neri | 5a4a73108a | |
neri | f9de6e5164 | |
neri | 16ba5f025e | |
neri | ca56e501a2 | |
neri | b9849153f0 | |
neri | dc2f7ecab0 | |
neri | 2de28ca5db | |
neri | 44843ab222 | |
neri | 756d4b67a0 | |
neri | 7664ba3ec9 | |
neri | 7983557c5a | |
neri | 32fdda0b1e | |
neri | e0ac712a4e | |
neri | 8bc086a524 | |
neri | 171bfc98a9 | |
neri | d7b6d31198 | |
neri | f6628e63da | |
neri | 1dc2fff0c1 | |
neri | e4857cde42 | |
neri | 44aa90369d | |
neri | 1527445857 | |
neri | 4ea8797149 | |
neri | 4496335f50 | |
neri | 96eadb1723 | |
neri | e0b5a3fc65 | |
neri | b414fda39a | |
neri | 53c568082d | |
neri | bf7c762f83 | |
neri | 36b9096325 | |
neri | 24fc93cef7 | |
neri | 7e2d1d8c71 | |
neri | c6a9eae828 | |
neri | d822ae27ae | |
neri | eddbeec7ef | |
neri | becfefb070 | |
neri | d9c92a2827 | |
neri | 7f26e7c456 | |
neri | 29add89e3d | |
neri | 6601e719c9 | |
neri | 1eeff7b0c4 | |
neri | 166d2e09ba | |
neri | d340db3b51 | |
neri | 925a45a011 | |
neri | 8ca0a9cdee | |
neri | 7f650fa89c | |
neri | de43726283 | |
neri | 593f93d7d8 | |
neri | 78ef78f342 | |
neri | 48574b1ec3 | |
neri | 30d059b7af | |
neri | 937f0c439c | |
neri | 48005123de | |
neri | 2fb3b257c2 | |
neri | c320f87961 | |
neri | 530ae31c77 | |
neri | 424af11918 | |
neri | 6b60399c5f | |
neri | ff3bf42342 | |
neri | e568919641 | |
neri | 5a933641a4 | |
neri | 95dacb20b4 | |
neri | a065787487 | |
neri | dfd3387ac6 | |
neri | 2ff464915c | |
neri | b91ef4ab80 | |
neri | 32e411a4d5 | |
neri | 923574e235 | |
neri | 84b4c399ca | |
neri | 922663bf63 | |
neri | f417783821 | |
neri | 8fcc4f19d2 | |
neri | c372db6446 | |
neri | 31a429861d | |
neri | b66b34208c | |
neri | c89c934d04 | |
neri | ad4def1569 | |
neri | 983eafb2e1 | |
neri | f2dfca2b39 | |
neri | f97b3d79be | |
neri | 1c43d70457 | |
neri | dbafc1849e | |
neri | b8fac27511 | |
neri | e49800f05e | |
neri | 313da6b583 | |
neri | 3bed4de127 | |
neri | 77fd25b787 | |
neri | c551f40c7a | |
neri | 2388e2c2ce | |
neri | 1d51c200d6 | |
neri | 3a3174619d | |
neri | 9e38960f00 | |
neri | f100450796 | |
neri | 12544034af | |
neri | 83ea1a15c7 | |
neri | 4efea5e221 | |
neri | 19ae7ff673 | |
neri | dc99b87bcc | |
neri | f5a7ed4213 | |
neri | 0ec9e1f5f1 | |
neri | c9d00db39a | |
neri | 458220df47 | |
neri | 86b2b2bac8 | |
neri | 6c48d97799 | |
neri | 76fd093756 | |
neri | 2eb816134d | |
neri | 64c2567918 | |
neri | b0b03f32a4 | |
neri | b553bd621b | |
neri | c57d15c7e3 | |
neri | e3a7c5329e | |
neri | 180bc08cc5 |
|
@ -0,0 +1,7 @@
|
||||||
|
target/
|
||||||
|
files/
|
||||||
|
README.md
|
||||||
|
screenshot.png
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
|
|
@ -1,2 +1,6 @@
|
||||||
/target
|
/target
|
||||||
/files
|
/files
|
||||||
|
/static/index.html
|
||||||
|
/static/auth-hide.js
|
||||||
|
/.cargo
|
||||||
|
docker-push.sh
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
49
Cargo.toml
49
Cargo.toml
|
@ -1,25 +1,42 @@
|
||||||
[package]
|
[package]
|
||||||
name = "datatrash"
|
name = "datatrash"
|
||||||
version = "0.1.0"
|
version = "2.5.1"
|
||||||
authors = ["neri"]
|
authors = ["neri"]
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "2.0.0", default-features = false, features = [] }
|
actix-web = { version = "4.3.0", default-features = false, features = [
|
||||||
sqlx = { version = "0.3.5", default-features = false, features = [ "runtime-async-std", "postgres", "chrono" ] }
|
"macros",
|
||||||
actix-rt = "1.1.1"
|
"compress-gzip",
|
||||||
env_logger = "0.7.1"
|
"compress-zstd",
|
||||||
log = "0.4.8"
|
] }
|
||||||
actix-files = "0.2.2"
|
sqlx = { version = "0.8.2", default-features = false, features = [
|
||||||
async-std = "1.6.2"
|
"runtime-tokio-rustls",
|
||||||
actix-multipart = "0.2.0"
|
"postgres",
|
||||||
futures = "0.3.5"
|
"time",
|
||||||
rand = "0.7.3"
|
] }
|
||||||
chrono = "0.4.13"
|
env_logger = { version = "0.11.3", default-features = false, features = [
|
||||||
openssl-sys = "*"
|
"humantime",
|
||||||
|
] }
|
||||||
|
log = "0.4.17"
|
||||||
|
actix-files = "0.6.2"
|
||||||
|
tokio = { version = "1.25.0", features = ["rt-multi-thread", "macros", "sync"] }
|
||||||
|
actix-multipart = "0.7.0"
|
||||||
|
futures-util = "0.3.26"
|
||||||
|
rand = "0.8.5"
|
||||||
|
time = "0.3.17"
|
||||||
htmlescape = "0.3.1"
|
htmlescape = "0.3.1"
|
||||||
|
urlencoding = "2.1.2"
|
||||||
|
tree_magic_mini = { version = "3.0.3", features = ["with-gpl-data"] }
|
||||||
|
tree_magic_db = "*"
|
||||||
|
mime = "0.3.16"
|
||||||
|
url = "2.3.1"
|
||||||
|
actix-governor = "0.6.0"
|
||||||
|
lazy_static = "1.4.0"
|
||||||
|
|
||||||
[features]
|
[profile.release]
|
||||||
vendored = ["openssl-sys/vendored"]
|
strip = "symbols"
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
|
36
Dockerfile
36
Dockerfile
|
@ -1,26 +1,30 @@
|
||||||
FROM ekidd/rust-musl-builder as build
|
FROM rust:alpine AS builder
|
||||||
|
|
||||||
USER rust
|
WORKDIR /app
|
||||||
WORKDIR /home/rust/src/
|
RUN apk add musl-dev
|
||||||
RUN USER=rust cargo new datatrash
|
|
||||||
|
|
||||||
WORKDIR /home/rust/src/datatrash
|
RUN cargo init
|
||||||
COPY --chown=rust Cargo.toml Cargo.lock ./
|
COPY Cargo.toml Cargo.lock ./
|
||||||
RUN cargo build --release --features vendored
|
RUN cargo build --release --target=x86_64-unknown-linux-musl
|
||||||
|
|
||||||
COPY --chown=rust src ./src
|
COPY src ./src
|
||||||
COPY --chown=rust static ./static
|
COPY static ./static
|
||||||
COPY --chown=rust template ./template
|
COPY template ./template
|
||||||
COPY --chown=rust init-db.sql ./init-db.sql
|
COPY snippet ./snippet
|
||||||
|
COPY init-db.sql ./init-db.sql
|
||||||
|
COPY mime.types ./mime.types
|
||||||
RUN touch src/main.rs
|
RUN touch src/main.rs
|
||||||
RUN cargo install --path . --features vendored
|
RUN cargo build --release --target=x86_64-unknown-linux-musl
|
||||||
|
RUN strip /app/target/x86_64-unknown-linux-musl/release/datatrash
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
FROM alpine
|
FROM alpine
|
||||||
|
|
||||||
ENV RUST_BACKTRACE "1"
|
WORKDIR /opt/datatrash
|
||||||
|
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/datatrash ./
|
||||||
COPY --from=build /home/rust/.cargo/bin/datatrash .
|
|
||||||
COPY static ./static
|
COPY static ./static
|
||||||
RUN mkdir ./files
|
RUN mkdir ./files
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
ENTRYPOINT ["./datatrash"]
|
ENTRYPOINT ["/opt/datatrash/datatrash"]
|
||||||
|
|
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
75
README.md
75
README.md
|
@ -2,7 +2,60 @@
|
||||||
|
|
||||||
A file and text uploading service with configurable time limit
|
A file and text uploading service with configurable time limit
|
||||||
|
|
||||||
![Application screenshot](./screenshot.png)
|
![Application screenshot showing the web form for file or text upload](./screenshot.png)
|
||||||
|
|
||||||
|
## running
|
||||||
|
|
||||||
|
For running on docker, use the provided `docker-compose.yml.sample` and adapt it to your needs.
|
||||||
|
To run the software directly, use the compiling instructions below.
|
||||||
|
|
||||||
|
## config
|
||||||
|
|
||||||
|
- The `static` files directory needs to be next to the binary.
|
||||||
|
- The `static` directory – sadly – needs to be writable
|
||||||
|
- On startup the `index.html` will be generated based on the config
|
||||||
|
- The maximum filename length is 255
|
||||||
|
|
||||||
|
### General configuration
|
||||||
|
|
||||||
|
| environment variable | default value | description |
|
||||||
|
| ---------------------------- | -------------- | ---------------------------------------------- |
|
||||||
|
| STATIC_DIR | ./static | directory to generate "static" files into |
|
||||||
|
| FILES_DIR | ./files | directory to save uploaded files into |
|
||||||
|
| UPLOAD_MAX_BYTES | 8388608 (8MiB) | maximum size for uploaded files |
|
||||||
|
| BIND_ADDRESS | 0.0.0.0:8000 | address to bind the server to |
|
||||||
|
| RATE_LIMIT | true | whether download rate should be limited |
|
||||||
|
| RATE_LIMIT_PROXIED | false | whether rate limit should read x-forwarded-for |
|
||||||
|
| RATE_LIMIT_REPLENISH_SECONDS | 60 | seconds to wait between requests |
|
||||||
|
| RATE_LIMIT_BURST | 480 | allowed request burst |
|
||||||
|
| ABUSE_MAIL | | email address to report abuse to |
|
||||||
|
|
||||||
|
### Database configuration
|
||||||
|
|
||||||
|
| environment variable | default value |
|
||||||
|
| -------------------- | ------------- |
|
||||||
|
| DATABASE_URL | |
|
||||||
|
| DATABASE_USER | |
|
||||||
|
| DATABASE_PASS | |
|
||||||
|
| DATABASE_HOST | localhost |
|
||||||
|
| DATABASE_NAME | datatrash |
|
||||||
|
|
||||||
|
### No auth limits configuration
|
||||||
|
|
||||||
|
Require authentication for certain uploads
|
||||||
|
|
||||||
|
- The password is provided as plain text
|
||||||
|
- Uploads with longer validity than NO_AUTH_MAX_TIME require authentication
|
||||||
|
- Uploads larger than NO_AUTH_LARGE_FILE_SIZE require auth when they are valid for longer than
|
||||||
|
NO_AUTH_LARGE_FILE_MAX_TIME
|
||||||
|
- All times are in seconds, the size is in bytes
|
||||||
|
|
||||||
|
| environment variable | default value |
|
||||||
|
| --------------------------- | ------------- |
|
||||||
|
| AUTH_PASSWORD | |
|
||||||
|
| NO_AUTH_MAX_TIME | |
|
||||||
|
| NO_AUTH_LARGE_FILE_MAX_TIME | |
|
||||||
|
| NO_AUTH_LARGE_FILE_SIZE | |
|
||||||
|
|
||||||
## compiling
|
## compiling
|
||||||
|
|
||||||
|
@ -16,23 +69,3 @@ or
|
||||||
docker build -t datatrash .
|
docker build -t datatrash .
|
||||||
docker cp datatrash:/home/rust/.cargo/bin/datatrash datatrash
|
docker cp datatrash:/home/rust/.cargo/bin/datatrash datatrash
|
||||||
```
|
```
|
||||||
|
|
||||||
or, to just run it in docker
|
|
||||||
|
|
||||||
```sh
|
|
||||||
docker-compose up -d --build
|
|
||||||
```
|
|
||||||
|
|
||||||
## running & config
|
|
||||||
|
|
||||||
The static files directory needs to be next to the binary.
|
|
||||||
|
|
||||||
| environment variable | default value |
|
|
||||||
| -------------------- | --------------------- |
|
|
||||||
| DATABASE_URL | postresql://localhost |
|
|
||||||
| SERVER_URL | http://loalhost:8000 |
|
|
||||||
| FILES_DIR | ./files |
|
|
||||||
| UPLOAD_MAX_BYTES | 8388608 (8MiB) |
|
|
||||||
| BIND_ADDRESS | 0.0.0.0:8000 |
|
|
||||||
|
|
||||||
The maximum filename length is 255
|
|
||||||
|
|
|
@ -0,0 +1,72 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||||
|
|
||||||
|
<svg
|
||||||
|
width="20.040001mm"
|
||||||
|
height="32.470001mm"
|
||||||
|
viewBox="0 0 20.040001 32.470002"
|
||||||
|
version="1.1"
|
||||||
|
id="svg5"
|
||||||
|
inkscape:version="1.2.2 (b0a8486541, 2022-12-01)"
|
||||||
|
sodipodi:docname="datatrash-favicon.svg"
|
||||||
|
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||||
|
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg">
|
||||||
|
<sodipodi:namedview
|
||||||
|
id="namedview7"
|
||||||
|
pagecolor="#505050"
|
||||||
|
bordercolor="#eeeeee"
|
||||||
|
borderopacity="1"
|
||||||
|
inkscape:showpageshadow="0"
|
||||||
|
inkscape:pageopacity="0"
|
||||||
|
inkscape:pagecheckerboard="0"
|
||||||
|
inkscape:deskcolor="#505050"
|
||||||
|
inkscape:document-units="mm"
|
||||||
|
showgrid="false"
|
||||||
|
showguides="false"
|
||||||
|
inkscape:zoom="4"
|
||||||
|
inkscape:cx="6.875"
|
||||||
|
inkscape:cy="74.375"
|
||||||
|
inkscape:window-width="1661"
|
||||||
|
inkscape:window-height="1354"
|
||||||
|
inkscape:window-x="0"
|
||||||
|
inkscape:window-y="0"
|
||||||
|
inkscape:window-maximized="1"
|
||||||
|
inkscape:current-layer="layer1" />
|
||||||
|
<defs
|
||||||
|
id="defs2" />
|
||||||
|
<g
|
||||||
|
inkscape:label="Layer 1"
|
||||||
|
inkscape:groupmode="layer"
|
||||||
|
id="layer1">
|
||||||
|
<path
|
||||||
|
id="path27079"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0,3.4728255 19.692763,1.0182368e-8 20.04,1.9695374 0.34723656,5.4423629 Z" />
|
||||||
|
<path
|
||||||
|
id="path27076"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0.42165307,7.3209983 H 19.618346 V 9.3209188 H 0.42165307 Z" />
|
||||||
|
<path
|
||||||
|
id="path27073"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0.82158379,12.920776 H 19.218416 v 1.99992 H 0.82158379 Z" />
|
||||||
|
<path
|
||||||
|
id="path27070"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 1.2215157,18.520553 H 18.818485 v 1.999921 H 1.2215157 Z" />
|
||||||
|
<path
|
||||||
|
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0;stroke-dasharray:none;paint-order:normal"
|
||||||
|
d="m 6.9813387,24.122065 a 4.999139,4.9998014 0 0 1 2.3095393,1.999798 h 9.129654 v -1.999798 z"
|
||||||
|
id="path27067" />
|
||||||
|
<path
|
||||||
|
id="path27064"
|
||||||
|
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0;stroke-dasharray:none;paint-order:normal"
|
||||||
|
d="M 9.9160553,29.7184 A 4.999139,4.9998014 0 0 1 9.0170401,31.718199 H 18.017524 V 29.7184 Z" />
|
||||||
|
<path
|
||||||
|
id="path27061"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 8.7702156,28.720149 A 3.7493543,3.749851 0 0 1 5.0208613,32.47 3.7493543,3.749851 0 0 1 1.271507,28.720149 3.7493543,3.749851 0 0 1 5.0208613,24.970298 3.7493543,3.749851 0 0 1 8.7702156,28.720149 Z" />
|
||||||
|
</g>
|
||||||
|
</svg>
|
After Width: | Height: | Size: 2.7 KiB |
|
@ -1,15 +0,0 @@
|
||||||
version: "3.3"
|
|
||||||
services:
|
|
||||||
datatrash:
|
|
||||||
build: .
|
|
||||||
environment:
|
|
||||||
DATABASE_URL: 'postgresql://admin:secure@postgres'
|
|
||||||
ports:
|
|
||||||
- '8000:8000'
|
|
||||||
postgres:
|
|
||||||
image: postgres
|
|
||||||
environment:
|
|
||||||
POSTGRES_USER: admin
|
|
||||||
POSTGRES_PASSWORD: secure
|
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,33 @@
|
||||||
|
version: "3.3"
|
||||||
|
services:
|
||||||
|
datatrash:
|
||||||
|
build: .
|
||||||
|
container_name: datatrash
|
||||||
|
volumes:
|
||||||
|
- /var/datatrash/files:/opt/datatrash/files
|
||||||
|
environment:
|
||||||
|
DATABASE_HOST: db
|
||||||
|
DATABASE_USER: datatrash
|
||||||
|
DATABASE_PASS: database_password
|
||||||
|
# UPLOAD_MAX_BYTES: 1073741824 # 1 GiB
|
||||||
|
# BIND_ADDRESS: 0.0.0.0:8000
|
||||||
|
# FILES_DIR: /opt/datatrash/files
|
||||||
|
# AUTH_PASSWORD: auth_password
|
||||||
|
# NO_AUTH_MAX_TIME: 604800
|
||||||
|
# NO_AUTH_LARGE_FILE_MAX_TIME: 1800
|
||||||
|
# NO_AUTH_LARGE_FILE_SIZE: 10485760
|
||||||
|
ports:
|
||||||
|
- "80:8000"
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
|
db:
|
||||||
|
image: postgres
|
||||||
|
container_name: datatrash-db
|
||||||
|
volumes:
|
||||||
|
- /var/datatrash/db:/var/lib/postgresql/data
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: datatrash
|
||||||
|
POSTGRES_USER: datatrash
|
||||||
|
POSTGRES_PASSWORD: database_password
|
||||||
|
restart: unless-stopped
|
11
init-db.sql
11
init-db.sql
|
@ -1,8 +1,17 @@
|
||||||
CREATE TABLE IF NOT EXISTS files (
|
CREATE TABLE IF NOT EXISTS files (
|
||||||
id serial,
|
id serial,
|
||||||
file_id varchar(255) not null,
|
file_id varchar(255) not null unique,
|
||||||
file_name varchar(255) not null,
|
file_name varchar(255) not null,
|
||||||
valid_till timestamp not null,
|
valid_till timestamp not null,
|
||||||
kind varchar(255) not null,
|
kind varchar(255) not null,
|
||||||
primary key (id)
|
primary key (id)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
ALTER TABLE files ADD COLUMN IF NOT EXISTS delete_on_download boolean;
|
||||||
|
ALTER TABLE files ALTER COLUMN delete_on_download set not null;
|
||||||
|
ALTER TABLE files ALTER COLUMN valid_till TYPE timestamptz;
|
||||||
|
ALTER TABLE files ADD COLUMN IF NOT EXISTS content_type varchar(255) not null
|
||||||
|
GENERATED ALWAYS AS (CASE WHEN kind = 'text' THEN 'text/plain' ELSE 'application/octet-stream' END) STORED;
|
||||||
|
ALTER TABLE files ALTER COLUMN content_type DROP EXPRESSION IF EXISTS;
|
||||||
|
ALTER TABLE files DROP COLUMN IF EXISTS kind;
|
||||||
|
ALTER TABLE files ALTER COLUMN file_name DROP NOT NULL;
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
BIN
screenshot.png
BIN
screenshot.png
Binary file not shown.
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 33 KiB |
|
@ -0,0 +1,6 @@
|
||||||
|
|
||||||
|
<a
|
||||||
|
href="mailto:{abusemail}?subject=Inhaltsmeldung%20datatrash&body=Dies%20ist%20eine%20Inhaltsmeldung%20f%C3%BCr%20eine%20Datei%20auf%20deiner%20datatrash-Instanz.%0ADie%20illegale%20Datei%20ist%20aktuell%20unter%20folgender%20URL%20abrufbar%3A%0A%0A{url}"
|
||||||
|
>
|
||||||
|
inhalt melden
|
||||||
|
</a>
|
|
@ -0,0 +1,9 @@
|
||||||
|
|
||||||
|
<div id="password-input">
|
||||||
|
<label for="password">
|
||||||
|
passwort benötigt (>{auth_time} oder datei >{auth_large_size} und >{auth_large_time})
|
||||||
|
</label>
|
||||||
|
<br />
|
||||||
|
<input id="password" name="password" type="password" />
|
||||||
|
</div>
|
||||||
|
<script nonce="{script_nonce}" src="/static/auth-hide.js"></script>
|
|
@ -0,0 +1 @@
|
||||||
|
<h2>{file_name}</h2>
|
|
@ -0,0 +1 @@
|
||||||
|
(maximal {max_size})
|
|
@ -0,0 +1,96 @@
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use time::ext::NumericalDuration;
|
||||||
|
use time::Duration;
|
||||||
|
use tokio::fs;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Config {
|
||||||
|
pub static_dir: PathBuf,
|
||||||
|
pub files_dir: PathBuf,
|
||||||
|
pub max_file_size: Option<u64>,
|
||||||
|
pub no_auth_limits: Option<NoAuthLimits>,
|
||||||
|
pub enable_rate_limit: bool,
|
||||||
|
pub proxied: bool,
|
||||||
|
pub rate_limit_replenish_seconds: u64,
|
||||||
|
pub rate_limit_burst: u32,
|
||||||
|
pub abuse_mail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct NoAuthLimits {
|
||||||
|
pub auth_password: String,
|
||||||
|
pub max_time: Duration,
|
||||||
|
pub large_file_max_time: Duration,
|
||||||
|
pub large_file_size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn from_env() -> Config {
|
||||||
|
let max_file_size = env::var("UPLOAD_MAX_BYTES")
|
||||||
|
.ok()
|
||||||
|
.and_then(|variable| variable.parse().ok())
|
||||||
|
.or(Some(8 * 1024 * 1024))
|
||||||
|
.filter(|&max_file_size| max_file_size != 0);
|
||||||
|
|
||||||
|
let static_dir =
|
||||||
|
PathBuf::from(env::var("STATIC_DIR").unwrap_or_else(|_| "./static".to_owned()));
|
||||||
|
let files_dir = PathBuf::from(env::var("FILES_DIR").unwrap_or_else(|_| "./files".to_owned()));
|
||||||
|
fs::create_dir_all(&files_dir)
|
||||||
|
.await
|
||||||
|
.expect("could not create directory for storing files");
|
||||||
|
|
||||||
|
let no_auth_limits = get_no_auth_limits();
|
||||||
|
|
||||||
|
// default to 480requests/8h
|
||||||
|
let enable_rate_limit = matches!(env::var("RATE_LIMIT").as_deref(), Ok("true") | Err(_));
|
||||||
|
let proxied = env::var("RATE_LIMIT_PROXIED").as_deref() == Ok("true");
|
||||||
|
let rate_limit_replenish_seconds = env::var("RATE_LIMIT_REPLENISH_SECONDS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|rate_limit| rate_limit.parse().ok())
|
||||||
|
.unwrap_or(60);
|
||||||
|
let rate_limit_burst = env::var("RATE_LIMIT_BURST")
|
||||||
|
.ok()
|
||||||
|
.and_then(|burst| burst.parse().ok())
|
||||||
|
.unwrap_or(480);
|
||||||
|
let abuse_mail = env::var("ABUSE_MAIL").ok();
|
||||||
|
|
||||||
|
Config {
|
||||||
|
static_dir,
|
||||||
|
files_dir,
|
||||||
|
max_file_size,
|
||||||
|
no_auth_limits,
|
||||||
|
enable_rate_limit,
|
||||||
|
proxied,
|
||||||
|
rate_limit_replenish_seconds,
|
||||||
|
rate_limit_burst,
|
||||||
|
abuse_mail,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_no_auth_limits() -> Option<NoAuthLimits> {
|
||||||
|
match (
|
||||||
|
env::var("AUTH_PASSWORD").ok(),
|
||||||
|
env_number::<i64>("NO_AUTH_MAX_TIME"),
|
||||||
|
env_number::<i64>("NO_AUTH_LARGE_FILE_MAX_TIME"),
|
||||||
|
env_number("NO_AUTH_LARGE_FILE_SIZE"),
|
||||||
|
) {
|
||||||
|
(Some(auth_password), Some(max_time), Some(large_file_max_time), Some(large_file_size)) => {
|
||||||
|
Some(NoAuthLimits {
|
||||||
|
auth_password,
|
||||||
|
max_time: max_time.seconds(),
|
||||||
|
large_file_max_time: large_file_max_time.seconds(),
|
||||||
|
large_file_size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
(None, None, None, None) => None,
|
||||||
|
_ => {
|
||||||
|
panic!("Incomplete NO_AUTH configuration: All environment variables must be specified")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_number<T: FromStr>(variable: &str) -> Option<T> {
|
||||||
|
env::var(variable).ok().and_then(|n| n.parse::<T>().ok())
|
||||||
|
}
|
|
@ -0,0 +1,44 @@
|
||||||
|
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||||
|
use std::env;
|
||||||
|
use time::ext::NumericalStdDuration;
|
||||||
|
|
||||||
|
pub async fn setup() -> PgPool {
|
||||||
|
let conn_url = &get_db_url();
|
||||||
|
log::info!("Using Connection string {}", conn_url);
|
||||||
|
|
||||||
|
let pool = PgPoolOptions::new()
|
||||||
|
.max_connections(5)
|
||||||
|
.acquire_timeout(5.std_seconds())
|
||||||
|
.connect(conn_url)
|
||||||
|
.await
|
||||||
|
.expect("could not create db pool");
|
||||||
|
|
||||||
|
for query in include_str!("../init-db.sql").split_inclusive(';') {
|
||||||
|
sqlx::query(query)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.expect("could not initialize database schema");
|
||||||
|
}
|
||||||
|
|
||||||
|
pool
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_db_url() -> String {
|
||||||
|
if let Ok(database_url) = env::var("DATABASE_URL") {
|
||||||
|
return database_url;
|
||||||
|
}
|
||||||
|
|
||||||
|
let auth = if let Ok(user) = env::var("DATABASE_USER") {
|
||||||
|
if let Ok(pass) = env::var("DATABASE_PASS") {
|
||||||
|
format!("{user}:{pass}@")
|
||||||
|
} else {
|
||||||
|
format!("{user}@")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
|
||||||
|
let host = env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string());
|
||||||
|
let name = env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string());
|
||||||
|
format!("postgresql://{auth}{host}/{name}")
|
||||||
|
}
|
134
src/deleter.rs
134
src/deleter.rs
|
@ -1,51 +1,115 @@
|
||||||
use async_std::{fs, path::PathBuf, sync::Receiver, task};
|
use futures_util::TryStreamExt;
|
||||||
use chrono::{prelude::*, Duration};
|
use sqlx::{postgres::PgPool, Row};
|
||||||
use futures::future::FutureExt;
|
use std::cmp::max;
|
||||||
use sqlx::{postgres::PgPool, Cursor, Row};
|
use std::error::Error;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use time::ext::NumericalStdDuration;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use tokio::fs;
|
||||||
|
use tokio::sync::mpsc::Receiver;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
|
||||||
pub(crate) async fn delete_old_files(receiver: Receiver<()>, db: PgPool, files_dir: PathBuf) {
|
pub(crate) async fn delete_old_files(
|
||||||
|
mut receiver: Receiver<()>,
|
||||||
|
db: PgPool,
|
||||||
|
files_dir: PathBuf,
|
||||||
|
) -> Result<(), DeletionError> {
|
||||||
loop {
|
loop {
|
||||||
wait_for_file_expiry(&receiver, &db).await;
|
wait_for_file_expiry(&mut receiver, &db).await?;
|
||||||
|
|
||||||
let now = Local::now().naive_local();
|
let now = OffsetDateTime::now_utc();
|
||||||
let mut cursor = sqlx::query("SELECT file_id FROM files WHERE files.valid_till < $1")
|
let mut rows = sqlx::query("SELECT file_id FROM files WHERE files.valid_till < $1")
|
||||||
.bind(now)
|
.bind(now)
|
||||||
.fetch(&db);
|
.fetch(&db);
|
||||||
while let Some(row) = cursor.next().await.expect("could not load expired files") {
|
while let Some(row) = rows.try_next().await? {
|
||||||
let file_id: String = row.get("file_id");
|
let file_id: String = row.try_get("file_id").expect("we selected this column");
|
||||||
let mut path = files_dir.clone();
|
delete_content(&file_id, &files_dir).await?;
|
||||||
path.push(&file_id);
|
|
||||||
if path.exists().await {
|
|
||||||
log::info!("delete file {}", file_id);
|
|
||||||
fs::remove_file(&path).await.expect("could not delete file");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
sqlx::query("DELETE FROM files WHERE valid_till < $1")
|
sqlx::query("DELETE FROM files WHERE valid_till < $1")
|
||||||
.bind(now)
|
.bind(now)
|
||||||
.execute(&db)
|
.execute(&db)
|
||||||
.await
|
.await?;
|
||||||
.expect("could not delete expired files from database");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wait_for_file_expiry(receiver: &Receiver<()>, db: &PgPool) {
|
pub(crate) async fn delete_by_id(
|
||||||
let mut cursor = sqlx::query("SELECT MIN(valid_till) as min from files").fetch(db);
|
db: &PgPool,
|
||||||
let row = cursor
|
file_id: &str,
|
||||||
.next()
|
files_dir: &Path,
|
||||||
.await
|
) -> Result<(), sqlx::Error> {
|
||||||
.expect("could not fetch expiring files from database")
|
delete_content(file_id, files_dir).await?;
|
||||||
.expect("postgres min did not return any row");
|
sqlx::query("DELETE FROM files WHERE file_id = $1")
|
||||||
let valid_till: Option<NaiveDateTime> = row.get("min");
|
.bind(file_id)
|
||||||
let next_timeout = match valid_till {
|
.execute(db)
|
||||||
Some(valid_till) => valid_till.signed_duration_since(Local::now().naive_local()),
|
.await?;
|
||||||
None => Duration::days(1),
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_content(file_id: &str, files_dir: &Path) -> Result<(), std::io::Error> {
|
||||||
|
let path = files_dir.join(file_id);
|
||||||
|
if fs::try_exists(&path).await? {
|
||||||
|
fs::remove_file(&path).await?;
|
||||||
|
log::info!("deleted file {}", file_id);
|
||||||
|
} else {
|
||||||
|
log::warn!("expiring file {} was missing from the filesystem", file_id);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_for_file_expiry(
|
||||||
|
receiver: &mut Receiver<()>,
|
||||||
|
db: &PgPool,
|
||||||
|
) -> Result<(), DeletionError> {
|
||||||
|
let valid_till: (Option<OffsetDateTime>,) =
|
||||||
|
sqlx::query_as("SELECT MIN(valid_till) as min from files")
|
||||||
|
.fetch_one(db)
|
||||||
|
.await?;
|
||||||
|
let next_timeout = match valid_till.0 {
|
||||||
|
Some(valid_till) => (max(
|
||||||
|
0,
|
||||||
|
valid_till.unix_timestamp() - OffsetDateTime::now_utc().unix_timestamp(),
|
||||||
|
) as u64)
|
||||||
|
.std_seconds(),
|
||||||
|
None => 1_u64.std_days(),
|
||||||
};
|
};
|
||||||
let positive_timeout = next_timeout
|
let _ = timeout(next_timeout, receiver.recv()).await;
|
||||||
.to_std()
|
Ok(())
|
||||||
.unwrap_or_else(|_| std::time::Duration::from_secs(0));
|
}
|
||||||
futures::select! {
|
|
||||||
_ = task::sleep(positive_timeout).fuse() => {}
|
#[derive(Debug)]
|
||||||
_ = receiver.recv().fuse() => {}
|
pub enum DeletionError {
|
||||||
|
Db(sqlx::Error),
|
||||||
|
Fs(std::io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sqlx::Error> for DeletionError {
|
||||||
|
fn from(value: sqlx::Error) -> Self {
|
||||||
|
DeletionError::Db(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<std::io::Error> for DeletionError {
|
||||||
|
fn from(value: std::io::Error) -> Self {
|
||||||
|
DeletionError::Fs(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Display for DeletionError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
DeletionError::Db(_) => write!(f, "Failed to fetch expired files from database"),
|
||||||
|
DeletionError::Fs(_) => write!(f, "Failed to delete file from filesystem"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for DeletionError {
|
||||||
|
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||||
|
match self {
|
||||||
|
DeletionError::Db(err) => Some(err),
|
||||||
|
DeletionError::Fs(err) => Some(err),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,234 @@
|
||||||
|
use std::{io::ErrorKind, time::SystemTime};
|
||||||
|
|
||||||
|
use actix_files::NamedFile;
|
||||||
|
use actix_web::{
|
||||||
|
error,
|
||||||
|
http::header::{
|
||||||
|
Accept, CacheControl, CacheDirective, Charset, ContentDisposition, DispositionParam,
|
||||||
|
DispositionType, Expires, ExtendedValue, Header, HeaderValue, HttpDate, TryIntoHeaderValue,
|
||||||
|
ACCEPT, CACHE_CONTROL, CONTENT_TYPE, EXPIRES, VARY,
|
||||||
|
},
|
||||||
|
web, Error, HttpRequest, HttpResponse,
|
||||||
|
};
|
||||||
|
use mime::{Mime, APPLICATION_OCTET_STREAM, TEXT_HTML};
|
||||||
|
use sqlx::postgres::PgPool;
|
||||||
|
use std::path::Path;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use tokio::fs;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
config::Config,
|
||||||
|
deleter,
|
||||||
|
file_info::{self, FileInfo},
|
||||||
|
mime_relations, template,
|
||||||
|
};
|
||||||
|
|
||||||
|
const TEXT_VIEW_SIZE_LIMIT: u64 = 512 * 1024; // 512KiB
|
||||||
|
|
||||||
|
enum ViewType {
|
||||||
|
Raw,
|
||||||
|
Download,
|
||||||
|
Html,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn download(
|
||||||
|
req: HttpRequest,
|
||||||
|
db: web::Data<PgPool>,
|
||||||
|
config: web::Data<Config>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let id = req.match_info().query("id");
|
||||||
|
let file_info = file_info::find_by_id(id, &db)
|
||||||
|
.await
|
||||||
|
.map_err(|db_err| {
|
||||||
|
log::error!("could not run select statement {:?}", db_err);
|
||||||
|
error::ErrorInternalServerError("could not run select statement")
|
||||||
|
})?
|
||||||
|
.ok_or_else(|| error::ErrorNotFound("file does not exist or has expired"))?;
|
||||||
|
let delete = file_info.delete_on_download;
|
||||||
|
let valid_till = file_info.valid_till;
|
||||||
|
let path = config.files_dir.join(&file_info.file_id);
|
||||||
|
|
||||||
|
let mut response = match get_view_type(&file_info, &path, &req).await {
|
||||||
|
ViewType::Raw => build_file_response(file_info, &path, false, &req),
|
||||||
|
ViewType::Download => build_file_response(file_info, &path, true, &req),
|
||||||
|
ViewType::Html => build_html_response(file_info, &path, &config, &req).await,
|
||||||
|
}?;
|
||||||
|
|
||||||
|
insert_cache_headers(&mut response, valid_till);
|
||||||
|
|
||||||
|
if delete {
|
||||||
|
deleter::delete_by_id(&db, id, &config.files_dir)
|
||||||
|
.await
|
||||||
|
.map_err(|db_err| {
|
||||||
|
log::error!("could not delete file {:?}", db_err);
|
||||||
|
error::ErrorInternalServerError("could not delete file")
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_view_type(file_info: &FileInfo, file_path: &Path, req: &HttpRequest) -> ViewType {
|
||||||
|
if file_info.delete_on_download || req.query_string().contains("dl") {
|
||||||
|
return ViewType::Download;
|
||||||
|
}
|
||||||
|
if req.query_string().contains("raw") {
|
||||||
|
return ViewType::Raw;
|
||||||
|
}
|
||||||
|
if !mime_relations::matches_text(&file_info.content_type) {
|
||||||
|
return ViewType::Raw;
|
||||||
|
}
|
||||||
|
if get_file_size(file_path).await >= TEXT_VIEW_SIZE_LIMIT {
|
||||||
|
return ViewType::Raw;
|
||||||
|
}
|
||||||
|
if let Ok(accept) = Accept::parse(req) {
|
||||||
|
for accept_mime in accept.ranked() {
|
||||||
|
if accept_mime == TEXT_HTML {
|
||||||
|
return ViewType::Html;
|
||||||
|
}
|
||||||
|
if mime_matches(&accept_mime, &file_info.content_type) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ViewType::Raw
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mime_matches(accept: &Mime, content: &Mime) -> bool {
|
||||||
|
let type_matches = accept.type_() == content.type_() || accept.type_() == mime::STAR;
|
||||||
|
let subtype_matches = accept.subtype() == content.subtype() || accept.subtype() == mime::STAR;
|
||||||
|
type_matches && subtype_matches
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_file_size(file_path: &Path) -> u64 {
|
||||||
|
fs::metadata(file_path)
|
||||||
|
.await
|
||||||
|
.map(|metadata| metadata.len())
|
||||||
|
.unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn build_html_response(
|
||||||
|
file_info: FileInfo,
|
||||||
|
path: &Path,
|
||||||
|
config: &Config,
|
||||||
|
req: &HttpRequest,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let content = match fs::read_to_string(path).await {
|
||||||
|
Ok(content) => content,
|
||||||
|
Err(file_err) if file_err.kind() == ErrorKind::InvalidData => {
|
||||||
|
// content may not be valid UTF-8, try to return the raw file instead
|
||||||
|
return build_file_response(file_info, path, false, req);
|
||||||
|
}
|
||||||
|
Err(file_err) => {
|
||||||
|
log::error!("file could not be read: {:?}", file_err);
|
||||||
|
return Err(error::ErrorInternalServerError(
|
||||||
|
"this file should be here but could not be found",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let html_view =
|
||||||
|
template::build_html_view_template(&content, file_info.file_name.as_deref(), req, config);
|
||||||
|
Ok(HttpResponse::Ok()
|
||||||
|
.content_type(TEXT_HTML.to_string())
|
||||||
|
.body(html_view))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_file_response(
|
||||||
|
file_info: FileInfo,
|
||||||
|
path: &Path,
|
||||||
|
download: bool,
|
||||||
|
req: &HttpRequest,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let file_name: String = file_info.file_name.unwrap_or_else(|| {
|
||||||
|
let file_id = file_info.file_id;
|
||||||
|
let extension = mime_relations::get_extension(&file_info.content_type).unwrap_or("txt");
|
||||||
|
format!("{file_id}.{extension}")
|
||||||
|
});
|
||||||
|
let content_disposition = ContentDisposition {
|
||||||
|
disposition: if download {
|
||||||
|
DispositionType::Attachment
|
||||||
|
} else {
|
||||||
|
DispositionType::Inline
|
||||||
|
},
|
||||||
|
parameters: get_disposition_params(file_name),
|
||||||
|
};
|
||||||
|
let file = NamedFile::open(path)
|
||||||
|
.map_err(|file_err| {
|
||||||
|
log::error!("file could not be read: {:?}", file_err);
|
||||||
|
error::ErrorInternalServerError("this file should be here but could not be found")
|
||||||
|
})?
|
||||||
|
.set_content_type(file_info.content_type)
|
||||||
|
.set_content_disposition(content_disposition);
|
||||||
|
|
||||||
|
let mut response = file.into_response(req);
|
||||||
|
append_security_headers(&mut response, req);
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_disposition_params(filename: String) -> Vec<DispositionParam> {
|
||||||
|
if !filename.is_ascii() {
|
||||||
|
vec![
|
||||||
|
DispositionParam::Filename(filename.clone()),
|
||||||
|
DispositionParam::FilenameExt(ExtendedValue {
|
||||||
|
charset: Charset::Ext(String::from("UTF-8")),
|
||||||
|
language_tag: None,
|
||||||
|
value: filename.into_bytes(),
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
vec![DispositionParam::Filename(filename)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALLOWED_CONTEXTS: [&str; 6] = ["audio", "document", "empty", "font", "image", "video"];
|
||||||
|
|
||||||
|
fn append_security_headers(response: &mut HttpResponse, req: &HttpRequest) {
|
||||||
|
// if the browser is trying to fetch this resource in a secure context pretend the response is
|
||||||
|
// just binary data so it won't be executed
|
||||||
|
let sec_fetch_dest = req
|
||||||
|
.headers()
|
||||||
|
.get("sec-fetch-dest")
|
||||||
|
.map(|v| v.to_str().unwrap_or("unknown"));
|
||||||
|
if sec_fetch_dest.is_some_and(|sec_fetch_dest| !ALLOWED_CONTEXTS.contains(&sec_fetch_dest)) {
|
||||||
|
response.headers_mut().insert(
|
||||||
|
CONTENT_TYPE,
|
||||||
|
HeaderValue::from_str(APPLICATION_OCTET_STREAM.as_ref())
|
||||||
|
.expect("mime type can be encoded to header value"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// the response varies based on these request headers
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.append(VARY, HeaderValue::from_static("sec-fetch-dest"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_cache_headers(response: &mut HttpResponse, valid_till: OffsetDateTime) {
|
||||||
|
if response.status().is_success() {
|
||||||
|
let valid_duration = valid_till - OffsetDateTime::now_utc();
|
||||||
|
let valid_cache_seconds =
|
||||||
|
valid_duration.whole_seconds().clamp(0, i64::from(u32::MAX)) as u32;
|
||||||
|
response.headers_mut().insert(
|
||||||
|
CACHE_CONTROL,
|
||||||
|
CacheControl(vec![
|
||||||
|
CacheDirective::Public,
|
||||||
|
CacheDirective::MustRevalidate,
|
||||||
|
CacheDirective::MaxAge(valid_cache_seconds),
|
||||||
|
CacheDirective::NoTransform,
|
||||||
|
CacheDirective::Extension("immutable".to_owned(), None),
|
||||||
|
])
|
||||||
|
.try_into_value()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
response.headers_mut().insert(
|
||||||
|
EXPIRES,
|
||||||
|
Expires(HttpDate::from(
|
||||||
|
SystemTime::now() + std::time::Duration::from_secs(valid_cache_seconds.into()),
|
||||||
|
))
|
||||||
|
.try_into_value()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.append(VARY, HeaderValue::from_name(ACCEPT));
|
||||||
|
}
|
|
@ -0,0 +1,69 @@
|
||||||
|
use mime::{Mime, APPLICATION_OCTET_STREAM};
|
||||||
|
use sqlx::{postgres::PgRow, FromRow, Row};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
use crate::multipart::UploadConfig;
|
||||||
|
|
||||||
|
pub struct FileInfo {
|
||||||
|
pub file_id: String,
|
||||||
|
pub file_name: Option<String>,
|
||||||
|
pub valid_till: OffsetDateTime,
|
||||||
|
pub content_type: Mime,
|
||||||
|
pub delete_on_download: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FileInfo {
|
||||||
|
pub fn new(file_id: String, upload_config: UploadConfig) -> Self {
|
||||||
|
Self {
|
||||||
|
file_id,
|
||||||
|
file_name: upload_config.original_name,
|
||||||
|
valid_till: upload_config.valid_till,
|
||||||
|
content_type: upload_config.content_type,
|
||||||
|
delete_on_download: upload_config.delete_on_download,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn find_by_id(
|
||||||
|
id: &str,
|
||||||
|
db: &sqlx::Pool<sqlx::Postgres>,
|
||||||
|
) -> Result<Option<FileInfo>, sqlx::Error> {
|
||||||
|
sqlx::query_as(
|
||||||
|
"SELECT file_id, file_name, valid_till, content_type, delete_on_download from files WHERE file_id = $1",
|
||||||
|
)
|
||||||
|
.bind(id)
|
||||||
|
.fetch_optional(db)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn create(file_info: &FileInfo, db: &sqlx::Pool<sqlx::Postgres>) -> Result<(), sqlx::Error> {
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO Files (file_id, file_name, content_type, valid_till, delete_on_download) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5)",
|
||||||
|
)
|
||||||
|
.bind(&file_info.file_id)
|
||||||
|
.bind(&file_info.file_name)
|
||||||
|
.bind(file_info.content_type.to_string())
|
||||||
|
.bind(file_info.valid_till)
|
||||||
|
.bind(file_info.delete_on_download)
|
||||||
|
.execute(db)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FromRow<'_, PgRow> for FileInfo {
|
||||||
|
fn from_row(row: &'_ PgRow) -> Result<Self, sqlx::Error> {
|
||||||
|
Ok(Self {
|
||||||
|
file_id: row.try_get("file_id")?,
|
||||||
|
file_name: row.try_get("file_name")?,
|
||||||
|
valid_till: row.try_get("valid_till")?,
|
||||||
|
content_type: row
|
||||||
|
.try_get_raw("content_type")?
|
||||||
|
.as_str()
|
||||||
|
.map_err(sqlx::Error::Decode)?
|
||||||
|
.parse()
|
||||||
|
.unwrap_or(APPLICATION_OCTET_STREAM),
|
||||||
|
delete_on_download: row.try_get("delete_on_download")?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,27 +0,0 @@
|
||||||
use std::{fmt::Display, str::FromStr};
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) enum FileKind {
|
|
||||||
TEXT,
|
|
||||||
BINARY,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for FileKind {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
FileKind::TEXT => write!(f, "text"),
|
|
||||||
FileKind::BINARY => write!(f, "binary"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FromStr for FileKind {
|
|
||||||
type Err = String;
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
|
||||||
match s.to_lowercase().as_str() {
|
|
||||||
"text" => Ok(FileKind::TEXT),
|
|
||||||
"binary" => Ok(FileKind::BINARY),
|
|
||||||
_ => Err(format!("unknown kind {}", s)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
305
src/main.rs
305
src/main.rs
|
@ -1,225 +1,134 @@
|
||||||
|
mod config;
|
||||||
|
mod db;
|
||||||
mod deleter;
|
mod deleter;
|
||||||
mod file_kind;
|
mod download;
|
||||||
|
mod file_info;
|
||||||
|
mod mime_relations;
|
||||||
mod multipart;
|
mod multipart;
|
||||||
|
mod rate_limit;
|
||||||
|
mod script_nonce;
|
||||||
|
mod template;
|
||||||
|
mod upload;
|
||||||
|
|
||||||
use actix_files::{Files, NamedFile};
|
use crate::rate_limit::ForwardedPeerIpKeyExtractor;
|
||||||
use actix_multipart::Multipart;
|
use actix_files::Files;
|
||||||
use actix_web::{error, http::header::{ContentDisposition, DispositionParam, DispositionType}, middleware, web::{self, Bytes}, App, Error, FromRequest, HttpRequest, HttpResponse, HttpServer};
|
use actix_governor::{Governor, GovernorConfigBuilder};
|
||||||
use async_std::{
|
use actix_web::{
|
||||||
fs,
|
http::header::{
|
||||||
path::PathBuf,
|
HeaderName, CROSS_ORIGIN_OPENER_POLICY, PERMISSIONS_POLICY, REFERRER_POLICY,
|
||||||
sync::{channel, Sender},
|
X_CONTENT_TYPE_OPTIONS, X_FRAME_OPTIONS, X_XSS_PROTECTION,
|
||||||
task,
|
},
|
||||||
};
|
middleware::{self, Condition, DefaultHeaders},
|
||||||
use file_kind::FileKind;
|
web::{self, Data},
|
||||||
use sqlx::{
|
App, Error, HttpResponse, HttpServer,
|
||||||
postgres::{PgPool, PgRow},
|
|
||||||
Cursor, Row,
|
|
||||||
};
|
};
|
||||||
|
use actix_web::middleware::from_fn;
|
||||||
|
use env_logger::Env;
|
||||||
|
use sqlx::postgres::PgPool;
|
||||||
use std::env;
|
use std::env;
|
||||||
|
use tokio::sync::mpsc::channel;
|
||||||
|
|
||||||
const UPLOAD_HTML: &str = include_str!("../template/upload.html");
|
static DEFAULT_PERMISSIONS: (HeaderName, &str) = (
|
||||||
const VIEW_HTML: &str = include_str!("../template/view.html");
|
PERMISSIONS_POLICY,
|
||||||
|
"accelerometer=(), ambient-light-sensor=(), battery=(), camera=(), display-capture=(), document-domain=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=(), usb=(), web-share=()"
|
||||||
|
);
|
||||||
|
static DEFAULT_CONTENT_TYPE_OPTIONS: (HeaderName, &str) = (X_CONTENT_TYPE_OPTIONS, "nosniff");
|
||||||
|
static DEFAULT_FRAME_OPTIONS: (HeaderName, &str) = (X_FRAME_OPTIONS, "deny");
|
||||||
|
static DEFAULT_XSS_PROTECTION: (HeaderName, &str) = (X_XSS_PROTECTION, "1; mode=block");
|
||||||
|
static DEFAULT_REFERRER_POLICY: (HeaderName, &str) = (REFERRER_POLICY, "no-referrer");
|
||||||
|
static DEFAULT_CROSS_ORIGIN_OPENER_POLICY: (HeaderName, &str) =
|
||||||
|
(CROSS_ORIGIN_OPENER_POLICY, "same-origin");
|
||||||
|
|
||||||
async fn index() -> Result<NamedFile, Error> {
|
async fn not_found() -> Result<HttpResponse, Error> {
|
||||||
Ok(NamedFile::open("./static/index.html")
|
Ok(HttpResponse::NotFound()
|
||||||
.map_err(|_| error::ErrorNotFound(""))?
|
.content_type("text/plain")
|
||||||
.disable_content_disposition())
|
.body("not found"))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn upload(
|
#[tokio::main]
|
||||||
payload: Multipart,
|
|
||||||
db: web::Data<PgPool>,
|
|
||||||
sender: web::Data<Sender<()>>,
|
|
||||||
config: web::Data<Config>,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let file_id = format!("{:x?}", rand::random::<u32>());
|
|
||||||
let mut filename = config.files_dir.clone();
|
|
||||||
filename.push(&file_id);
|
|
||||||
|
|
||||||
let (original_name, valid_till, kind) =
|
|
||||||
match multipart::parse_multipart(payload, &file_id, &filename).await {
|
|
||||||
Ok(data) => data,
|
|
||||||
Err(err) => {
|
|
||||||
if filename.exists().await {
|
|
||||||
fs::remove_file(filename)
|
|
||||||
.await
|
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not remove file"))?;
|
|
||||||
}
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
sqlx::query("INSERT INTO Files (file_id, file_name, valid_till, kind) VALUES ($1, $2, $3, $4)")
|
|
||||||
.bind(&file_id)
|
|
||||||
.bind(original_name.unwrap_or_else(|| file_id.clone()))
|
|
||||||
.bind(valid_till.naive_local())
|
|
||||||
.bind(kind.to_string())
|
|
||||||
.execute(db.as_ref())
|
|
||||||
.await
|
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not insert file into database"))?;
|
|
||||||
|
|
||||||
log::info!(
|
|
||||||
"create new file {} (valid_till: {}, kind: {})",
|
|
||||||
file_id,
|
|
||||||
valid_till,
|
|
||||||
kind
|
|
||||||
);
|
|
||||||
|
|
||||||
sender.send(()).await;
|
|
||||||
|
|
||||||
Ok(HttpResponse::SeeOther()
|
|
||||||
.header("location", format!("/upload/{}", file_id))
|
|
||||||
.finish())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn uploaded(id: web::Path<String>, req: web::HttpRequest) -> Result<HttpResponse, Error> {
|
|
||||||
let url = req.url_for("file", &[id.as_str()])?;
|
|
||||||
let upload_html = UPLOAD_HTML
|
|
||||||
.replace("{url}", url.as_str());
|
|
||||||
Ok(HttpResponse::Ok()
|
|
||||||
.content_type("text/html")
|
|
||||||
.body(upload_html))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn download(
|
|
||||||
req: HttpRequest,
|
|
||||||
id: web::Path<String>,
|
|
||||||
db: web::Data<PgPool>,
|
|
||||||
config: web::Data<Config>,
|
|
||||||
) -> Result<HttpResponse, Error> {
|
|
||||||
let mut cursor = sqlx::query("SELECT file_id, file_name, kind from files WHERE file_id = $1")
|
|
||||||
.bind(id.as_ref())
|
|
||||||
.fetch(db.as_ref());
|
|
||||||
let row: PgRow = cursor
|
|
||||||
.next()
|
|
||||||
.await
|
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not run select statement"))?
|
|
||||||
.ok_or_else(|| error::ErrorNotFound("file does not exist or has expired"))?;
|
|
||||||
|
|
||||||
let file_id: String = row.get("file_id");
|
|
||||||
let file_name: String = row.get("file_name");
|
|
||||||
let kind: String = row.get("kind");
|
|
||||||
let mut path = config.files_dir.clone();
|
|
||||||
path.push(&file_id);
|
|
||||||
|
|
||||||
if kind == FileKind::TEXT.to_string() && !req.query_string().contains("raw") {
|
|
||||||
let content = fs::read_to_string(path).await.map_err(|_| {
|
|
||||||
error::ErrorInternalServerError("this file should be here but could not be found")
|
|
||||||
})?;
|
|
||||||
let encoded = htmlescape::encode_minimal(&content);
|
|
||||||
let view_html = VIEW_HTML.replace("{text}", &encoded);
|
|
||||||
let response = HttpResponse::Ok().content_type("text/html").body(view_html);
|
|
||||||
Ok(response)
|
|
||||||
} else {
|
|
||||||
let file = NamedFile::open(path)
|
|
||||||
.map_err(|_| {
|
|
||||||
error::ErrorInternalServerError("this file should be here but could not be found")
|
|
||||||
})?
|
|
||||||
.set_content_disposition(ContentDisposition {
|
|
||||||
disposition: DispositionType::Attachment,
|
|
||||||
parameters: vec![DispositionParam::Filename(file_name)],
|
|
||||||
});
|
|
||||||
file.into_response(&req)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_db_url() -> String {
|
|
||||||
return env::var("DATABASE_URL").unwrap_or_else(|_| {
|
|
||||||
let mut url = "postgresql://".to_string();
|
|
||||||
|
|
||||||
let user = env::var("DATABASE_USER").unwrap_or_default();
|
|
||||||
if !user.is_empty() {
|
|
||||||
url += user.as_str();
|
|
||||||
|
|
||||||
let pass = env::var("DATABASE_PASS").unwrap_or_default();
|
|
||||||
if !pass.is_empty() {
|
|
||||||
url += ":";
|
|
||||||
url += pass.as_str();
|
|
||||||
}
|
|
||||||
|
|
||||||
url += "@";
|
|
||||||
}
|
|
||||||
url += env::var("DATABASE_HOST").unwrap_or_else(|_| "localhost".to_string()).as_str();
|
|
||||||
url += "/";
|
|
||||||
url += env::var("DATABASE_NAME").unwrap_or_else(|_| "datatrash".to_string()).as_str();
|
|
||||||
|
|
||||||
url.to_string()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn setup_db() -> PgPool {
|
|
||||||
let conn_url = &get_db_url();
|
|
||||||
log::info!("Using Connection string {}", conn_url);
|
|
||||||
|
|
||||||
let pool = PgPool::builder()
|
|
||||||
.max_size(5)
|
|
||||||
.connect_timeout(std::time::Duration::from_secs(5))
|
|
||||||
.build(conn_url)
|
|
||||||
.await
|
|
||||||
.expect("could not create db pool");
|
|
||||||
|
|
||||||
sqlx::query(include_str!("../init-db.sql"))
|
|
||||||
.execute(&pool)
|
|
||||||
.await
|
|
||||||
.expect("could not create table Files");
|
|
||||||
|
|
||||||
pool
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct Config {
|
|
||||||
files_dir: PathBuf,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_rt::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
if env::var("RUST_LOG").is_err() {
|
env_logger::Builder::from_env(Env::default().default_filter_or("info,sqlx=warn")).init();
|
||||||
env::set_var("RUST_LOG", "info");
|
|
||||||
}
|
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
let pool: PgPool = setup_db().await;
|
let pool: PgPool = db::setup().await;
|
||||||
let config = Config {
|
let config = config::from_env().await;
|
||||||
files_dir: PathBuf::from(env::var("FILES_DIR").unwrap_or_else(|_| "./files".to_owned())),
|
|
||||||
};
|
|
||||||
fs::create_dir_all(&config.files_dir)
|
|
||||||
.await
|
|
||||||
.expect("could not create directory for storing files");
|
|
||||||
let (sender, receiver) = channel(8);
|
let (sender, receiver) = channel(8);
|
||||||
|
|
||||||
log::info!("omnomnom");
|
let db = web::Data::new(pool.clone());
|
||||||
|
let expiry_watch_sender = web::Data::new(sender);
|
||||||
|
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:8000".to_owned());
|
||||||
|
|
||||||
task::spawn(deleter::delete_old_files(
|
let deleter = tokio::spawn(deleter::delete_old_files(
|
||||||
receiver,
|
receiver,
|
||||||
pool.clone(),
|
pool,
|
||||||
config.files_dir.clone(),
|
config.files_dir.clone(),
|
||||||
));
|
));
|
||||||
|
|
||||||
let db = web::Data::new(pool);
|
template::write_prefillable_templates(&config).await;
|
||||||
let sender = web::Data::new(sender);
|
let config = Data::new(config);
|
||||||
let upload_max_bytes: usize = env::var("UPLOAD_MAX_BYTES")
|
|
||||||
.ok()
|
|
||||||
.and_then(|variable| variable.parse().ok())
|
|
||||||
.unwrap_or(8_388_608);
|
|
||||||
let bind_address = env::var("BIND_ADDRESS").unwrap_or_else(|_| "0.0.0.0:8000".to_owned());
|
|
||||||
|
|
||||||
HttpServer::new({
|
let governor_conf = GovernorConfigBuilder::default()
|
||||||
|
.seconds_per_request(config.rate_limit_replenish_seconds)
|
||||||
|
.burst_size(config.rate_limit_burst)
|
||||||
|
.key_extractor(ForwardedPeerIpKeyExtractor {
|
||||||
|
proxied: config.proxied,
|
||||||
|
})
|
||||||
|
.use_headers()
|
||||||
|
.finish()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
log::info!("Listening on {bind_address}");
|
||||||
|
log::info!("omnomnom");
|
||||||
|
|
||||||
|
let http_server = HttpServer::new({
|
||||||
move || {
|
move || {
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(
|
||||||
|
DefaultHeaders::new()
|
||||||
|
.add(DEFAULT_PERMISSIONS.clone())
|
||||||
|
.add(DEFAULT_CONTENT_TYPE_OPTIONS.clone())
|
||||||
|
.add(DEFAULT_FRAME_OPTIONS.clone())
|
||||||
|
.add(DEFAULT_XSS_PROTECTION.clone())
|
||||||
|
.add(DEFAULT_REFERRER_POLICY.clone())
|
||||||
|
.add(DEFAULT_CROSS_ORIGIN_OPENER_POLICY.clone()),
|
||||||
|
)
|
||||||
|
.wrap(middleware::Compress::default())
|
||||||
|
.wrap(middleware::NormalizePath::trim())
|
||||||
|
.wrap(from_fn(script_nonce::insert_script_nonce))
|
||||||
.app_data(db.clone())
|
.app_data(db.clone())
|
||||||
.app_data(sender.clone())
|
.app_data(expiry_watch_sender.clone())
|
||||||
.app_data(Bytes::configure(|cfg| cfg.limit(upload_max_bytes)))
|
.app_data(config.clone())
|
||||||
.data(config.clone())
|
.service(
|
||||||
.service(web::resource("/").route(web::get().to(index)))
|
web::resource("/")
|
||||||
.service(web::resource("/upload").route(web::post().to(upload)))
|
.route(web::get().to(upload::index))
|
||||||
.service(web::resource("/upload/{id}").route(web::get().to(uploaded)))
|
.route(web::head().to(upload::index)),
|
||||||
.service(web::resource("/file/{id}").name("file").route(web::get().to(download)))
|
)
|
||||||
|
.service(web::resource("/upload").route(web::post().to(upload::upload)))
|
||||||
|
.service(
|
||||||
|
web::resource(["/upload/{id}", "/upload/{id}/{name}"])
|
||||||
|
.route(web::get().to(upload::uploaded))
|
||||||
|
.route(web::head().to(upload::uploaded)),
|
||||||
|
)
|
||||||
.service(Files::new("/static", "static").disable_content_disposition())
|
.service(Files::new("/static", "static").disable_content_disposition())
|
||||||
|
.default_service(web::route().to(not_found))
|
||||||
|
.service(
|
||||||
|
web::resource(["/{id:[a-z0-9]{5}}", "/{id:[a-z0-9]{5}}/{name}"])
|
||||||
|
.wrap(Condition::new(
|
||||||
|
config.enable_rate_limit,
|
||||||
|
Governor::new(&governor_conf),
|
||||||
|
))
|
||||||
|
.route(web::get().to(download::download))
|
||||||
|
.route(web::head().to(download::download)),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.bind(bind_address)?
|
.bind(bind_address)?
|
||||||
.run()
|
.run();
|
||||||
.await
|
|
||||||
|
// exit when http_server exits OR when deleter errors
|
||||||
|
tokio::select! {
|
||||||
|
result = http_server => result,
|
||||||
|
result = deleter => {
|
||||||
|
result?.map(|_| unreachable!("deletion runs infinitely")).expect("deletion may not fail")
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,71 @@
|
||||||
|
use std::{
|
||||||
|
collections::{HashMap, VecDeque},
|
||||||
|
str::FromStr,
|
||||||
|
};
|
||||||
|
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use mime::Mime;
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref ALIASES: HashMap<Mime, Mime> = load_mime_aliases();
|
||||||
|
static ref PARENTS: Vec<(Mime, Mime)> = load_mime_parent_relations();
|
||||||
|
static ref EXTENSIONS: HashMap<Mime, &'static str> = load_mime_extensions();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_mime_aliases() -> HashMap<Mime, Mime> {
|
||||||
|
tree_magic_db::aliases()
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| line.split_once(' '))
|
||||||
|
.filter_map(|(alias, mime)| Some((Mime::from_str(alias).ok()?, Mime::from_str(mime).ok()?)))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_mime_parent_relations() -> Vec<(Mime, Mime)> {
|
||||||
|
tree_magic_db::subclasses()
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| line.split_once(' '))
|
||||||
|
.filter_map(|(child, parent)| {
|
||||||
|
Some((Mime::from_str(child).ok()?, Mime::from_str(parent).ok()?))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load_mime_extensions() -> HashMap<Mime, &'static str> {
|
||||||
|
include_str!("../mime.types")
|
||||||
|
.lines()
|
||||||
|
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
||||||
|
.map(str::split_whitespace)
|
||||||
|
.filter_map(|mut elements| Some((Mime::from_str(elements.next()?).ok()?, elements.next()?)))
|
||||||
|
.map(|(mime, extension)| (ALIASES.get(&mime).cloned().unwrap_or(mime), extension))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_alias(mimetype: Mime) -> Mime {
|
||||||
|
ALIASES.get(&mimetype).cloned().unwrap_or(mimetype)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_mime_parents(mimetype: &Mime) -> Vec<&Mime> {
|
||||||
|
PARENTS
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(child, parent)| (child == mimetype).then_some(parent))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn matches_text(mime: &Mime) -> bool {
|
||||||
|
if mime.type_() == mime::TEXT {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return get_mime_parents(mime).into_iter().any(matches_text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_extension(mimetype: &Mime) -> Option<&'static str> {
|
||||||
|
let mut queue = VecDeque::new();
|
||||||
|
queue.push_back(mimetype);
|
||||||
|
while let Some(mime) = queue.pop_front() {
|
||||||
|
match EXTENSIONS.get(mimetype).copied() {
|
||||||
|
Some(ext) => return Some(ext),
|
||||||
|
None => queue.extend(get_mime_parents(mime)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
264
src/multipart.rs
264
src/multipart.rs
|
@ -1,123 +1,239 @@
|
||||||
use crate::file_kind::FileKind;
|
use crate::{config, mime_relations};
|
||||||
use actix_multipart::{Field, Multipart};
|
use actix_multipart::{Field, Multipart};
|
||||||
use actix_web::{error, http::header::DispositionParam};
|
use actix_web::{
|
||||||
use async_std::{fs, fs::File, path::Path, prelude::*};
|
error,
|
||||||
use chrono::{prelude::*, Duration};
|
http::header::{ContentDisposition, DispositionParam},
|
||||||
use futures::{StreamExt, TryStreamExt};
|
Error,
|
||||||
|
};
|
||||||
|
use futures_util::{StreamExt, TryStreamExt};
|
||||||
|
use mime::{Mime, APPLICATION_OCTET_STREAM, TEXT_PLAIN};
|
||||||
|
use std::{cmp::min, io::ErrorKind, path::Path};
|
||||||
|
use time::{Duration, OffsetDateTime};
|
||||||
|
use tokio::{
|
||||||
|
fs::{self, File},
|
||||||
|
io::AsyncWriteExt,
|
||||||
|
};
|
||||||
|
|
||||||
|
const MAX_UPLOAD_DURATION: Duration = Duration::days(31);
|
||||||
|
const DEFAULT_UPLOAD_DURATION: Duration = Duration::minutes(30);
|
||||||
|
|
||||||
|
pub(crate) struct UploadConfig {
|
||||||
|
pub original_name: Option<String>,
|
||||||
|
pub content_type: Mime,
|
||||||
|
pub valid_till: OffsetDateTime,
|
||||||
|
pub delete_on_download: bool,
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) async fn parse_multipart(
|
pub(crate) async fn parse_multipart(
|
||||||
mut payload: Multipart,
|
payload: Multipart,
|
||||||
file_id: &str,
|
file_path: &Path,
|
||||||
filename: &Path,
|
config: &config::Config,
|
||||||
) -> Result<(Option<String>, DateTime<Local>, FileKind), error::Error> {
|
) -> Result<UploadConfig, error::Error> {
|
||||||
let mut original_name: Option<String> = None;
|
match parse_multipart_inner(payload, file_path, config).await {
|
||||||
let mut timeout: Option<String> = None;
|
Ok(data) => Ok(data),
|
||||||
let mut kind: Option<FileKind> = None;
|
Err(err) => {
|
||||||
|
match fs::remove_file(file_path).await {
|
||||||
while let Ok(Some(field)) = payload.try_next().await {
|
Err(err) if err.kind() != ErrorKind::NotFound => {
|
||||||
let name = get_field_name(&field)?;
|
log::error!("could not remove file {:?}", err);
|
||||||
let name = name.as_str();
|
|
||||||
match name {
|
|
||||||
"validity_secs" => {
|
|
||||||
timeout = Some(parse_string(name, field).await?);
|
|
||||||
}
|
}
|
||||||
"content" => {
|
_ => {}
|
||||||
let file_original_name = get_original_filename(&field);
|
}
|
||||||
if file_original_name == None || file_original_name.as_deref() == Some("") {
|
Err(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn parse_multipart_inner(
|
||||||
|
mut payload: Multipart,
|
||||||
|
file_path: &Path,
|
||||||
|
config: &config::Config,
|
||||||
|
) -> Result<UploadConfig, error::Error> {
|
||||||
|
let mut original_name: Option<String> = None;
|
||||||
|
let mut content_type: Option<Mime> = None;
|
||||||
|
let mut keep_for_seconds: Option<String> = None;
|
||||||
|
let mut delete_on_download = false;
|
||||||
|
let mut password = None;
|
||||||
|
let mut size = 0;
|
||||||
|
|
||||||
|
while let Ok(Some(mut field)) = payload.try_next().await {
|
||||||
|
let name = get_field_name(&field)
|
||||||
|
.ok_or(error::ParseError::Incomplete)?
|
||||||
|
.to_owned();
|
||||||
|
match name.as_str() {
|
||||||
|
"keep_for" => {
|
||||||
|
keep_for_seconds = Some(parse_string(&name, &mut field).await?);
|
||||||
|
}
|
||||||
|
"file" => {
|
||||||
|
let (mime, uploaded_name) = get_file_metadata(&field);
|
||||||
|
if uploaded_name.is_none() || uploaded_name.as_deref() == Some("") {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
original_name = file_original_name;
|
original_name = uploaded_name;
|
||||||
kind = Some(FileKind::BINARY);
|
let first_bytes;
|
||||||
let mut file = fs::File::create(&filename)
|
(size, first_bytes) = create_file(file_path, field, config.max_file_size).await?;
|
||||||
.await
|
content_type = Some(
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not create file"))?;
|
mime.filter(|mime| *mime != APPLICATION_OCTET_STREAM)
|
||||||
write_to_file(&mut file, field)
|
.map(mime_relations::get_alias)
|
||||||
.await
|
.or_else(|| get_content_type(&first_bytes))
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not write file"))?;
|
.unwrap_or(APPLICATION_OCTET_STREAM),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
"text_content" => {
|
"text" => {
|
||||||
if original_name.is_some() {
|
if original_name.is_some() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
original_name = Some(format!("{}.txt", file_id));
|
let first_bytes;
|
||||||
kind = Some(FileKind::TEXT);
|
(size, first_bytes) = create_file(file_path, field, config.max_file_size).await?;
|
||||||
let mut file = fs::File::create(&filename)
|
content_type = Some(get_content_type(&first_bytes).unwrap_or(TEXT_PLAIN));
|
||||||
.await
|
}
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not create file"))?;
|
"delete_on_download" => {
|
||||||
write_to_file(&mut file, field)
|
delete_on_download = parse_string(&name, &mut field).await? != "false";
|
||||||
.await
|
}
|
||||||
.map_err(|_| error::ErrorInternalServerError("could not write file"))?;
|
"password" => {
|
||||||
|
password = Some(parse_string(&name, &mut field).await?);
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(original_name) = &original_name {
|
let content_type =
|
||||||
|
content_type.ok_or_else(|| error::ErrorBadRequest("no content type found"))?;
|
||||||
|
let keep_for = keep_for_seconds
|
||||||
|
.map(|k| k.parse())
|
||||||
|
.transpose()
|
||||||
|
.map_err(|e| error::ErrorBadRequest(format!("field keep_for is not a number: {e}")))?
|
||||||
|
.map_or(DEFAULT_UPLOAD_DURATION, Duration::seconds);
|
||||||
|
let valid_till = OffsetDateTime::now_utc() + keep_for;
|
||||||
|
|
||||||
|
let upload_config = UploadConfig {
|
||||||
|
original_name,
|
||||||
|
content_type,
|
||||||
|
valid_till,
|
||||||
|
delete_on_download,
|
||||||
|
};
|
||||||
|
|
||||||
|
check_requirements(&upload_config, size, &password, &keep_for, config)?;
|
||||||
|
|
||||||
|
Ok(upload_config)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_requirements(
|
||||||
|
upload_config: &UploadConfig,
|
||||||
|
size: u64,
|
||||||
|
password: &Option<String>,
|
||||||
|
keep_for: &Duration,
|
||||||
|
config: &config::Config,
|
||||||
|
) -> Result<(), error::Error> {
|
||||||
|
if let Some(original_name) = upload_config.original_name.as_ref() {
|
||||||
if original_name.len() > 255 {
|
if original_name.len() > 255 {
|
||||||
return Err(error::ErrorBadRequest("filename is too long"));
|
return Err(error::ErrorBadRequest("filename is too long"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let validity_secs = timeout
|
if *keep_for > MAX_UPLOAD_DURATION {
|
||||||
.ok_or_else(|| error::ErrorBadRequest("field validity_secs not set"))?
|
|
||||||
.parse()
|
|
||||||
.map_err(|e| {
|
|
||||||
error::ErrorBadRequest(format!("field validity_secs is not a number: {}", e))
|
|
||||||
})?;
|
|
||||||
let max_validity_secs = Duration::days(31).num_seconds();
|
|
||||||
if validity_secs > max_validity_secs {
|
|
||||||
return Err(error::ErrorBadRequest(format!(
|
return Err(error::ErrorBadRequest(format!(
|
||||||
"maximum allowed validity is {} seconds, but you specified {} seconds",
|
"maximum allowed validity is {MAX_UPLOAD_DURATION}, but you specified {keep_for}"
|
||||||
max_validity_secs, validity_secs
|
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
let valid_till = Local::now() + Duration::seconds(validity_secs);
|
|
||||||
let kind = kind.ok_or_else(|| error::ErrorBadRequest("no content found"))?;
|
if let Some(no_auth_limits) = &config.no_auth_limits {
|
||||||
Ok((original_name, valid_till, kind))
|
let requires_auth = *keep_for > no_auth_limits.max_time
|
||||||
|
|| *keep_for > no_auth_limits.large_file_max_time
|
||||||
|
&& size > no_auth_limits.large_file_size;
|
||||||
|
// hIGh sECUriTy paSsWoRD CHEck
|
||||||
|
if requires_auth && password.as_ref() != Some(&no_auth_limits.auth_password) {
|
||||||
|
return Err(error::ErrorBadRequest(
|
||||||
|
"upload requires authentication, but authentication was incorrect",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_field_name(field: &Field) -> Result<String, error::Error> {
|
fn get_field_name(field: &Field) -> Option<&str> {
|
||||||
Ok(field
|
field.content_disposition()?.get_name()
|
||||||
.content_disposition()
|
|
||||||
.ok_or_else(|| error::ParseError::Incomplete)?
|
|
||||||
.get_name()
|
|
||||||
.map(|s| s.to_owned())
|
|
||||||
.ok_or_else(|| error::ParseError::Incomplete)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn parse_string(name: &str, field: actix_multipart::Field) -> Result<String, error::Error> {
|
async fn parse_string(
|
||||||
|
name: &str,
|
||||||
|
field: &mut actix_multipart::Field,
|
||||||
|
) -> Result<String, error::Error> {
|
||||||
let data = read_content(field).await?;
|
let data = read_content(field).await?;
|
||||||
String::from_utf8(data)
|
String::from_utf8(data)
|
||||||
.map_err(|_| error::ErrorBadRequest(format!("could not parse field {} as utf-8", name)))
|
.map_err(|_| error::ErrorBadRequest(format!("could not parse field {name} as utf-8")))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_content(mut field: actix_multipart::Field) -> Result<Vec<u8>, error::Error> {
|
async fn read_content(field: &mut actix_multipart::Field) -> Result<Vec<u8>, error::Error> {
|
||||||
let mut data = Vec::new();
|
let mut data = Vec::new();
|
||||||
while let Some(chunk) = field.next().await {
|
while let Some(chunk) = field.try_next().await.map_err(error::ErrorBadRequest)? {
|
||||||
data.extend(chunk.map_err(error::ErrorBadRequest)?);
|
data.extend(chunk);
|
||||||
}
|
}
|
||||||
Ok(data)
|
Ok(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn create_file(
|
||||||
|
filename: &Path,
|
||||||
|
field: Field,
|
||||||
|
max_file_size: Option<u64>,
|
||||||
|
) -> Result<(u64, Vec<u8>), Error> {
|
||||||
|
let mut file = File::create(&filename).await.map_err(|file_err| {
|
||||||
|
log::error!("could not create file {:?}", file_err);
|
||||||
|
error::ErrorInternalServerError("could not create file")
|
||||||
|
})?;
|
||||||
|
write_to_file(&mut file, field, max_file_size).await
|
||||||
|
}
|
||||||
|
|
||||||
async fn write_to_file(
|
async fn write_to_file(
|
||||||
file: &mut File,
|
file: &mut File,
|
||||||
mut field: actix_multipart::Field,
|
mut field: Field,
|
||||||
) -> Result<(), error::Error> {
|
max_size: Option<u64>,
|
||||||
|
) -> Result<(u64, Vec<u8>), error::Error> {
|
||||||
|
let mut first_bytes = Vec::with_capacity(2048);
|
||||||
|
let mut written_bytes: u64 = 0;
|
||||||
while let Some(chunk) = field.next().await {
|
while let Some(chunk) = field.next().await {
|
||||||
file.write_all(chunk.map_err(error::ErrorBadRequest)?.as_ref())
|
let chunk = chunk.map_err(error::ErrorBadRequest)?;
|
||||||
.await?;
|
written_bytes += chunk.len() as u64;
|
||||||
|
validate_max_size(written_bytes, max_size)?;
|
||||||
|
|
||||||
|
let remaining_first_bytes = min(2048 - first_bytes.len(), chunk.len());
|
||||||
|
first_bytes.extend_from_slice(&chunk[..remaining_first_bytes]);
|
||||||
|
|
||||||
|
file.write_all(&chunk).await.map_err(|write_err| {
|
||||||
|
log::error!("could not write file {:?}", write_err);
|
||||||
|
error::ErrorInternalServerError("could not write file")
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Ok((written_bytes, first_bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_max_size(written_bytes: u64, max_size: Option<u64>) -> Result<(), Error> {
|
||||||
|
if let Some(max_size) = max_size {
|
||||||
|
if written_bytes > max_size {
|
||||||
|
return Err(error::ErrorPayloadTooLarge(format!(
|
||||||
|
"exceeded maximum file size of {max_size} bytes"
|
||||||
|
)));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_original_filename(field: &actix_multipart::Field) -> Option<String> {
|
fn get_file_metadata(field: &actix_multipart::Field) -> (Option<Mime>, Option<String>) {
|
||||||
field.content_disposition().and_then(|content_disposition| {
|
let mime = field.content_type().cloned();
|
||||||
|
let filename = field.content_disposition().and_then(get_filename);
|
||||||
|
(mime, filename)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_filename(content_disposition: &ContentDisposition) -> Option<String> {
|
||||||
content_disposition
|
content_disposition
|
||||||
.parameters
|
.parameters
|
||||||
.into_iter()
|
.iter()
|
||||||
.find_map(|param| match param {
|
.find_map(|param| match param {
|
||||||
DispositionParam::Filename(filename) => Some(filename),
|
DispositionParam::Filename(filename) => Some(filename.clone()),
|
||||||
_ => None,
|
_ => None,
|
||||||
})
|
})
|
||||||
})
|
}
|
||||||
|
|
||||||
|
fn get_content_type(bytes: &[u8]) -> Option<Mime> {
|
||||||
|
tree_magic_mini::from_u8(bytes).parse().ok()
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,59 @@
|
||||||
|
use actix_governor::governor::clock::{Clock, DefaultClock, QuantaInstant};
|
||||||
|
use actix_governor::governor::NotUntil;
|
||||||
|
use actix_governor::KeyExtractor;
|
||||||
|
use actix_governor::PeerIpKeyExtractor;
|
||||||
|
use actix_governor::SimpleKeyExtractionError;
|
||||||
|
use actix_web::HttpResponse;
|
||||||
|
use actix_web::HttpResponseBuilder;
|
||||||
|
use actix_web::{dev::ServiceRequest, http::header::ContentType};
|
||||||
|
use std::net::{IpAddr, Ipv6Addr};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ForwardedPeerIpKeyExtractor {
|
||||||
|
pub proxied: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyExtractor for ForwardedPeerIpKeyExtractor {
|
||||||
|
type Key = IpAddr;
|
||||||
|
type KeyExtractionError = SimpleKeyExtractionError<&'static str>;
|
||||||
|
|
||||||
|
fn extract(&self, req: &ServiceRequest) -> Result<Self::Key, Self::KeyExtractionError> {
|
||||||
|
let forwarded_for = req.headers().get("x-forwarded-for");
|
||||||
|
let ip = if self.proxied && forwarded_for.is_some() {
|
||||||
|
read_forwareded_for(forwarded_for).map_err(SimpleKeyExtractionError::new)?
|
||||||
|
} else {
|
||||||
|
PeerIpKeyExtractor.extract(req)?
|
||||||
|
};
|
||||||
|
|
||||||
|
if let IpAddr::V6(mut ipv6) = ip {
|
||||||
|
// only keep the first /56 for IPv6 addresses
|
||||||
|
ipv6 &= Ipv6Addr::from_bits(u128::MAX << (u128::BITS - 56));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exceed_rate_limit_response(
|
||||||
|
&self,
|
||||||
|
negative: &NotUntil<QuantaInstant>,
|
||||||
|
mut response: HttpResponseBuilder,
|
||||||
|
) -> HttpResponse {
|
||||||
|
let wait_time = negative
|
||||||
|
.wait_time_from(DefaultClock::default().now())
|
||||||
|
.as_secs();
|
||||||
|
response
|
||||||
|
.content_type(ContentType::plaintext())
|
||||||
|
.body(format!("too many requests, retry in {wait_time}s"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_forwareded_for(
|
||||||
|
forwarded_for: Option<&actix_web::http::header::HeaderValue>,
|
||||||
|
) -> Result<IpAddr, &'static str> {
|
||||||
|
forwarded_for
|
||||||
|
.unwrap()
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| "x-forwarded-for contains invalid header value")?
|
||||||
|
.parse::<IpAddr>()
|
||||||
|
.map_err(|_| "x-forwarded-for contains invalid ip adress")
|
||||||
|
}
|
|
@ -0,0 +1,35 @@
|
||||||
|
use actix_web::{
|
||||||
|
body::MessageBody,
|
||||||
|
dev::{ServiceRequest, ServiceResponse},
|
||||||
|
http::header::{HeaderValue, CONTENT_SECURITY_POLICY},
|
||||||
|
Error, HttpMessage,
|
||||||
|
};
|
||||||
|
use actix_web::middleware::Next;
|
||||||
|
use rand::Rng;
|
||||||
|
use std::fmt::Display;
|
||||||
|
|
||||||
|
pub struct ScriptNonce(String);
|
||||||
|
|
||||||
|
impl Display for ScriptNonce {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}", self.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn insert_script_nonce(
|
||||||
|
req: ServiceRequest,
|
||||||
|
next: Next<impl MessageBody>,
|
||||||
|
) -> Result<ServiceResponse<impl MessageBody>, Error> {
|
||||||
|
let script_nonce = format!("{:02x}", rand::thread_rng().gen::<u128>());
|
||||||
|
req.extensions_mut()
|
||||||
|
.insert(ScriptNonce(script_nonce.clone()));
|
||||||
|
let mut res = next.call(req).await;
|
||||||
|
if let Ok(res) = res.as_mut() {
|
||||||
|
let value = format!("default-src 'none'; connect-src 'self'; img-src 'self'; media-src 'self'; font-src 'self'; script-src 'nonce-{script_nonce}'; style-src 'self'; object-src 'none'; base-uri 'self'; frame-src 'none'; frame-ancestors 'none'; form-action 'self'; require-trusted-types-for 'script';");
|
||||||
|
res.headers_mut().insert(
|
||||||
|
CONTENT_SECURITY_POLICY,
|
||||||
|
HeaderValue::from_str(&value).unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}
|
|
@ -0,0 +1,207 @@
|
||||||
|
use std::{cmp, io::ErrorKind, str::FromStr};
|
||||||
|
|
||||||
|
use actix_web::{HttpMessage, HttpRequest};
|
||||||
|
use time::Duration;
|
||||||
|
use tokio::fs;
|
||||||
|
use url::Url;
|
||||||
|
|
||||||
|
use crate::{config::Config, script_nonce::ScriptNonce};
|
||||||
|
|
||||||
|
const INDEX_HTML: &str = include_str!("../template/index.html");
|
||||||
|
const AUTH_HIDE_JS: &str = include_str!("../template/auth-hide.js");
|
||||||
|
const AUTH_SNIPPET_HTML: &str = include_str!("../snippet/auth.html.snippet");
|
||||||
|
const MAX_SIZE_SNIPPET_HTML: &str = include_str!("../snippet/max_size.html.snippet");
|
||||||
|
const FILE_NAME_SNIPPET_HTML: &str = include_str!("../snippet/file_name.html.snippet");
|
||||||
|
|
||||||
|
const ABUSE_SNIPPET_HTML: &str = include_str!("../snippet/abuse.html.snippet");
|
||||||
|
|
||||||
|
const UPLOAD_HTML: &str = include_str!("../template/upload.html");
|
||||||
|
const UPLOAD_SHORT_HTML: &str = include_str!("../template/upload-short.html");
|
||||||
|
|
||||||
|
const TEXT_VIEW_HTML: &str = include_str!("../template/text-view.html");
|
||||||
|
const URL_VIEW_HTML: &str = include_str!("../template/url-view.html");
|
||||||
|
|
||||||
|
pub fn build_uploaded_html(
|
||||||
|
req: &HttpRequest,
|
||||||
|
id: &str,
|
||||||
|
name: Option<&str>,
|
||||||
|
config: &Config,
|
||||||
|
) -> String {
|
||||||
|
let upload_html = if name.is_some() {
|
||||||
|
UPLOAD_SHORT_HTML
|
||||||
|
.replace("{link}", &get_file_url(req, id, name))
|
||||||
|
.replace("{shortlink}", &get_file_url(req, id, None))
|
||||||
|
} else {
|
||||||
|
UPLOAD_HTML.replace("{link}", &get_file_url(req, id, name))
|
||||||
|
};
|
||||||
|
let upload_html = insert_abuse_template(upload_html, None, config);
|
||||||
|
insert_script_nonce(req, upload_html)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_file_url(req: &HttpRequest, id: &str, name: Option<&str>) -> String {
|
||||||
|
let host = get_host_url(req);
|
||||||
|
if let Some(name) = name {
|
||||||
|
let encoded_name = urlencoding::encode(name);
|
||||||
|
format!("{host}/{id}/{encoded_name}")
|
||||||
|
} else {
|
||||||
|
format!("{host}/{id}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_html_view_template(
|
||||||
|
content: &str,
|
||||||
|
file_name: Option<&str>,
|
||||||
|
req: &HttpRequest,
|
||||||
|
config: &Config,
|
||||||
|
) -> String {
|
||||||
|
let encoded_content = htmlescape::encode_minimal(content);
|
||||||
|
let name_snippet = file_name
|
||||||
|
.map(htmlescape::encode_minimal)
|
||||||
|
.map(|name| FILE_NAME_SNIPPET_HTML.replace("{file_name}", &name))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let html = if !content.trim().contains(['\n', '\r']) && Url::from_str(content.trim()).is_ok() {
|
||||||
|
let attribute_encoded_content = htmlescape::encode_attribute(content);
|
||||||
|
URL_VIEW_HTML
|
||||||
|
.replace("{link_content}", &encoded_content)
|
||||||
|
.replace("{link_attribute}", &attribute_encoded_content)
|
||||||
|
} else {
|
||||||
|
TEXT_VIEW_HTML
|
||||||
|
.replace("{file_name}", &name_snippet)
|
||||||
|
.replace("{text}", &encoded_content)
|
||||||
|
};
|
||||||
|
let html = insert_abuse_template(html, Some(req), config);
|
||||||
|
insert_script_nonce(req, html)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn write_prefillable_templates(config: &Config) {
|
||||||
|
let auth_hide_path = config.static_dir.join("auth-hide.js");
|
||||||
|
if let Some(auth_hide_js) = build_auth_hide_js(config) {
|
||||||
|
fs::write(auth_hide_path, auth_hide_js)
|
||||||
|
.await
|
||||||
|
.expect("could not write auth-hide.js to static folder");
|
||||||
|
} else {
|
||||||
|
match fs::remove_file(auth_hide_path).await {
|
||||||
|
Err(err) if err.kind() == ErrorKind::NotFound => {}
|
||||||
|
r => r.expect("could not delete auth-hide.js from static folder"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_index_html(req: &HttpRequest, config: &Config) -> String {
|
||||||
|
let mut html = INDEX_HTML.to_owned();
|
||||||
|
if let Some(limit) = config.no_auth_limits.as_ref() {
|
||||||
|
html = html
|
||||||
|
.replace("{auth_snippet}", AUTH_SNIPPET_HTML.trim_end())
|
||||||
|
.replace("{auth_time}", &render_duration(limit.max_time))
|
||||||
|
.replace(
|
||||||
|
"{auth_large_time}",
|
||||||
|
&render_duration(limit.large_file_max_time),
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"{auth_large_size}",
|
||||||
|
&render_file_size(limit.large_file_size),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
html = html.replace("{auth_snippet}", "");
|
||||||
|
}
|
||||||
|
html = insert_abuse_template(html, None, config);
|
||||||
|
if let Some(max_file_size) = config.max_file_size {
|
||||||
|
html = html
|
||||||
|
.replace("{max_size_snippet}", MAX_SIZE_SNIPPET_HTML.trim_end())
|
||||||
|
.replace("{max_size}", &render_file_size(max_file_size));
|
||||||
|
} else {
|
||||||
|
html = html.replace("{max_size_snippet}", "");
|
||||||
|
};
|
||||||
|
insert_script_nonce(req, html)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_abuse_template(html: String, req: Option<&HttpRequest>, config: &Config) -> String {
|
||||||
|
if let Some(abuse_mail) = &config.abuse_mail {
|
||||||
|
let url = if let Some(req) = req {
|
||||||
|
format!("{host}{path}", host = get_host_url(req), path = req.uri())
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
// urlencoding::encode(data)
|
||||||
|
html.replace("{abuse}", ABUSE_SNIPPET_HTML.trim_end())
|
||||||
|
.replace("{abusemail}", abuse_mail)
|
||||||
|
.replace("{url}", &urlencoding::encode(&url))
|
||||||
|
} else {
|
||||||
|
html.replace("{abuse}", "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn insert_script_nonce(req: &HttpRequest, html: String) -> String {
|
||||||
|
let extensions = &req.extensions();
|
||||||
|
let script_nonce = extensions.get::<ScriptNonce>().expect("script_nonce available");
|
||||||
|
html.replace("{script_nonce}", &script_nonce.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_file_size(size: u64) -> String {
|
||||||
|
let magnitude = cmp::min((size as f64).log(1024.0) as u32, 5);
|
||||||
|
let prefix = ["", "ki", "Mi", "Gi", "Ti", "Pi"][magnitude as usize];
|
||||||
|
let value = size / (1024_u64.pow(magnitude));
|
||||||
|
format!("{value}{prefix}B")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_duration(duration: Duration) -> String {
|
||||||
|
let days = duration.whole_days();
|
||||||
|
let hours = duration.whole_hours() % 24;
|
||||||
|
let minutes = duration.whole_minutes() % 60;
|
||||||
|
let seconds = duration.whole_seconds() % 60;
|
||||||
|
let mut elements = vec![];
|
||||||
|
if let Some(name) = pluralize(days, "tag", "e") {
|
||||||
|
elements.push(name);
|
||||||
|
}
|
||||||
|
if let Some(name) = pluralize(hours, "stunde", "n") {
|
||||||
|
elements.push(name);
|
||||||
|
}
|
||||||
|
if let Some(name) = pluralize(minutes, "minute", "n") {
|
||||||
|
elements.push(name);
|
||||||
|
}
|
||||||
|
if let Some(name) = pluralize(seconds, "sekunde", "n") {
|
||||||
|
elements.push(name);
|
||||||
|
}
|
||||||
|
elements.join("+")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pluralize(number: i64, word: &str, suffix: &str) -> Option<String> {
|
||||||
|
match number {
|
||||||
|
0 => None,
|
||||||
|
1 => Some(format!("{number} {word}")),
|
||||||
|
_ => Some(format!("{number} {word}{suffix}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_auth_hide_js(config: &Config) -> Option<String> {
|
||||||
|
if let Some(no_auth_limits) = &config.no_auth_limits {
|
||||||
|
let auth_hide_js = AUTH_HIDE_JS
|
||||||
|
.replace(
|
||||||
|
"{no_auth_max_time}",
|
||||||
|
&no_auth_limits.max_time.whole_seconds().to_string(),
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"{no_auth_large_file_max_time}",
|
||||||
|
&no_auth_limits
|
||||||
|
.large_file_max_time
|
||||||
|
.whole_seconds()
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"{no_auth_large_file_size}",
|
||||||
|
&no_auth_limits.large_file_size.to_string(),
|
||||||
|
);
|
||||||
|
Some(auth_hide_js)
|
||||||
|
// Ok(HttpResponse::Ok()
|
||||||
|
// .content_type("application/javascript")
|
||||||
|
// .body(auth_hide_js))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
// Err(error::ErrorNotFound("file not found"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_host_url(req: &HttpRequest) -> String {
|
||||||
|
let conn = req.connection_info();
|
||||||
|
format!("{}://{}", conn.scheme(), conn.host())
|
||||||
|
}
|
|
@ -0,0 +1,125 @@
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
|
||||||
|
use crate::config::Config;
|
||||||
|
use crate::file_info::FileInfo;
|
||||||
|
use crate::{file_info, multipart, template};
|
||||||
|
use actix_multipart::Multipart;
|
||||||
|
use actix_web::http::header::LOCATION;
|
||||||
|
use actix_web::{error, web, Error, HttpRequest, HttpResponse};
|
||||||
|
use rand::{distributions::Slice, Rng};
|
||||||
|
use sqlx::postgres::PgPool;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use tokio::fs::{self, OpenOptions};
|
||||||
|
use tokio::sync::mpsc::Sender;
|
||||||
|
|
||||||
|
const ID_CHARS: &[char] = &[
|
||||||
|
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u',
|
||||||
|
'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
||||||
|
];
|
||||||
|
|
||||||
|
pub async fn index(req: HttpRequest, config: web::Data<Config>) -> HttpResponse {
|
||||||
|
let index_html = template::build_index_html(&req, &config);
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.content_type("text/html")
|
||||||
|
.body(index_html)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn upload(
|
||||||
|
req: HttpRequest,
|
||||||
|
payload: Multipart,
|
||||||
|
db: web::Data<PgPool>,
|
||||||
|
expiry_watch_sender: web::Data<Sender<()>>,
|
||||||
|
config: web::Data<Config>,
|
||||||
|
) -> Result<HttpResponse, Error> {
|
||||||
|
let (file_id, file_path) = create_unique_file_id(&config).await.map_err(|file_err| {
|
||||||
|
log::error!("could not create file {:?}", file_err);
|
||||||
|
error::ErrorInternalServerError("could not create file")
|
||||||
|
})?;
|
||||||
|
let upload_config = multipart::parse_multipart(payload, &file_path, &config).await?;
|
||||||
|
let file_info = FileInfo::new(file_id, upload_config);
|
||||||
|
|
||||||
|
create_file(&file_info, &file_path, db).await?;
|
||||||
|
|
||||||
|
expiry_watch_sender.send(()).await.unwrap();
|
||||||
|
|
||||||
|
let redirect = get_redirect_url(&file_info.file_id, file_info.file_name.as_deref());
|
||||||
|
let url = template::get_file_url(&req, &file_info.file_id, file_info.file_name.as_deref());
|
||||||
|
Ok(HttpResponse::SeeOther()
|
||||||
|
.insert_header((LOCATION, redirect))
|
||||||
|
.body(format!("{url}\n")))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_file(
|
||||||
|
file_info: &FileInfo,
|
||||||
|
file_path: &Path,
|
||||||
|
db: web::Data<sqlx::Pool<sqlx::Postgres>>,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
if let Err(db_err) = file_info::create(file_info, &db).await {
|
||||||
|
log::error!("could not insert into datebase {:?}", db_err);
|
||||||
|
|
||||||
|
if let Err(file_err) = fs::remove_file(file_path).await {
|
||||||
|
log::error!("could not remove file {:?}", file_err);
|
||||||
|
}
|
||||||
|
return Err(error::ErrorInternalServerError(
|
||||||
|
"could not insert file into database",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
log::info!(
|
||||||
|
"create new file {} (valid_till: {}, content_type: {}, delete_on_download: {})",
|
||||||
|
file_info.file_id,
|
||||||
|
file_info.valid_till,
|
||||||
|
file_info.content_type,
|
||||||
|
file_info.delete_on_download
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_unique_file_id(
|
||||||
|
config: &web::Data<Config>,
|
||||||
|
) -> Result<(String, PathBuf), std::io::Error> {
|
||||||
|
loop {
|
||||||
|
let file_id = gen_file_id();
|
||||||
|
let file_path = config.files_dir.join(&file_id);
|
||||||
|
match OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.create_new(true)
|
||||||
|
.open(&file_path)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(_) => return Ok((file_id, file_path)),
|
||||||
|
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
|
||||||
|
Err(error) => return Err(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gen_file_id() -> String {
|
||||||
|
let distribution = Slice::new(ID_CHARS).expect("ID_CHARS is not empty");
|
||||||
|
rand::thread_rng()
|
||||||
|
.sample_iter(distribution)
|
||||||
|
.take(5)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_redirect_url(id: &str, name: Option<&str>) -> String {
|
||||||
|
if let Some(name) = name {
|
||||||
|
let encoded_name = urlencoding::encode(name);
|
||||||
|
format!("/upload/{id}/{encoded_name}")
|
||||||
|
} else {
|
||||||
|
format!("/upload/{id}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn uploaded(req: HttpRequest, config: web::Data<Config>) -> Result<HttpResponse, Error> {
|
||||||
|
let id = req.match_info().query("id");
|
||||||
|
let name = req
|
||||||
|
.match_info()
|
||||||
|
.get("name")
|
||||||
|
.map(urlencoding::decode)
|
||||||
|
.transpose()
|
||||||
|
.map_err(|_| error::ErrorBadRequest("name is invalid utf-8"))?;
|
||||||
|
let uploaded_html = template::build_uploaded_html(&req, id, name.as_deref(), &config);
|
||||||
|
Ok(HttpResponse::Ok()
|
||||||
|
.content_type("text/html")
|
||||||
|
.body(uploaded_html))
|
||||||
|
}
|
|
@ -0,0 +1,13 @@
|
||||||
|
if (navigator.clipboard) {
|
||||||
|
const buttons = document.querySelectorAll("button[data-copy], a[data-copy]");
|
||||||
|
for (const button of buttons) {
|
||||||
|
button.classList.remove("hidden");
|
||||||
|
button.onclick = () => {
|
||||||
|
const target = document.querySelector(button.getAttribute("data-copy"));
|
||||||
|
navigator.clipboard.writeText(target.textContent).then(
|
||||||
|
(_) => (button.innerText = "kopiert!"),
|
||||||
|
(_) => (button.innerText = "nicht unterstützt")
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
After Width: | Height: | Size: 55 KiB |
|
@ -0,0 +1,45 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||||
|
|
||||||
|
<svg
|
||||||
|
width="20.039999mm"
|
||||||
|
height="32.470001mm"
|
||||||
|
viewBox="0 0 20.039999 32.470002"
|
||||||
|
version="1.1"
|
||||||
|
id="svg5"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
xmlns:svg="http://www.w3.org/2000/svg">
|
||||||
|
<defs
|
||||||
|
id="defs2" />
|
||||||
|
<g
|
||||||
|
id="layer1">
|
||||||
|
<path
|
||||||
|
id="path27079"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0,3.4728255 19.692763,1.0182368e-8 20.04,1.9695374 0.34723656,5.4423629 Z" />
|
||||||
|
<path
|
||||||
|
id="path27076"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0.42165307,7.3209983 H 19.618346 V 9.3209188 H 0.42165307 Z" />
|
||||||
|
<path
|
||||||
|
id="path27073"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 0.82158379,12.920776 H 19.218416 v 1.99992 H 0.82158379 Z" />
|
||||||
|
<path
|
||||||
|
id="path27070"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 1.2215157,18.520553 H 18.818485 v 1.999921 H 1.2215157 Z" />
|
||||||
|
<path
|
||||||
|
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0;stroke-dasharray:none;paint-order:normal"
|
||||||
|
d="m 6.9813387,24.122065 a 4.999139,4.9998014 0 0 1 2.3095393,1.999798 h 9.129654 v -1.999798 z"
|
||||||
|
id="path27067" />
|
||||||
|
<path
|
||||||
|
id="path27064"
|
||||||
|
style="fill:#ffffff;fill-opacity:1;fill-rule:nonzero;stroke:none;stroke-width:0;stroke-dasharray:none;paint-order:normal"
|
||||||
|
d="M 9.9160553,29.7184 A 4.999139,4.9998014 0 0 1 9.0170401,31.718199 H 18.017524 V 29.7184 Z" />
|
||||||
|
<path
|
||||||
|
id="path27061"
|
||||||
|
style="fill:#ffffff;stroke:none;stroke-width:0"
|
||||||
|
d="M 8.7702156,28.720149 A 3.7493543,3.749851 0 0 1 5.0208613,32.47 3.7493543,3.749851 0 0 1 1.271507,28.720149 3.7493543,3.749851 0 0 1 5.0208613,24.970298 3.7493543,3.749851 0 0 1 8.7702156,28.720149 Z" />
|
||||||
|
</g>
|
||||||
|
</svg>
|
After Width: | Height: | Size: 1.8 KiB |
175
static/index.css
175
static/index.css
|
@ -1,19 +1,51 @@
|
||||||
|
:root {
|
||||||
|
--bg: #262824;
|
||||||
|
--bg-alt: #434742;
|
||||||
|
--accent: #007100;
|
||||||
|
--accent-alt: #228b22;
|
||||||
|
--fg: #dfe1de;
|
||||||
|
--fg-light: #afb3ab;
|
||||||
|
--radius: 5px;
|
||||||
|
--separators: 1px;
|
||||||
|
--separators-wide: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
*,
|
||||||
|
*::before,
|
||||||
|
*::after {
|
||||||
|
box-sizing: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
background-color: #222222;
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: space-between;
|
||||||
|
background-color: var(--bg);
|
||||||
|
min-height: 100vh;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
|
font-family: sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
main {
|
main {
|
||||||
color: #dddddd;
|
color: var(--fg);
|
||||||
font-family: sans;
|
width: 100%;
|
||||||
max-width: 1200px;
|
max-width: 1000px;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 1rem;
|
padding: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 > a,
|
h1 > a,
|
||||||
h1 > a:visited {
|
h1 > a:visited {
|
||||||
color: #dddddd;
|
color: var(--fg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
height: 1.2em;
|
||||||
|
margin-left: 0.1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
|
@ -25,24 +57,82 @@ a:visited {
|
||||||
}
|
}
|
||||||
|
|
||||||
label {
|
label {
|
||||||
|
display: inline-block;
|
||||||
margin-right: 0.25em;
|
margin-right: 0.25em;
|
||||||
|
margin-bottom: 0.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
input,
|
input,
|
||||||
select,
|
select,
|
||||||
textarea,
|
textarea,
|
||||||
.button {
|
.button {
|
||||||
background-color: #222222;
|
display: inline-block;
|
||||||
color: #dddddd;
|
background-color: var(--bg-alt);
|
||||||
padding: 0.5rem;
|
color: var(--fg);
|
||||||
border: 2px solid #dddddd;
|
padding: 0.5em;
|
||||||
border-radius: 5px;
|
border: var(--separators) solid var(--fg-light);
|
||||||
margin-bottom: 1rem;
|
border-radius: var(--radius);
|
||||||
max-width: calc(100vw - 3rem - 4px);
|
margin-bottom: 1.5em;
|
||||||
|
max-width: calc(100vw - 2em);
|
||||||
|
}
|
||||||
|
|
||||||
|
details {
|
||||||
|
display: inline;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
details > pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 1rem 0.5rem;
|
||||||
|
overflow-x: scroll;
|
||||||
|
}
|
||||||
|
|
||||||
|
details summary {
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
details[open] summary {
|
||||||
|
border-bottom: var(--separators) solid var(--fg-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
input:focus-within,
|
||||||
|
select:focus-within,
|
||||||
|
textarea:focus-within,
|
||||||
|
.button:focus-within,
|
||||||
|
details:focus-within,
|
||||||
|
a:focus-within {
|
||||||
|
outline: solid cornflowerblue var(--separators);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
width: 100%;
|
||||||
|
height: 60vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
form > textarea {
|
||||||
|
height: 30vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hidden {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="checkbox"] {
|
||||||
|
margin-top: 0.5em;
|
||||||
|
margin-bottom: 1.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.button {
|
.button {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
font-family: sans-serif;
|
||||||
|
font-weight: normal;
|
||||||
|
font-size: 1em;
|
||||||
|
margin-right: 0.5em;
|
||||||
|
margin-top: 1em;
|
||||||
|
user-select: none;
|
||||||
|
border-width: var(--separators-wide);
|
||||||
}
|
}
|
||||||
|
|
||||||
a.button {
|
a.button {
|
||||||
|
@ -50,17 +140,68 @@ a.button {
|
||||||
}
|
}
|
||||||
|
|
||||||
a.button:visited {
|
a.button:visited {
|
||||||
color: #dddddd;
|
color: var(--fg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.button:hover {
|
.button:hover {
|
||||||
background-color: #444444;
|
background-color: var(--bg-alt);
|
||||||
|
border-color: var(--fg);
|
||||||
}
|
}
|
||||||
|
|
||||||
.button.main {
|
.button.main {
|
||||||
background-color: green;
|
background-color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.button.main:hover {
|
.button.main:hover {
|
||||||
background-color: forestgreen;
|
background-color: var(--accent-alt);
|
||||||
|
}
|
||||||
|
|
||||||
|
.usage {
|
||||||
|
margin-top: 2em;
|
||||||
|
overflow: auto;
|
||||||
|
color: var(--fg-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.usage > p {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.usage > p > label {
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.usage > p > code {
|
||||||
|
margin-left: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.large-link {
|
||||||
|
display: inline-block;
|
||||||
|
margin-bottom: 1em;
|
||||||
|
max-height: 60vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
|
||||||
|
font-size: clamp(1em, 3vw, 1.5em);
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer {
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
padding: 0.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer > * {
|
||||||
|
padding: 0.5em;
|
||||||
|
color: var(--fg-light);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
footer > *:visited {
|
||||||
|
color: var(--fg-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
footer > *:hover {
|
||||||
|
color: var(--fg);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,36 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>datatrash</title>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<link href="/static/index.css" rel="stylesheet" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<main>
|
|
||||||
<h1>datatrash</h1>
|
|
||||||
<form action="/upload" method="POST" enctype="multipart/form-data">
|
|
||||||
<input type="file" name="content" />
|
|
||||||
<br />
|
|
||||||
<textarea
|
|
||||||
name="text_content"
|
|
||||||
placeholder="Oder asciitrash"
|
|
||||||
rows="20"
|
|
||||||
cols="120"
|
|
||||||
></textarea>
|
|
||||||
<br />
|
|
||||||
<label for="validity_secs">Gültig für</label>
|
|
||||||
<select id="validity_secs" name="validity_secs">
|
|
||||||
<option value="1800">30 minuten</option>
|
|
||||||
<option value="3600">60 minuten</option>
|
|
||||||
<option value="43200">12 stunden</option>
|
|
||||||
<option value="86400">24 stunden</option>
|
|
||||||
<option value="604800">1 woche</option>
|
|
||||||
<option value="2678400">1 monat</option>
|
|
||||||
</select>
|
|
||||||
<br />
|
|
||||||
<input class="main button" type="submit" value="Hochladen" />
|
|
||||||
</form>
|
|
||||||
</main>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
|
@ -0,0 +1,4 @@
|
||||||
|
const originSpans = document.querySelectorAll(".origin");
|
||||||
|
for (const originSpan of originSpans) {
|
||||||
|
originSpan.textContent = window.location.origin;
|
||||||
|
}
|
|
@ -0,0 +1,4 @@
|
||||||
|
const fileInput = document.getElementById("file-upload");
|
||||||
|
window.addEventListener('paste', e => {
|
||||||
|
fileInput.files = e.clipboardData.files;
|
||||||
|
});
|
|
@ -0,0 +1,38 @@
|
||||||
|
const fileUpload = document.getElementById('file-upload');
|
||||||
|
const textUpload = document.getElementById('text-upload');
|
||||||
|
const keepFor = document.getElementById('keep_for');
|
||||||
|
const passwordInput = document.getElementById('password-input');
|
||||||
|
|
||||||
|
const maxTime = Number('{no_auth_max_time}');
|
||||||
|
const largeFileMaxTime = Number('{no_auth_large_file_max_time}');
|
||||||
|
const largeFileSize = Number('{no_auth_large_file_size}');
|
||||||
|
|
||||||
|
let keep = Number(keepFor.value);
|
||||||
|
let size = fileUpload.files[0]
|
||||||
|
? fileUpload.files[0].size
|
||||||
|
: textUpload.value.length;
|
||||||
|
|
||||||
|
const updatePasswordInput = () => {
|
||||||
|
const requirePassword =
|
||||||
|
keep > maxTime || (size > largeFileSize && keep > largeFileMaxTime);
|
||||||
|
passwordInput.className = requirePassword ? '' : 'hidden';
|
||||||
|
};
|
||||||
|
|
||||||
|
updatePasswordInput();
|
||||||
|
|
||||||
|
fileUpload.addEventListener('change', () => {
|
||||||
|
size = fileUpload.files[0]
|
||||||
|
? fileUpload.files[0].size
|
||||||
|
: textUpload.value.length;
|
||||||
|
updatePasswordInput();
|
||||||
|
});
|
||||||
|
textUpload.addEventListener('input', () => {
|
||||||
|
if (!fileUpload.files[0]) {
|
||||||
|
size = textUpload.value.length;
|
||||||
|
updatePasswordInput();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
keepFor.addEventListener('change', () => {
|
||||||
|
keep = Number(keepFor.value);
|
||||||
|
updatePasswordInput();
|
||||||
|
});
|
|
@ -0,0 +1,99 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="de-DE">
|
||||||
|
<head>
|
||||||
|
<title>datatrash</title>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="description" content="Temporärer Dateiaustausch" />
|
||||||
|
<link href="/static/index.css" rel="stylesheet" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
|
||||||
|
<link
|
||||||
|
rel="icon"
|
||||||
|
type="image/vnd.microsoft.icon"
|
||||||
|
href="/static/favicon.ico"
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>datatrash<img src="/static/favicon.svg" class="icon" /></h1>
|
||||||
|
<form action="/upload" method="POST" enctype="multipart/form-data">
|
||||||
|
<label for="file-upload">datei{max_size_snippet}</label>
|
||||||
|
<br />
|
||||||
|
<input id="file-upload" type="file" name="file" />
|
||||||
|
<br />
|
||||||
|
<label for="text-upload">oder asciitrash</label>
|
||||||
|
<br />
|
||||||
|
<textarea id="text-upload" name="text" rows="15" cols="120"></textarea>
|
||||||
|
<br />
|
||||||
|
<input
|
||||||
|
id="delete_on_download"
|
||||||
|
type="checkbox"
|
||||||
|
name="delete_on_download"
|
||||||
|
/>
|
||||||
|
<label for="delete_on_download">nach einem download löschen</label>
|
||||||
|
<br />
|
||||||
|
<label for="keep_for">gültig für</label>
|
||||||
|
<select id="keep_for" name="keep_for">
|
||||||
|
<option value="1800">30 minuten</option>
|
||||||
|
<option value="3600">60 minuten</option>
|
||||||
|
<option value="43200">12 stunden</option>
|
||||||
|
<option value="86400">24 stunden</option>
|
||||||
|
<option value="604800">eine woche</option>
|
||||||
|
<option value="2678400">einen monat</option>
|
||||||
|
</select>
|
||||||
|
<br />{auth_snippet}
|
||||||
|
<input class="main button" type="submit" value="hochladen" />
|
||||||
|
</form>
|
||||||
|
<details class="usage">
|
||||||
|
<summary>nutzung als api</summary>
|
||||||
|
<p>
|
||||||
|
<label>datei hochladen</label>
|
||||||
|
<code
|
||||||
|
>curl -F 'file=@yourfile.rs'
|
||||||
|
<span class="origin"><origin></span>/upload</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>text hochladen</label>
|
||||||
|
<code
|
||||||
|
>curl -F 'text=your text'
|
||||||
|
<span class="origin"><origin></span>/upload</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>zeitbegrenzung setzen</label>
|
||||||
|
<code
|
||||||
|
>curl -F 'text=your text' -F 'keep_for=1800'
|
||||||
|
<span class="origin"><origin></span>/upload</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>nach einem download löschen</label>
|
||||||
|
<code
|
||||||
|
>curl -F 'text=your text' -F 'delete_on_download=true'
|
||||||
|
<span class="origin"><origin></span>/upload</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<label>authentifizieren</label>
|
||||||
|
<code
|
||||||
|
>curl -F 'text=your text' -F 'password=…'
|
||||||
|
<span class="origin"><origin></span>/upload</code
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
</details>
|
||||||
|
</main>
|
||||||
|
<footer>
|
||||||
|
{abuse}
|
||||||
|
<a
|
||||||
|
href="https://git.ctdo.de/neri/datatrash"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
repo
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
<script nonce="{script_nonce}" src="/static/paste.js"></script>
|
||||||
|
<script nonce="{script_nonce}" src="/static/origin.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,41 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="de-DE">
|
||||||
|
<head>
|
||||||
|
<title>datatrash</title>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link href="/static/index.css" rel="stylesheet" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
|
||||||
|
<link
|
||||||
|
rel="icon"
|
||||||
|
type="image/vnd.microsoft.icon"
|
||||||
|
href="/static/favicon.ico"
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>
|
||||||
|
<a href="/">datatrash<img src="/static/favicon.svg" class="icon" /></a>
|
||||||
|
</h1>
|
||||||
|
{file_name}
|
||||||
|
<textarea id="text" rows="20" cols="120" readonly>{text}</textarea>
|
||||||
|
<br />
|
||||||
|
<a class="main button" href="?dl">herunterladen</a>
|
||||||
|
<button id="copy" data-copy="#text" class="button hidden">
|
||||||
|
text kopieren
|
||||||
|
</button>
|
||||||
|
<a class="button" href="?raw">roh anzeigen</a>
|
||||||
|
</main>
|
||||||
|
<footer>
|
||||||
|
{abuse}
|
||||||
|
<a
|
||||||
|
href="https://git.ctdo.de/neri/datatrash"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
repo
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
<script nonce="{script_nonce}" src="/static/copy.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,41 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="de-DE">
|
||||||
|
<head>
|
||||||
|
<title>datatrash</title>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link href="/static/index.css" rel="stylesheet" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
|
||||||
|
<link
|
||||||
|
rel="icon"
|
||||||
|
type="image/vnd.microsoft.icon"
|
||||||
|
href="/static/favicon.ico"
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>
|
||||||
|
<a href="/">datatrash<img src="/static/favicon.svg" class="icon" /></a>
|
||||||
|
</h1>
|
||||||
|
<p>link: <a id="link" href="{link}">{link}</a></p>
|
||||||
|
<p>shortlink: <a id="shortlink" href="{shortlink}">{shortlink}</a></p>
|
||||||
|
<button id="copy" data-copy="#link" class="main button hidden">
|
||||||
|
link kopieren
|
||||||
|
</button>
|
||||||
|
<button id="copy-short" data-copy="#shortlink" class="button hidden">
|
||||||
|
shortlink kopieren
|
||||||
|
</button>
|
||||||
|
</main>
|
||||||
|
<footer>
|
||||||
|
{abuse}
|
||||||
|
<a
|
||||||
|
href="https://git.ctdo.de/neri/datatrash"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
repo
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
<script nonce="{script_nonce}" src="/static/copy.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -1,20 +1,37 @@
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html lang="de-DE">
|
||||||
<head>
|
<head>
|
||||||
<title>datatrash</title>
|
<title>datatrash</title>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
<link href="/static/index.css" rel="stylesheet" />
|
<link href="/static/index.css" rel="stylesheet" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
|
||||||
|
<link
|
||||||
|
rel="icon"
|
||||||
|
type="image/vnd.microsoft.icon"
|
||||||
|
href="/static/favicon.ico"
|
||||||
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<main>
|
<main>
|
||||||
<h1><a href="/">datatrash</a></h1>
|
<h1>
|
||||||
<p>
|
<a href="/">datatrash<img src="/static/favicon.svg" class="icon" /></a>
|
||||||
Datei-Link:
|
</h1>
|
||||||
<a href="{url}">
|
<p>link: <a id="link" href="{link}">{link}</a></p>
|
||||||
{url}
|
<button id="copy" data-copy="#link" class="main button hidden">
|
||||||
</a>
|
link kopieren
|
||||||
</p>
|
</button>
|
||||||
</main>
|
</main>
|
||||||
|
<footer>
|
||||||
|
{abuse}
|
||||||
|
<a
|
||||||
|
href="https://git.ctdo.de/neri/datatrash"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
repo
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
<script nonce="{script_nonce}" src="/static/copy.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
@ -0,0 +1,49 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="de-DE">
|
||||||
|
<head>
|
||||||
|
<title>datatrash</title>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<link href="/static/index.css" rel="stylesheet" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg" />
|
||||||
|
<link
|
||||||
|
rel="icon"
|
||||||
|
type="image/vnd.microsoft.icon"
|
||||||
|
href="/static/favicon.ico"
|
||||||
|
/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>
|
||||||
|
<a href="/">datatrash<img src="/static/favicon.svg" class="icon" /></a>
|
||||||
|
</h1>
|
||||||
|
<a
|
||||||
|
id="link"
|
||||||
|
class="large-link"
|
||||||
|
href="{link_attribute}"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>{link_content}</a
|
||||||
|
>
|
||||||
|
<br />
|
||||||
|
<a class="main button" href="{link_attribute}" rel="noopener noreferrer">
|
||||||
|
link öffnen
|
||||||
|
</a>
|
||||||
|
<button id="copy" data-copy="#link" class="button hidden">
|
||||||
|
link kopieren
|
||||||
|
</button>
|
||||||
|
<a class="button" href="?dl">als text herunterladen</a>
|
||||||
|
<a class="button" href="?raw">roh anzeigen</a>
|
||||||
|
</main>
|
||||||
|
<footer>
|
||||||
|
{abuse}
|
||||||
|
<a
|
||||||
|
href="https://git.ctdo.de/neri/datatrash"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
repo
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
<script nonce="{script_nonce}" src="/static/copy.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -1,34 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>datatrash</title>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
||||||
<link href="/static/index.css" rel="stylesheet" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<main>
|
|
||||||
<h1><a href="/">datatrash</a></h1>
|
|
||||||
<textarea id="text" rows="20" cols="120" readonly>{text}</textarea>
|
|
||||||
<br />
|
|
||||||
<a class="main button" href="?raw">Herunterladen</a>
|
|
||||||
<button id="copy" class="button" onclick="copyToClipboard()">
|
|
||||||
Text kopieren
|
|
||||||
</button>
|
|
||||||
</main>
|
|
||||||
<script lang="javascript">
|
|
||||||
function copyToClipboard() {
|
|
||||||
const button = document.getElementById("copy");
|
|
||||||
if (!navigator.clipboard) {
|
|
||||||
button.innerText = "Nicht unterstützt";
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const textarea = document.getElementById("text");
|
|
||||||
navigator.clipboard.writeText(textarea.value).then(
|
|
||||||
_ => { button.innerText = "Kopiert!"; },
|
|
||||||
_ => { button.innerText = "Nicht unterstützt"; },
|
|
||||||
);
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
Loading…
Reference in New Issue