summaryrefslogtreecommitdiff
path: root/tmp-upload
blob: aae822dc16f1bad22c70ae5f8e2cc896965bd6ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#!/bin/bash
host=0.0.0.0
port=1111

if [ -n "$1" ]; then
	if [[ $1 =~ ^[0-9]+$ ]]; then
		port=$1
	else
		echo "Usage: $0 port"
		exit 1
	fi
fi

# Temporary directory for storing uploads and PHP script
tmpdir="$(mktemp -d)"

out="$tmpdir/upload.php"
cleanup() {
	rm -rvf "$tmpdir"
}
trap cleanup EXIT

# wrap
startline=$(grep -hn -F -m 1 "# stuff ""below" "$0" | cut -d: -f1)
tail -n+$((startline+1)) "$0" > "$out"

php -d post_max_size=128M -d upload_max_filesize=128M \
	-d upload_tmp_dir="$tmpdir/" \
	-d open_basedir="$tmpdir/:$(pwd)/" \
	-S "$host:$port" "$out"
exit
# stuff below
<?php
function get_mime_type($file) {
	$finfo = new finfo(FILEINFO_MIME_TYPE | FILEINFO_MIME_ENCODING);
	if (!is_resource($finfo)) {
		return $finfo->file($file);
	}
	return false;
}

$url = urldecode($_SERVER['REQUEST_URI']);

/* treat non-browser programs specially, do not output HTML for them */
$userAgent = explode("/", filter_input(INPUT_SERVER, "HTTP_USER_AGENT"))[0];
$text_only = in_array($userAgent, array("curl", "Wget"));

/* Simply returning false causes PHP to parse (index).php. Unwanted,
 * therefore serve it here. First check whether the path is within the
 * current working directory, then whether the file exists or not. */
$cwdir = realpath(".");
if ($cwdir === FALSE) {
	http_response_code(500);
	exit;
}

$path = realpath("./" . $url);
if ($path === FALSE) {
	http_response_code(404);
	exit;
}
if (strpos($path . DIRECTORY_SEPARATOR, $cwdir . DIRECTORY_SEPARATOR) !== 0) {
	http_response_code(403);
	exit;
}

$relDir = '';

if (is_dir($path)) {
	if (substr($url, -1) !== '/') {
		header("Location: $url/");
		exit;
	}

	/* remove common prefix */
	$rootDir = realpath(".");
	if ($cwdir == '/') {
		$relDir = substr($path, strlen($cwdir));
	} else {
		$relDir = substr($path, strlen($cwdir . DIRECTORY_SEPARATOR));
	}
	if (!strlen($relDir)) {
		$relDir = '.';
	}
	$relDir .= DIRECTORY_SEPARATOR;
} else {
	/* determine content type and size in bytes */
	$filesize = filesize($path);
	$mimetype = get_mime_type($path);
	if (!$mimetype) {
		http_response_code(500);
		exit;
	}

	header("Content-Type: $mimetype");
	if ($filesize !== false) {
		header("Content-Length: $filesize");
	}

	error_log(sprintf("download %s %s %d", $mimetype, $path, $filesize));
	readfile($path);
	exit;
}

$msg = "";
if (isset($_FILES["file"]["name"]) && is_array($_FILES["file"]["name"])) {
	// file[] array upload
	$upload = $_FILES["file"];
	for ($i=0; $i<count($_FILES["file"]["name"]); $i++) {
		$upload = array();
		foreach ($_FILES["file"] as $key=>$vals) {
			$upload[$key] = $vals[$i];
		}
		$res = saveUpload($upload);
		if ($res) $msg .= "$res\n";
	}
} else if (isset($_FILES["file"]["name"])) {
	// single file upload
	$msg = saveUpload($_FILES["file"]);
}
function saveUpload($upload) {
	global $relDir;

	$msg = NULL;
	$name = trim(basename($upload["name"]), ".");
	$name = preg_replace('/[\x00-\x1F\x7F]/', '', $name);
	if ($relDir === '') {
		$msg = 'Invalid upload directory!';
	} else if ($name === '') {
		$msg = "No filename is given!";
	} else if (!$_FILES["file"]["size"]) {
		$msg = "I do not accept empty files!";
	} else {
		$filename = $relDir . $name;
		$is_dupe = file_equals($filename, $upload["tmp_name"], $upload["size"]);
		for ($i=1; !$is_dupe && file_exists($filename); $i++) {
			$filename = "$name.$i";
			$is_dupe = file_equals($filename, $upload["tmp_name"], $upload["size"]);
		}
		if ($is_dupe) {
			$msg = "Uploaded file is a duplicate of " . $filename;
		} else if (move_uploaded_file($upload["tmp_name"], $filename)) {
			$msg = "File is saved as " . $filename;
			error_log(sprintf("upload %s", $filename));
		} else {
			$msg = "File could not be saved.";
		}
	}
	return $msg;
}

if ($text_only) {
	header("Content-Type: text/plain");
	if ($msg) {
		echo "$msg\n";
	} else {
		echo "Usage: curl -F file=@input.txt ...\n";
	}
	exit;
}

?>
<!doctype html>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1">
<form action="." method="POST" enctype="multipart/form-data">
<input type="file" name="file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if ($msg) {
	printf("<p>%s</p>", nl2br(htmlspecialchars($msg)), false);
}

?>
<hr>
<pre>
<?php
mb_internal_encoding('UTF-8');
date_default_timezone_set('Europe/Amsterdam');
$dir = new DirectoryIterator($path);

foreach ($dir as $f) {
	$filename = $f->getFilename();
	/* skip top-level directory due to basedir restrictions */
	if ($filename == '..' && $relDir == '.' . DIRECTORY_SEPARATOR) {
		continue;
	}
	$len = mb_strlen($filename);
	$maxLen = $f->isDir() ? 49 : 50;
	if ($len > $maxLen) {
		$dispName = mb_substr($filename, 0, $maxLen - 3) . '..>';
	} else {
		$dispName = $filename;
	}
	if ($f->isDir()) {
		$filename .= '/';
		$dispName .= '/';
	}

	printf('<a href="%s">%s</a>%s %s %20d' . "\n",
		htmlspecialchars($filename),
		htmlspecialchars($dispName),
		str_repeat(' ', max(0, $maxLen - $len)),
		date('d-M-Y H:i', $f->getMTime()),
		$f->getSize()
		);
}
function file_equals($newFile, $refFile, $refSize) {
	if (!file_exists($newFile)) {
		return false;
	}
	$newSize = filesize($newFile);
	if ($newSize !== $refSize) {
		return false;
	}
	return md5_file($newFile) === md5_file($refFile);
}
?>
</pre>