#!/bin/sh # ezfs: upload files to ezfileshare from the command line and get one download link. # # ezfs report.pdf photos.zip # link=$(ezfs -q release.zip) # # The link goes to standard output; progress and errors go to standard error. The exit # status is 0 only when the link was created. # # A plain POSIX shell script (sh, bash, zsh, dash, BusyBox ash): nothing to install. It # sends files with whichever of these it finds first: curl, wget (GNU 1.15 or newer), # HTTPie. Everything it does goes through the site's API (backend/main.py): # # GET /api/info limits (files per link, size per file) # POST /api/shares announce the files; returns a share id and upload token # PUT /api/shares/{id}/files/{fileId} send one file # GET /api/shares/{id}/progress follow the virus scan; "ready" means the link works # GET /api/shares/{id} the published link's expiry date # # build.sh fills in the version and the default site. No double curly braces anywhere in # this file: the web server treats them as a template when it serves the script. VERSION='4508abbc1ee1' DEFAULT_SERVER='https://ezfileshare.io' ATTEMPTS=3 # per file, for failures that may pass (network, busy server) SCAN_WAIT=4200 # seconds to wait for the virus scan; the server gives up after an hour idle server=${EZFS_SERVER:-$DEFAULT_SERVER} quiet=0 token='' tmp='' say() { [ "$quiet" = 1 ] || printf '%s\n' "$*" >&2; } die() { printf 'ezfs: error: %s\n' "$*" >&2 exit 1 } usage() { cat <... Uploads the files to $server and prints one download link for all of them. No account needed. Options: -s, --server SITE the ezfileshare site to upload to (or set EZFS_SERVER) -q, --quiet print only the link, no progress -V, --version print the version and exit -h, --help show this help EOF } # ---------- options ---------- while [ $# -gt 0 ]; do case $1 in -s | --server) [ $# -ge 2 ] || die "$1 needs a site address" server=$2 shift 2 ;; --server=*) server=${1#--server=} shift ;; -q | --quiet) quiet=1 shift ;; -V | --version) echo "ezfs $VERSION" exit 0 ;; -h | --help) usage exit 0 ;; --) shift break ;; -?*) die "unknown option $1 (see ezfs --help)" ;; *) break ;; esac done if [ $# -eq 0 ]; then usage >&2 exit 2 fi # Updates always come from the packaged release site, independent of --server. release_get() { if command -v curl >/dev/null 2>&1; then curl -fsS --max-time 30 "$1" elif command -v wget >/dev/null 2>&1; then wget -q --max-redirect=0 -T 30 -O - "$1" else http --check-status --ignore-stdin --timeout=30 --pretty=none --print=b GET "$1" fi } checksum() { if command -v sha256sum >/dev/null 2>&1; then sha256sum < "$1" else shasum -a 256 < "$1"; fi | awk '{print $1}' } if [ "$VERSION" != dev ]; then case $DEFAULT_SERVER in https://*) ;; *) die "updates require an HTTPS release site" ;; esac manifest=$(release_get "${DEFAULT_SERVER%/}/cli/SHA256SUMS") || die "cannot check for updates" expected=$(printf '%s\n' "$manifest" | awk '$2 == "ezfs" {print $1}') [ "${#expected}" = 64 ] || die "invalid release checksum" if [ "$(checksum "$0")" != "$expected" ]; then candidate=$(mktemp "$0.update.XXXXXX") || die "cannot write update next to $0" trap 'rm -f "$candidate"' EXIT release_get "${DEFAULT_SERVER%/}/cli/ezfs" > "$candidate" && [ "$(checksum "$candidate")" = "$expected" ] && chmod 755 "$candidate" && mv -f "$candidate" "$0" || die "update failed" if [ "$quiet" = 1 ]; then set -- -q --server "$server" -- "$@" else set -- --server "$server" -- "$@"; fi exec sh "$0" "$@" fi fi # "share.example.com" and "https://share.example.com/" both work. server=${server%/} case $server in *://*) ;; *) server="https://$server" ;; esac # ---------- how to talk HTTP ---------- # The first tool that can send a file as a request body. EZFS_TOOL forces one (for testing). pick_tool() { if [ -n "${EZFS_TOOL:-}" ]; then echo "$EZFS_TOOL" elif command -v curl >/dev/null 2>&1; then echo curl elif command -v wget >/dev/null 2>&1 && wget --help 2>&1 | grep -q -e '--body-file'; then echo wget elif command -v http >/dev/null 2>&1 && http --version >/dev/null 2>&1; then echo httpie fi } tool=$(pick_tool) case $tool in curl | wget | httpie) ;; '') die "needs curl, wget (GNU wget 1.15 or newer) or HTTPie to send files; install one and try again" ;; *) die "EZFS_TOOL must be curl, wget or httpie" ;; esac tmp=$(mktemp -d 2>/dev/null || mktemp -d -t ezfs) || die "couldn't create a temporary folder" trap 'rm -rf "$tmp"' EXIT trap 'exit 130' INT TERM agent="ezfs-cli/$VERSION ($tool)" # request METHOD URL [BODY-FILE CONTENT-TYPE [progress]] # Leaves the HTTP status in $status ("000": no answer) and the answer in $tmp/reply. request() { r_method=$1 r_url=$2 r_body=${3:-} r_type=${4:-} r_progress=${5:-} : >"$tmp/reply" : >"$tmp/log" case $tool in curl) r_bar=--silent if [ -n "$r_progress" ] && [ "$quiet" = 0 ] && [ -t 2 ]; then r_bar=--progress-bar; fi if [ -z "$r_body" ]; then status=$(curl --silent --show-error -X "$r_method" -A "$agent" -H "X-Upload-Token: $token" \ -o "$tmp/reply" -w '%{http_code}' "$r_url" 2>"$tmp/log") elif [ "$r_bar" = --progress-bar ]; then # -T streams the file from disk with its length; the bar goes straight to the terminal. status=$(curl --progress-bar -X "$r_method" -T "$r_body" -A "$agent" -H "Content-Type: $r_type" \ -H "X-Upload-Token: $token" -H 'Expect:' -o "$tmp/reply" -w '%{http_code}' "$r_url") else status=$(curl --silent --show-error -X "$r_method" -T "$r_body" -A "$agent" -H "Content-Type: $r_type" \ -H "X-Upload-Token: $token" -H 'Expect:' -o "$tmp/reply" -w '%{http_code}' "$r_url" 2>"$tmp/log") fi ;; wget) if [ -z "$r_body" ]; then wget -q -S --tries=1 --content-on-error --method="$r_method" -U "$agent" \ --header="X-Upload-Token: $token" -O "$tmp/reply" "$r_url" 2>"$tmp/log" else wget -q -S --tries=1 --content-on-error --method="$r_method" --body-file="$r_body" -U "$agent" \ --header="Content-Type: $r_type" --header="X-Upload-Token: $token" -O "$tmp/reply" "$r_url" 2>"$tmp/log" fi # -S prints the answer's headers; the last status line is the final answer. status=$(sed -n 's/^ *HTTP\/[0-9.]* \([0-9][0-9][0-9]\).*/\1/p' "$tmp/log" | tail -n 1) ;; httpie) if [ -z "$r_body" ]; then http --ignore-stdin --pretty=none --print=hb "$r_method" "$r_url" "User-Agent:$agent" \ "X-Upload-Token:$token" >"$tmp/raw" 2>"$tmp/log" elif [ ! -s "$r_body" ]; then # An empty file: HTTPie sends no usable body from empty input, so say so ourselves. http --ignore-stdin --pretty=none --print=hb "$r_method" "$r_url" "User-Agent:$agent" "Content-Type:$r_type" \ "Content-Length:0" "X-Upload-Token:$token" >"$tmp/raw" 2>"$tmp/log" else # Standard input as the body is streamed, with the Content-Length we give. http --pretty=none --print=hb "$r_method" "$r_url" "User-Agent:$agent" "Content-Type:$r_type" \ "Content-Length:$(file_size "$r_body")" "X-Upload-Token:$token" <"$r_body" >"$tmp/raw" 2>"$tmp/log" fi # Headers, a blank line, then the body. status=$(sed -n '1s/^HTTP\/[0-9.]* \([0-9][0-9][0-9]\).*/\1/p' "$tmp/raw") tr -d '\r' <"$tmp/raw" | sed '1,/^$/d' >"$tmp/reply" ;; esac case $status in [1-5][0-9][0-9]) ;; *) status=000 ;; esac } # ---------- small helpers ---------- file_size() { wc -c <"$1" | tr -d ' '; } # "1.5 GB", 1024-based like the web app. human() { awk -v b="$1" 'BEGIN { split("B KB MB GB TB", u, " "); i = 1 while (b >= 1000 && i < 5) { b /= 1024; i++ } if (i == 1 || b >= 100) printf "%d %s", b, u[i]; else printf "%.1f %s", b, u[i] }' } # A number field of the JSON answer in $tmp/reply: json_number max_files json_number() { sed -n 's/.*"'"$1"'" *: *\([0-9][0-9]*\).*/\1/p' "$tmp/reply" | head -n 1; } # The server's own explanation of an error, FastAPI's {"detail": "..."}; empty if there is none. detail() { d=$(sed -n 's/.*"detail" *: *"\([^"]*\)".*/\1/p' "$tmp/reply" | head -n 1) [ -z "$d" ] && d=$(sed -n 's/.*"msg" *: *"\([^"]*\)".*/\1/p' "$tmp/reply" | head -n 1) [ -n "$d" ] && printf ' (%s)' "$d" } # Why the last request failed, as a sentence. problem() { case $status in 000) why=$(grep -v '^ *$' "$tmp/log" 2>/dev/null | tail -n 1 | sed 's/ (Caused by.*//; s/^http: error: //' | cut -c 1-200) printf "can't reach %s%s" "$server" "${why:+ ($why)}" ;; 404) printf 'the server no longer knows this upload (it may have timed out)' ;; 409) printf 'the server is still handling an earlier attempt' ;; 413 | 422) printf 'the server refused the files%s' "$(detail)" ;; *) printf 'the server answered %s%s' "$status" "$(detail)" ;; esac } # Whether the last failure may pass if we try again. retryable() { case $status in 000 | 409 | 429 | 5??) return 0 ;; *) return 1 ;; esac } # ---------- 1. limits ---------- max_files=100 max_size=17179869184 # 16 GiB; replaced by what the server says request GET "$server/api/info" if [ "$status" = 200 ] && grep -q '"service" *: *"ezfileshare"' "$tmp/reply"; then n=$(json_number max_files) && [ -n "$n" ] && max_files=$n n=$(json_number max_file_size) && [ -n "$n" ] && max_size=$n elif [ "$status" = 000 ]; then die "$(problem)" fi # Any other answer: an older server without /api/info. Carry on with the usual limits; # the server checks them itself anyway. # ---------- 2. check the files, before anything is sent ---------- [ $# -le "$max_files" ] || die "$# files given, but one link holds at most $max_files" json='{"files":[' sep='' for path in "$@"; do [ -e "$path" ] || die "$path: no such file" [ ! -d "$path" ] || die "$path is a folder; zip it first, or name the files in it" [ -f "$path" ] || die "$path is not a regular file" [ -r "$path" ] || die "$path: permission denied" size=$(file_size "$path") # awk compares as numbers of any size; the shell's own arithmetic may be 32-bit. if awk -v s="$size" -v m="$max_size" 'BEGIN { exit !(s > m) }'; then die "$path is $(human "$size"); the limit is $(human "$max_size") per file" fi # The name as a JSON string: drop control characters, escape \ and ". name=$(basename -- "$path" | tr -d '\000-\037' | sed 's/\\/\\\\/g; s/"/\\"/g') json="$json$sep{\"name\":\"$name\",\"size\":$size}" sep=',' done printf '%s]}' "$json" >"$tmp/create.json" # ---------- 3. announce the files ---------- request POST "$server/api/shares" "$tmp/create.json" application/json case $status in 201) ;; 404 | 405) die "$server doesn't look like an ezfileshare site (it answered $status)" ;; *) die "couldn't start the upload: $(problem)" ;; esac # The first ID identifies the share (10 characters, or 8 on older servers). # The remaining IDs identify files, in request order, and are always 8 characters. # (A file name can't fake one: inside a JSON string its quotes are escaped.) grep -o '"id" *: *"[A-Za-z0-9]*"' "$tmp/reply" | sed 's/.*"\([A-Za-z0-9]*\)"$/\1/' >"$tmp/ids" awk 'length != 8 && !(NR == 1 && length == 10) {exit 1}' "$tmp/ids" || die "unexpected identifier from $server" share=$(sed -n 1p "$tmp/ids") token=$(sed -n 's/.*"token" *: *"\([A-Za-z0-9_-]*\)".*/\1/p' "$tmp/reply" | head -n 1) if [ -z "$share" ] || [ -z "$token" ] || [ "$(wc -l <"$tmp/ids" | tr -d ' ')" -ne $(($# + 1)) ]; then die "unexpected answer from $server; is this an ezfileshare site?" fi file_id() { sed -n "$(($1 + 1))p" "$tmp/ids"; } # ---------- 4. send each file ---------- # send PATH ID LABEL: one file, trying again after failures that may pass. send() { s_path=$1 s_id=$2 s_label=$3 s_try=1 while :; do say "$s_label $(human "$(file_size "$s_path")")" request PUT "$server/api/shares/$share/files/$s_id" "$s_path" application/octet-stream progress case $status in 200 | 202) return 0 ;; esac if ! retryable || [ "$s_try" -ge "$ATTEMPTS" ]; then die "$(basename -- "$s_path"): $(problem)" fi s_try=$((s_try + 1)) say " $(problem); trying again ($s_try of $ATTEMPTS)" sleep $((s_try * 2)) done } i=0 for path in "$@"; do i=$((i + 1)) send "$path" "$(file_id "$i")" "[$i/$#] $(basename -- "$path")" done # ---------- 5. wait for the virus scan ---------- # The server scans files in the background after they arrive. A file whose scan failed on # the server's side is sent again; a file with malware ends the upload. : >"$tmp/resent" waited=0 failures=0 announced=0 while :; do request GET "$server/api/shares/$share/progress" if [ "$status" = 200 ]; then failures=0 grep -q '"ready" *: *true' "$tmp/reply" && break # One line per file: " ". tr -d ' \n' <"$tmp/reply" | grep -o '"id":"[A-Za-z0-9]*","received":[0-9]*,"status":"[a-z]*"' | sed 's/"id":"\([^"]*\)".*"status":"\([a-z]*\)"/\1 \2/' >"$tmp/states" i=0 for path in "$@"; do i=$((i + 1)) id=$(file_id "$i") state=$(sed -n "s/^$id //p" "$tmp/states") case $state in infected) die "$(basename -- "$path") was blocked: malware detected. No link was created" ;; scanning) [ "$announced" = 1 ] || say "Checking for viruses…" announced=1 ;; error) echo "$id" >>"$tmp/resent" if [ "$(grep -c "^$id\$" "$tmp/resent")" -ge "$ATTEMPTS" ]; then die "$(basename -- "$path"): the server couldn't check the file for viruses; try again later" fi say " $(basename -- "$path"): the virus check failed on the server; sending it again" send "$path" "$id" "[$i/$#] $(basename -- "$path")" ;; esac done else failures=$((failures + 1)) if ! retryable || [ "$failures" -gt 10 ]; then die "couldn't confirm the upload: $(problem)"; fi fi [ "$waited" -lt "$SCAN_WAIT" ] || die "the server didn't finish checking the files in time; try again later" sleep 1 waited=$((waited + 1)) done # ---------- 6. the link ---------- # When it expires is nice to know, but not worth failing for. expires='' request GET "$server/api/shares/$share" if [ "$status" = 200 ]; then at=$(json_number expires_at) if [ -n "$at" ]; then expires=$(date -r "$at" '+%e %B %Y' 2>/dev/null || date -d "@$at" '+%e %B %Y' 2>/dev/null) || expires='' expires=${expires# } fi fi say "Link ready${expires:+, valid until $expires}:" printf '%s\n' "$server/s/$share"