Debian Codegraph @

mod_upload_progress.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #include <stdint.h>
2 #include <ctype.h>
3 #include <ap_config.h>
4 #include <http_core.h>
5 #include <http_log.h>
6 #include <http_protocol.h>
7 #include <http_request.h>
8 #include <apr_version.h>
9 #include <apr_pools.h>
10 #include <apr_strings.h>
11 #include "unixd.h"
12
13 #if APR_HAS_SHARED_MEMORY
14 #include "apr_rmm.h"
15 #include "apr_shm.h"
16 #else
17 #error "APR_HAS_SHARED_MEMORY required for upload_progress module"
18 #endif
19
20 #if APR_HAVE_UNISTD_H
21 #include <unistd.h>
22 #endif
23
24 #include "ap_backports.h"
25
26 #ifndef PROGRESS_ID
27 # define PROGRESS_ID "X-Progress-ID"
28 #endif
29 #ifndef JSON_CB_PARAM
30 # define JSON_CB_PARAM "callback"
31 #endif
32 #ifndef CACHE_FILENAME
33 # define CACHE_FILENAME "/tmp/upload_progress_cache"
34 #endif
35 #ifndef PROGRESS_EXPIRES
36 /* shared memory entries not updated in PROGRESS_EXPIRES seconds
37 will be reused when needed */
38 # define PROGRESS_EXPIRES 60
39 #endif
40 #ifndef UP_DEBUG
41 # define UP_DEBUG 0
42 #endif
43
44 #ifndef ARG_ALLOWED_PROGRESSID
45 # define ARG_ALLOWED_PROGRESSID "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_:./!{}"
46 #endif
47 #ifndef ARG_ALLOWED_JSONPCALLBACK
48 # define ARG_ALLOWED_JSONPCALLBACK "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._$"
49 #endif
50 #ifndef ARG_MINLEN_PROGRESSID
51 # define ARG_MINLEN_PROGRESSID 8
52 #endif
53 #ifndef ARG_MAXLEN_PROGRESSID
54 # define ARG_MAXLEN_PROGRESSID 128
55 #endif
56 #define UP_STRINGIFY(arg) #arg
57 #define UP_TOSTRING(arg) UP_STRINGIFY(arg)
58 #define UP_ID_FMT "." UP_TOSTRING(ARG_MAXLEN_PROGRESSID) "s"
59 #ifndef ARG_MINLEN_JSONPCALLBACK
60 # define ARG_MINLEN_JSONPCALLBACK 1
61 #endif
62 #ifndef ARG_MAXLEN_JSONPCALLBACK
63 /* This limit is set by most JS implementations on identifier length */
64 # define ARG_MAXLEN_JSONPCALLBACK 64
65 #endif
66
67 #if UP_DEBUG > 0
68 # if UP_DEBUG > 1
69 # define up_log(m,s,err,srv,fmtstr,...) ap_log_error( m, s, err, srv, "pid:%" APR_PID_T_FMT " " fmtstr, getpid(), ##__VA_ARGS__ )
70 # else
71 # define up_log(...) ap_log_error( __VA_ARGS__ )
72 # endif
73 #else
74 # define up_log(...)
75 #endif
76
77 #define CACHE_LOCK() do { \
78 if (config->cache_lock) { \
79 char errbuf[200]; \
80 up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "CACHE_LOCK()"); \
81 apr_status_t status = apr_global_mutex_lock(config->cache_lock); \
82 if (status != APR_SUCCESS) { \
83 ap_log_error(APLOG_MARK, APLOG_CRIT, status, server, \
84 "%s", apr_strerror(status, errbuf, sizeof(errbuf))); \
85 } \
86 } \
87 } while (0)
88
89 #define CACHE_UNLOCK() do { \
90 if (config->cache_lock) \
91 { \
92 up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "CACHE_UNLOCK()"); \
93 apr_global_mutex_unlock(config->cache_lock); \
94 } \
95 } while (0)
96
97 typedef struct {
98 int track_enabled;
99 int report_enabled;
100 } DirConfig;
101
102 typedef struct upload_progress_node_s{
103 apr_off_t length;
104 apr_off_t received;
105 int err_status;
106 time_t started_at;
107 apr_off_t speed; /* bytes per second */
108 time_t updated_at;
109 int done;
110 char key[ARG_MAXLEN_PROGRESSID];
111 } upload_progress_node_t;
112
113 typedef struct {
114 apr_time_t cache_updated_at;
115 upload_progress_node_t node;
116 } upload_progress_req_t;
117
118 typedef struct {
119 int count;
120 int active;
121 } upload_progress_cache_t;
122
123 typedef struct {
124 apr_global_mutex_t *cache_lock;
125 char *lock_file; /* filename for shm lock mutex */
126 apr_size_t cache_bytes;
127 apr_shm_t *cache_shm;
128 char *cache_file;
129 upload_progress_cache_t *cache;
130 int *list; /* static array of node indexes, list begins with indexes of active nodes */
131 upload_progress_node_t *nodes; /* all nodes allocated at once */
132 } ServerConfig;
133
134 static void upload_progress_cache_write(server_rec *, upload_progress_node_t *);
135 static upload_progress_node_t *find_node(server_rec *, const char *);
136 static apr_status_t upload_progress_cleanup(void *);
137 static const char *get_progress_id(request_rec *, int *);
138
139 extern module AP_MODULE_DECLARE_DATA upload_progress_module;
140
141 static server_rec *global_server = NULL;
142
143 static inline ServerConfig *get_server_config(server_rec *s)
144 {
145 return (ServerConfig *)ap_get_module_config(s->module_config, &upload_progress_module);
146 }
147
148 static inline DirConfig *get_dir_config(request_rec *r)
149 {
150 return (DirConfig *)ap_get_module_config(r->per_dir_config, &upload_progress_module);
151 }
152
153 static inline upload_progress_req_t *get_request_config(request_rec *r)
154 {
155 return (upload_progress_req_t *)ap_get_module_config(r->request_config, &upload_progress_module);
156 }
157
158
159 static int upload_progress_handle_request(request_rec *r)
160 {
161 server_rec *server = r->server;
162 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "upload_progress_handle_request()");
163
164 DirConfig *dir = get_dir_config(r);
165
166 if (!dir || (dir->track_enabled <= 0)) {
167 return DECLINED;
168 }
169 if (r->method_number != M_POST) {
170 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
171 "Upload Progress: Non-POST request in trackable location: %s.", r->uri);
172 return DECLINED;
173 }
174
175 int param_error;
176 const char *id = get_progress_id(r, &param_error);
177
178 if (id) {
179 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
180 "Upload Progress: Upload id='%s' in trackable location: %s.", id, r->uri);
181
182 upload_progress_req_t *reqinfo = (upload_progress_req_t *)apr_pcalloc(r->pool,
183 sizeof(upload_progress_req_t));
184 upload_progress_node_t *node = NULL;
185 if (reqinfo) {
186 reqinfo->cache_updated_at = apr_time_now();
187 upload_progress_node_t *node = &(reqinfo->node);
188
189 strncpy(node->key, id, ARG_MAXLEN_PROGRESSID);
190 time_t t = time(NULL);
191
192 node->received = 0;
193 node->done = 0;
194 node->err_status = 0;
195 node->started_at = t;
196 node->speed = 0;
197 node->updated_at = t;
198 const char *content_length = apr_table_get(r->headers_in, "Content-Length");
199 node->length = 1;
200 /* Content-Length is missing is case of chunked transfer encoding */
201 if (content_length)
202 sscanf(content_length, "%" APR_OFF_T_FMT, &(node->length));
203 }
204
205 ap_set_module_config(r->request_config, &upload_progress_module, reqinfo);
206 apr_pool_cleanup_register(r->pool, r, upload_progress_cleanup, apr_pool_cleanup_null);
207 ap_add_input_filter("UPLOAD_PROGRESS", NULL, r, r->connection);
208
209 upload_progress_cache_write(server, node);
210
211 } else if (param_error < 0) {
212 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
213 "Upload Progress: Upload with invalid ID in trackable location: %s.", r->uri);
214 /*
215 return HTTP_BAD_REQUEST;
216 return HTTP_NOT_FOUND;
217 */
218
219 } else {
220 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
221 "Upload Progress: Upload without ID in trackable location: %s.", r->uri);
222 }
223
224 return DECLINED;
225 }
226
227 static const char *report_upload_progress_cmd(cmd_parms *cmd, void *config, int arg)
228 {
229 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "report_upload_progress_cmd()");
230 DirConfig *dir = (DirConfig *)config;
231 dir->report_enabled = arg ? 1 : -1;
232 return NULL;
233 }
234
235 static const char *track_upload_progress_cmd(cmd_parms *cmd, void *config, int arg)
236 {
237 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "track_upload_progress_cmd()");
238 DirConfig *dir = (DirConfig *)config;
239 dir->track_enabled = arg ? 1 : -1;
240 return NULL;
241 }
242
243 static const char* upload_progress_shared_memory_size_cmd(cmd_parms *cmd,
244 void *dummy, const char *arg)
245 {
246 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "upload_progress_shared_memory_size_cmd()");
247 ServerConfig *config = get_server_config(cmd->server);
248
249 long long int n = atoi(arg);
250
251 if (n <= 0) {
252 return "UploadProgressSharedMemorySize should be positive";
253 }
254
255 config->cache_bytes = (apr_size_t)n;
256
257 return NULL;
258 }
259
260 static void *upload_progress_create_dir_config(apr_pool_t *p, char *dirspec)
261 {
262 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "upload_progress_create_dir_config()");
263 DirConfig *dir = (DirConfig *)apr_pcalloc(p, sizeof(DirConfig));
264 dir->track_enabled = 0;
265 dir->report_enabled = 0;
266 return dir;
267 }
268
269 static void *upload_progress_merge_dir_config(apr_pool_t *p, void *basev, void *overridev)
270 {
271 DirConfig *new = (DirConfig *)apr_pcalloc(p, sizeof(DirConfig));
272 DirConfig *override = (DirConfig *)overridev;
273 DirConfig *base = (DirConfig *)basev;
274 new->track_enabled = (override->track_enabled == 0) ? base->track_enabled :
275 (override->track_enabled > 0 ? 1 : -1);
276 new->report_enabled = (override->report_enabled == 0) ? base->report_enabled :
277 (override->report_enabled > 0 ? 1 : -1);
278 return new;
279 }
280
281 static void *upload_progress_create_server_config(apr_pool_t *p, server_rec *s)
282 {
283 if (!global_server) global_server = s;
284 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "upload_progress_create_server_config()");
285 ServerConfig *config = (ServerConfig *)apr_pcalloc(p, sizeof(ServerConfig));
286 config->cache_file = apr_pstrdup(p, CACHE_FILENAME);
287 config->cache_bytes = 51200;
288 return config;
289 }
290
291 static void *upload_progress_merge_server_config(apr_pool_t *p, void *basev,
292 void *overridesv)
293 {
294 return basev;
295 }
296
297 static int read_request_status(request_rec *r)
298 {
299 int status;
300
301 if (r) {
302 /* error status rendered in status line is preferred because passenger
303 clobbers request_rec->status when exception occurs */
304 /* FIXME: Shouldn't we read r->status instead as it's already preparsed? */
305 status = r->status_line ? atoi(r->status_line) : 0;
306 if (!ap_is_HTTP_VALID_RESPONSE(status))
307 status = r->status;
308 return status;
309 } else {
310 return 0;
311 }
312 }
313
314 static int track_upload_progress(ap_filter_t *f, apr_bucket_brigade *bb,
315 ap_input_mode_t mode, apr_read_type_e block,
316 apr_off_t readbytes)
317 {
318 server_rec *server = f->r->server;
319 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "track_upload_progress()");
320
321 apr_status_t rv = ap_get_brigade(f->next, bb, mode, block, readbytes);
322
323 upload_progress_req_t *reqinfo = get_request_config(f->r);
324 if (!reqinfo) {
325 up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "Request config not available");
326 return rv;
327 }
328 upload_progress_node_t *node = &(reqinfo->node);
329
330 time_t t = time(NULL);
331 node->updated_at = t;
332 if (rv == APR_SUCCESS) {
333 apr_off_t length;
334 apr_brigade_length(bb, 1, &length);
335 node->received += length;
336 if (node->received > node->length) /* handle chunked transfer */
337 node->length = node->received;
338 int upload_time = t - node->started_at;
339 if (upload_time > 0) {
340 node->speed = node->received / upload_time;
341 }
342 } else {
343 node->err_status = read_request_status(f->r);
344 reqinfo->cache_updated_at = 0; /* force cache update */
345 }
346
347 apr_time_t now = apr_time_now();
348 if ((now - reqinfo->cache_updated_at) > apr_time_from_msec(500)) {
349 reqinfo->cache_updated_at = now;
350 upload_progress_cache_write(server, node);
351 }
352
353 return rv;
354 }
355
356 static int check_request_argument(const char *value, int len, char *allowed, int minlen, int maxlen) {
357 /* Check the length of the argument */
358 if (len > maxlen) return -1;
359 if (len < minlen) return -2;
360 /* If no whitelist given, assume everything whitelisted */
361 if (!allowed) return 0;
362 /* Check each char to be in the whitelist */
363 if (strspn(value, allowed) < len) return -3;
364 return 0;
365 }
366
367 static char *get_param_value(char *p, const char *param_name, int *len) {
368 char pn1[3] = {toupper(param_name[0]), tolower(param_name[0]), 0};
369 int pn_len = strlen(param_name);
370 char *val_end;
371 static char *param_sep = "&";
372
373 while (p) {
374 if ((strncasecmp(p, param_name, pn_len) == 0) && (p[pn_len] == '='))
375 break;
376 if (*p) p++;
377 p = strpbrk(p, pn1);
378 }
379 if (p) {
380 p += (pn_len + 1);
381 *len = strcspn(p, param_sep);
382 }
383 return p;
384 }
385
386 static const char *get_progress_id(request_rec *r, int *param_error) {
387 int len;
388
389 /* try to find progress id in http headers */
390 const char *id = apr_table_get(r->headers_in, PROGRESS_ID);
391 if (id) {
392 *param_error = check_request_argument(id, strlen(id), ARG_ALLOWED_PROGRESSID,
393 ARG_MINLEN_PROGRESSID, ARG_MAXLEN_PROGRESSID);
394 if (*param_error) return NULL;
395 return id;
396 }
397
398 /* if progress id not found in headers, check request args (query string) */
399 id = get_param_value(r->args, PROGRESS_ID, &len);
400 if (id) {
401 *param_error = check_request_argument(id, len, ARG_ALLOWED_PROGRESSID,
402 ARG_MINLEN_PROGRESSID, ARG_MAXLEN_PROGRESSID);
403 if (*param_error) return NULL;
404 return apr_pstrndup(r->connection->pool, id, len);
405 }
406
407 *param_error = 1; /* not found */
408 return NULL;
409 }
410
411 static const char *get_json_callback_param(request_rec *r, int *param_error) {
412 char *val;
413 int len;
414
415 val = get_param_value(r->args, JSON_CB_PARAM, &len);
416 if (val) {
417 *param_error = check_request_argument(val, len, ARG_ALLOWED_JSONPCALLBACK,
418 ARG_MINLEN_JSONPCALLBACK, ARG_MAXLEN_JSONPCALLBACK);
419 if (*param_error) return NULL;
420 return apr_pstrndup(r->connection->pool, val, len);
421 }
422
423 *param_error = 1; /* not found */
424 return NULL;
425 }
426
427 static inline int check_node(upload_progress_node_t *node, const char *key) {
428 return ((node) && (strncasecmp(node->key, key, ARG_MAXLEN_PROGRESSID) == 0)) ? 1 : 0;
429 }
430
431 static upload_progress_node_t *find_node(server_rec *server, const char *key) {
432 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "find_node()");
433
434 ServerConfig *config = get_server_config(server);
435 upload_progress_cache_t *cache = config->cache;
436 upload_progress_node_t *node, *nodes = config->nodes;
437 int *list = config->list;
438 int active = cache->active;
439 int i;
440
441 for (i = 0; i < active; i++) {
442 node = &nodes[list[i]];
443 if (check_node(node, key))
444 return node;
445 }
446 return NULL;
447 }
448
449 static apr_status_t upload_progress_cleanup(void *data)
450 {
451 request_rec *r = (request_rec *)data;
452 server_rec *server = r->server;
453 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "upload_progress_cleanup()");
454
455 upload_progress_req_t *reqinfo = get_request_config(r);
456 if (!reqinfo) {
457 up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "Request config not available");
458 return APR_SUCCESS;
459 }
460 upload_progress_node_t *node = &(reqinfo->node);
461 node->err_status = read_request_status(r);
462 node->updated_at = time(NULL);
463 node->done = 1;
464 upload_progress_cache_write(server, node);
465
466 return APR_SUCCESS;
467 }
468
469 static void upload_progress_cache_write(server_rec *server, upload_progress_node_t *new_data)
470 {
471 if (!new_data) return;
472 ServerConfig *config = get_server_config(server);
473
474 CACHE_LOCK();
475 upload_progress_node_t *node = find_node(server, new_data->key);
476 time_t now = time(NULL);
477 #define EXPIRED(node,now) ((now - node->updated_at) > PROGRESS_EXPIRES)
478 if (node) {
479 /* reuse node if: request finished, expired, or same started_at as node */
480 if (node->started_at == new_data->started_at || node->done || EXPIRED(node, now)) {
481 memcpy(node, new_data, sizeof(upload_progress_node_t));
482 up_log(APLOG_MARK, APLOG_DEBUG, 0, server,
483 "Upload Progress: Reused existing node with id='%" UP_ID_FMT "'.", node->key);
484 } else {
485 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
486 "Upload Progress: Upload with id='%" UP_ID_FMT "' already exists, ignoring.", node->key);
487 }
488 } else {
489
490 up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "cleaning expired cache nodes");
491
492 upload_progress_cache_t *cache = config->cache;
493 upload_progress_node_t *nodes = config->nodes;
494 int *list = config->list;
495 int i, tmp;
496
497 /* check active nodes list, if expired node found
498 then swap it with last active and shrink active list by one */
499 for (i = 0; i < cache->active; i++) {
500 node = &nodes[list[i]];
501 if (EXPIRED(node, now)) {
502 cache->active -= 1;
503 tmp = list[cache->active];
504 list[cache->active] = list[i];
505 list[i] = tmp;
506 i--;
507 }
508 }
509
510 if (cache->active < cache->count) {
511 node = &config->nodes[config->list[cache->active]];
512 cache->active += 1;
513 memcpy(node, new_data, sizeof(upload_progress_node_t));
514 up_log(APLOG_MARK, APLOG_DEBUG, 0, server,
515 "Upload Progress: Added upload with id='%" UP_ID_FMT "' to list.", node->key);
516 } else {
517 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server, "Cache full");
518 }
519
520 }
521 CACHE_UNLOCK();
522
523 }
524
525 static apr_status_t upload_progress_cache_init(apr_pool_t *pool, ServerConfig *config)
526 {
527 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "upload_progress_cache_init()");
528
529 apr_status_t result;
530 apr_size_t size;
531 int nodes_cnt, i;
532
533 if (config->cache_file) {
534 /* Remove any existing shm segment with this name. */
535 apr_shm_remove(config->cache_file, pool);
536 unlink(config->cache_file);
537 }
538
539 size = APR_ALIGN_DEFAULT(config->cache_bytes);
540 result = apr_shm_create(&config->cache_shm, size, config->cache_file, pool);
541 if (result != APR_SUCCESS) {
542 return result;
543 }
544
545 /* Determine the usable size of the shm segment. */
546 size = apr_shm_size_get(config->cache_shm);
547 nodes_cnt = (size - sizeof(upload_progress_cache_t)) /
548 (sizeof(int) + sizeof(upload_progress_node_t));
549
550 /* init cache */
551 config->cache = (upload_progress_cache_t *)apr_shm_baseaddr_get(config->cache_shm);
552 config->list = (int *)(config->cache + 1);
553 config->nodes = (upload_progress_node_t *)(config->list + nodes_cnt);
554 config->cache->count = nodes_cnt;
555 config->cache->active = 0;
556 for (i = 0; i < nodes_cnt; i++) config->list[i] = i;
557
558 ap_log_error(APLOG_MARK, APLOG_INFO, 0, global_server,
559 "Upload Progress: monitoring max %i simultaneous uploads, id (%s) length %i..%i",
560 nodes_cnt, PROGRESS_ID, ARG_MINLEN_PROGRESSID, ARG_MAXLEN_PROGRESSID);
561
562 return APR_SUCCESS;
563 }
564
565 static int upload_progress_init(apr_pool_t *p, apr_pool_t *plog,
566 apr_pool_t *ptemp,
567 server_rec *s) {
568 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, s, "upload_progress_init()");
569
570 apr_status_t result;
571
572 ServerConfig *config = get_server_config(s);
573
574 void *data;
575 const char *userdata_key = "upload_progress_init";
576
577 /* upload_progress_init will be called twice. Don't bother
578 * going through all of the initialization on the first call
579 * because it will just be thrown away.*/
580 apr_pool_userdata_get(&data, userdata_key, s->process->pool);
581 if (!data) {
582 apr_pool_userdata_set((const void *)1, userdata_key,
583 apr_pool_cleanup_null, s->process->pool);
584
585 /* If the cache file already exists then delete it. Otherwise we are
586 * going to run into problems creating the shared memory. */
587 if (config->cache_file) {
588 char *lck_file = apr_pstrcat(ptemp, config->cache_file, ".lck",
589 NULL);
590 up_log(APLOG_MARK, APLOG_DEBUG, 0, s, "Upload Progress: Remove lock file");
591 apr_file_remove(lck_file, ptemp);
592 }
593 return OK;
594 }
595
596 /* initializing cache if shared memory size is not zero and we already
597 * don't have shm address
598 */
599 if (!config->cache_shm && config->cache_bytes > 0) {
600 result = upload_progress_cache_init(p, config);
601 if (result != APR_SUCCESS) {
602 ap_log_error(APLOG_MARK, APLOG_ERR, result, s,
603 "Upload Progress cache: could not create shared memory segment");
604 return DONE;
605 }
606
607 if (config->cache_file) {
608 config->lock_file = apr_pstrcat(p, config->cache_file, ".lck",
609 NULL);
610 }
611
612 result = apr_global_mutex_create(&config->cache_lock,
613 config->lock_file, APR_LOCK_DEFAULT,
614 p);
615 if (result != APR_SUCCESS) {
616 return result;
617 }
618
619 #ifdef AP_NEED_SET_MUTEX_PERMS
620 result = ap_unixd_set_global_mutex_perms(config->cache_lock);
621 if (result != APR_SUCCESS) {
622 ap_log_error(APLOG_MARK, APLOG_CRIT, result, s,
623 "Upload progress cache: failed to set mutex permissions");
624 return result;
625 }
626 #endif
627
628 } else {
629 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s,
630 "Upload Progress cache: cache size is zero, disabling "
631 "shared memory cache");
632 }
633
634 return(OK);
635 }
636
637 static int reportuploads_handler(request_rec *r)
638 {
639 server_rec *server = r->server;
640 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, server, "reportuploads_handler()");
641
642 upload_progress_node_t upload, *found;
643 int param_error;
644 char *response;
645 DirConfig *dir = get_dir_config(r);
646
647 if (!dir || (dir->report_enabled <= 0)) {
648 return DECLINED;
649 }
650 if (r->method_number != M_GET) {
651 return HTTP_METHOD_NOT_ALLOWED;
652 }
653
654 /* get the tracking id if any */
655 const char *id = get_progress_id(r, &param_error);
656
657 if (id == NULL) {
658 if (param_error < 0) {
659 ap_log_error(APLOG_MARK, APLOG_INFO, 0, server,
660 "Upload Progress: Report requested with invalid id. uri=%s", r->uri);
661 return HTTP_BAD_REQUEST;
662 } else {
663 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
664 "Upload Progress: Report requested without id. uri=%s", r->uri);
665 return HTTP_NOT_FOUND;
666 }
667 }
668
669 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, server,
670 "Upload Progress: Report requested with id='%s'. uri=%s", id, r->uri);
671
672 ServerConfig *config = get_server_config(server);
673
674 CACHE_LOCK();
675 found = find_node(server, id);
676 if (found) {
677 up_log(APLOG_MARK, APLOG_DEBUG, 0, server,
678 "Node with id=%s found for report", id);
679 memcpy(&upload, found, sizeof(upload));
680 } else {
681 up_log(APLOG_MARK, APLOG_DEBUG, 0, server,
682 "Node with id=%s not found for report", id);
683 }
684 CACHE_UNLOCK();
685
686 ap_set_content_type(r, "application/json");
687
688 apr_table_set(r->headers_out, "Expires", "Mon, 28 Sep 1970 06:00:00 GMT");
689 apr_table_set(r->headers_out, "Cache-Control", "no-cache");
690
691 /* There are 4 possibilities
692 * request not yet started: found = false
693 * request in error: err_status >= NGX_HTTP_SPECIAL_RESPONSE
694 * request finished: done = true
695 * request not yet started but registered: length==0 && rest ==0
696 * request in progress: rest > 0
697 */
698
699 if (!found) {
700 response = apr_psprintf(r->pool, "{ \"state\" : \"starting\", \"uuid\" : \"%s\" }", id);
701 } else if (upload.err_status >= HTTP_BAD_REQUEST ) {
702 response = apr_psprintf(r->pool, "{ "
703 "\"state\": \"error\", "
704 "\"status\": %d, "
705 "\"uuid\": \"%s\" "
706 "}", upload.err_status, id);
707 } else if (upload.done) {
708 response = apr_psprintf(r->pool, "{ "
709 "\"state\": \"done\", "
710 "\"size\": %" APR_OFF_T_FMT ", "
711 "\"speed\": %" APR_OFF_T_FMT ", "
712 "\"started_at\": %li, "
713 "\"completed_at\": %li, "
714 "\"uuid\": \"%s\" "
715 "}", upload.length, upload.speed, upload.started_at, upload.updated_at, id);
716 } else if (upload.received == 0) {
717 response = apr_psprintf(r->pool, "{ \"state\" : \"starting\", \"uuid\" : \"%s\" }", id);
718 } else {
719 time_t eta = 0, t = time(NULL);
720 if (upload.speed > 0) eta = upload.started_at + upload.length / upload.speed;
721 if (eta <= t) eta = t + 1;
722 response = apr_psprintf(r->pool, "{ "
723 "\"state\": \"uploading\", "
724 "\"received\": %" APR_OFF_T_FMT ", "
725 "\"size\": %" APR_OFF_T_FMT ", "
726 "\"speed\": %" APR_OFF_T_FMT ", "
727 "\"started_at\": %li, "
728 "\"eta\": %li, "
729 "\"uuid\": \"%s\" "
730 "}", upload.received, upload.length, upload.speed, upload.started_at, eta, id);
731 }
732
733 char *completed_response;
734
735 /* get the jsonp callback if any */
736 const char *jsonp = get_json_callback_param(r, &param_error);
737
738 if (param_error < 0) {
739 ap_log_error(APLOG_MARK, APLOG_INFO, 0, server,
740 "Upload Progress: Report requested with invalid JSON-P callback. uri=%s", r->uri);
741 return HTTP_BAD_REQUEST;
742 }
743
744 up_log(APLOG_MARK, APLOG_DEBUG, 0, server,
745 "Upload Progress: JSON-P callback: %s.", jsonp);
746
747 // fix up response for jsonp request, if needed
748 if (jsonp) {
749 completed_response = apr_psprintf(r->pool, "%s(%s);\r\n", jsonp, response);
750 } else {
751 completed_response = apr_psprintf(r->pool, "%s\r\n", response);
752 }
753
754 ap_rputs(completed_response, r);
755
756 return OK;
757 }
758
759 static void upload_progress_child_init(apr_pool_t *p, server_rec *s)
760 {
761 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, s, "upload_progress_child_init()");
762
763 apr_status_t rv;
764 ServerConfig *config = get_server_config(s);
765
766 if (!config->cache_lock) {
767 ap_log_error(APLOG_MARK, APLOG_CRIT, 0, s, "Global mutex not set.");
768 return;
769 }
770
771 rv = apr_global_mutex_child_init(&config->cache_lock, config->lock_file, p);
772 if (rv != APR_SUCCESS) {
773 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
774 "Failed to initialise global mutex %s in child process %"
775 APR_PID_T_FMT ".", config->lock_file, getpid());
776 }
777
778 if (!config->cache_shm) {
779 rv = apr_shm_attach(&config->cache_shm, config->cache_file, p);
780 if (rv != APR_SUCCESS) {
781 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, "Failed to attach to "
782 "shared memory file '%s'", config->cache_file);
783 return;
784 }
785 }
786
787 config->cache = (upload_progress_cache_t *)apr_shm_baseaddr_get(config->cache_shm);
788 config->list = (int *)(config->cache + 1);
789 config->nodes = (upload_progress_node_t *)(config->list + config->cache->count);
790 }
791
792 static const command_rec upload_progress_cmds[] =
793 {
794 AP_INIT_FLAG("TrackUploads", track_upload_progress_cmd, NULL, OR_AUTHCFG,
795 "Track upload progress in this location"),
796 AP_INIT_FLAG("ReportUploads", report_upload_progress_cmd, NULL, OR_AUTHCFG,
797 "Report upload progress in this location"),
798 AP_INIT_TAKE1("UploadProgressSharedMemorySize", upload_progress_shared_memory_size_cmd, NULL, RSRC_CONF,
799 "Size of shared memory used to keep uploads data, default 100KB"),
800 { NULL }
801 };
802
803 static void upload_progress_register_hooks (apr_pool_t *p)
804 {
805 /**/up_log(APLOG_MARK, APLOG_DEBUG, 0, global_server, "upload_progress_register_hooks()");
806
807 ap_hook_fixups(upload_progress_handle_request, NULL, NULL, APR_HOOK_FIRST);
808 ap_hook_handler(reportuploads_handler, NULL, NULL, APR_HOOK_FIRST);
809 ap_hook_post_config(upload_progress_init, NULL, NULL, APR_HOOK_MIDDLE);
810 ap_hook_child_init(upload_progress_child_init, NULL, NULL, APR_HOOK_MIDDLE);
811 ap_register_input_filter("UPLOAD_PROGRESS", track_upload_progress, NULL, AP_FTYPE_RESOURCE);
812 }
813
814 module AP_MODULE_DECLARE_DATA upload_progress_module =
815 {
816 STANDARD20_MODULE_STUFF,
817 upload_progress_create_dir_config,
818 upload_progress_merge_dir_config,
819 upload_progress_create_server_config,
820 upload_progress_merge_server_config,
821 upload_progress_cmds,
822 upload_progress_register_hooks, /* callback for registering hooks */
823 };