-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.php
292 lines (251 loc) · 10.5 KB
/
functions.php
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
<?php
namespace {
/**
* @param DateInterval $interval The interval
* @param string[] $format
* @param string $separator
* @return string Formatted interval string.
*/
function human_date_interval(DateInterval $interval, $format = null, $separator = ', ') {
if (!is_array($format)) {
$format = [
'months' => '%d month(s)',
'days' => '%d day(s)',
'hours' => '%d hour(s)',
'minutes' => '%d minute(s)',
'seconds' => '%d second(s)',
];
}
$p1y = (new DateTime())->setTimeStamp(0)->add(new \DateInterval('P1Y'))->getTimeStamp();
$p1m = (new DateTime())->setTimeStamp(0)->add(new \DateInterval('P1M'))->getTimeStamp();
$p1d = (new DateTime())->setTimeStamp(0)->add(new \DateInterval('P1D'))->getTimeStamp();
$pt1h = (new DateTime())->setTimeStamp(0)->add(new \DateInterval('PT1H'))->getTimeStamp();
$pt1m = (new DateTime())->setTimeStamp(0)->add(new \DateInterval('PT1M'))->getTimeStamp();
$result['seconds'] = (new DateTime())->setTimeStamp(0)->add($interval)->getTimeStamp();
$result['years'] = (int) ($result['seconds'] / $p1y);
$result['months'] = (int) (($result['seconds'] = ($result['seconds'] - ($p1y * $result['years']))) / $p1m);
$result['days'] = (int) (($result['seconds'] = ($result['seconds'] - ($p1m * $result['months']))) / $p1d);
$result['hours'] = (int) (($result['seconds'] = ($result['seconds'] - ($p1d * $result['days']))) / $pt1h);
$result['minutes'] = (int) (($result['seconds'] = ($result['seconds'] - ($pt1h * $result['hours']))) / $pt1m);
$result['seconds'] = (int) ($result['seconds'] - ($pt1m * $result['minutes']));
$formattedResult = [];
foreach ($format as $t => $v) {
if ($result[$t] > 0) {
$formattedResult[$t] = sprintf($v, $result[$t]);
}
}
return implode($separator, $formattedResult);
}
/**
* @see https://stackoverflow.com/a/28047922/5431347
*
* @param int $bytes
* @return string
*/
function byteConvert($bytes)
{
if (!$bytes) {
return '0.00 B';
}
$s = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
$e = floor(log($bytes, 1024));
return round($bytes / (1024 ** $e), 2) . ' ' . $s[$e];
}
}
namespace CLiup {
use Defuse\Crypto\File;
use Fig\Http\Message\StatusCodeInterface;
use Slim\Psr7\Request;
use Slim\Psr7\Response;
use Slim\Routing\RouteContext;
function log($message, $level = 'INFO') {
file_put_contents('php://stderr', date('c') . " $level $message\n");
}
function generatePassword() {
global $context;
$dictFile = new \SplFileObject($context['WORDSLIST_FILE']);
$passwords = [];
$dictFile->seek(PHP_INT_MAX);
$lineCnt = $dictFile->key();
for ($i = 0; $i < $context['PASS_WORDS_COUNT']; $i++) {
do {
$dictFile->rewind();
$dictFile->seek(random_int(1, $lineCnt));
$word = trim($dictFile->fgets());
} while (!$word); // Make sure we never pick an empty word
$passwords[] = $word;
}
return implode('-', $passwords);
}
function getPasswordForLog($password) {
global $context;
return $context['LOG_PASSWORDS'] ? $password : '*HIDDEN*';
}
function getUploadHash(string $password) {
global $context;
return sha1($context['HASH_SALT'] . $password);
}
function getEncryptionKey(string $password) {
global $context;
return sha1($context['HASH_SALT'] . strrev($password));
}
function getUploadDir(string $uploadHash) {
global $context;
return $context['UPLOAD_DIR']
. '/' . substr($uploadHash, 0, 2)
. '/' . substr($uploadHash, 2, 2);
}
function getUploadFilePath(string $uploadHash) {
return getUploadDir($uploadHash) . "/$uploadHash";
}
function getUploadMetadataFilePath(string $uploadHash) {
return getUploadDir($uploadHash) . "/$uploadHash.json";
}
function getUploadMetadata(string $uploadHash) {
if (is_file($path = getUploadMetadataFilePath($uploadHash))) {
return json_decode(file_get_contents($path), true) ?: [];
}
return [];
}
/**
* @param \Slim\Psr7\UploadedFile $file
* @param string $uploadName
* @param string $password
*/
function moveUploadedFile(\Slim\Psr7\UploadedFile $file, string $uploadName, string $password) {
global $context;
$uploadHash = getUploadHash($password);
$uploadDir = getUploadDir($uploadHash);
if (!mkdir($uploadDir, $context['UPLOAD_DIR_PERMS'], true) && !is_dir($uploadDir)) {
log("Cannot create directory $uploadDir.", 'ERROR');
throw new \Exception('Cannot create directory ' . $uploadDir);
}
$metadata = [
'upload_name' => $uploadName,
'created_at' => date('c'),
'size' => $file->getSize()
];
encryptAndMoveFile($file, getUploadFilePath($uploadHash), $password, $metadata);
if ($context['TRACE_CLIENT_INFO']) {
$metadata['remote_ip'] = $_SERVER['HTTP_X_REAL_IP']
?? $_SERVER['HTTP_X_FORWARDED_FOR']
?? $_SERVER['REMOTE_ADDR'];
$metadata['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
}
if (!file_put_contents(getUploadMetadataFilePath($uploadHash), json_encode($metadata))) {
log("Could not write metadata file for $uploadHash.", 'ERROR');
}
if ($context['LOG_ACTIVITY']) {
log(sprintf(
'New file saved: %s with hash %s (%d bytes) Password: %s',
$uploadName,
$uploadHash,
$metadata['size'],
getPasswordForLog($password)
));
}
}
function encryptAndMoveFile(
\Slim\Psr7\UploadedFile $file,
string $targetPath,
string $password,
array &$metadata
) {
global $context;
if ($context['ENCRYPTION_ENABLED']) {
File::encryptFileWithPassword($file->getFilePath(), $targetPath, getEncryptionKey($password));
$metadata['encryption_enabled'] = true;
log("File encrypted successfully.");
} else {
$file->moveTo($targetPath);
$metadata['encryption_enabled'] = false;
log("File moved successfully without encryption.");
}
}
/**
* @param string $uploadName
* @param \Slim\Psr7\UploadedFile[] $files
* @param Request $request
* @param Response $response
* @return Response
* @throws \Exception
*/
function processUploadedFiles($uploadName, array $files, Request $request, Response $response) {
global $context,
$MEMORY_USAGE_START;
try {
if (empty($files)) {
log("Upload error, no file has been provided.", 'ERROR');
$response->getBody()->write("ERROR: No file has been provided.\n");
return $response->withStatus(StatusCodeInterface::STATUS_BAD_REQUEST, 'No file has been provided');
}
if (count($files) > 1) {
log("Upload error, more than one file has been provided.", 'ERROR');
$response->getBody()->write("ERROR: Only one file is allowed per call.\n");
return $response->withStatus(StatusCodeInterface::STATUS_BAD_REQUEST, 'Only one file is allowed per call');
}
$file = current($files);
$uploadName = basename(substr($uploadName, 0, $context['UPLOAD_NAME_MAX_LEN']));
$password = generatePassword();
moveUploadedFile($file, $uploadName, $password);
} catch (\Throwable $e) {
log("Upload error, could not move uploaded file:\n$e", 'ERROR');
$response->getBody()->write("ERROR: Could not save file, sorry.\n");
return $response->withStatus(
StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR,
'Could not save file, sorry'
);
}
$response = $response
->withHeader('CLIup-Upload-Name', $uploadName)
->withHeader('CLIup-File-Password', $password)
->withHeader('CLIup-File-Path', sprintf('/%s/%s', $password, $uploadName));
$response->getBody()->write("File uploaded successfully. The password for your file is:\n$password\n");
if ($baseUrl = $context['BASE_URL']) {
$downloadUrl = sprintf('%s/%s/%s', rtrim($baseUrl, '/'), $password, $uploadName);
$trustedUrl = true;
} else {
$downloadUrl = RouteContext::fromRequest($request)
->getRouteParser()
->fullUrlFor(
$request->getUri(),
'download-file',
['password' => $password, 'upload_name' => $uploadName]
)
;
$trustedUrl = false;
}
$response->getBody()->write("You can retrieve it using this URL: {$downloadUrl}\n");
$response->getBody()->write(" cURL: curl -OJ {$downloadUrl}\n");
$response->getBody()->write(" wget: wget -q --content-disposition {$downloadUrl}\n");
if (!$trustedUrl) {
$response->getBody()->write(
"Notice: This URL has been infered and might not be accurate. Set BASE_URL instead to prevent this.\n"
);
}
log(sprintf(
"New file uploaded successfully. Memory used: %s",
byteConvert(memory_get_usage() - $MEMORY_USAGE_START)
));
return $response;
}
/**
* @param string $password
* @return resource
*/
function getUploadFileStream(string $password) {
$uploadHash = getUploadHash($password);
$filePath = getUploadFilePath($uploadHash);
$metadata = getUploadMetadata($uploadHash);
if (!($metadata['encryption_enabled'] ?? false)) {
return fopen($filePath, 'rb');
}
$sourceFileHandler = fopen($filePath, 'rb');
$memHandler = fopen('php://memory', 'wb');
File::decryptResourceWithPassword($sourceFileHandler, $memHandler, getEncryptionKey($password));
fclose($sourceFileHandler);
log("Decrypted file $uploadHash to memory.");
rewind($memHandler);
return $memHandler;
}
}