forked from openstreetmap/mod_tile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod_tile.c
3047 lines (2514 loc) · 96.6 KB
/
mod_tile.c
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2007 - 2023 by mod_tile contributors (see AUTHORS file)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; If not, see http://www.gnu.org/licenses/.
*/
#include <apr.h>
#include <apr_strings.h>
#include <apr_thread_proc.h> /* for RLIMIT stuff */
#include <apr_optional.h>
#include <apr_buckets.h>
#include <apr_lib.h>
#include <apr_poll.h>
#define APR_WANT_STRFUNC
#define APR_WANT_MEMFUNC
#include <apr_want.h>
#include <util_filter.h>
#include <ap_config.h>
#include <httpd.h>
#include <http_config.h>
#include <http_request.h>
#include <http_core.h>
#include <http_protocol.h>
#include <http_main.h>
#include <http_log.h>
#include <util_script.h>
#include <ap_mpm.h>
#include <mod_core.h>
#include <mod_cgi.h>
#include <util_md5.h>
module AP_MODULE_DECLARE_DATA tile_module;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <limits.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <inttypes.h>
#include <poll.h>
#include "gen_tile.h"
#include "protocol.h"
#include "render_config.h"
#include "store.h"
#include "mod_tile.h"
#include "sys_utils.h"
#if !defined(OS2) && !defined(WIN32) && !defined(BEOS) && !defined(NETWARE)
#include "unixd.h"
#define MOD_TILE_SET_MUTEX_PERMS /* XXX Apache should define something */
#endif
#ifdef APLOG_USE_MODULE
APLOG_USE_MODULE(tile);
#define APACHE24 1
#endif
#if (defined(__FreeBSD__) || defined(__MACH__)) && !defined(s6_addr32)
#define s6_addr32 __u6_addr.__u6_addr32
#endif
apr_shm_t *stats_shm;
apr_shm_t *delaypool_shm;
char *shmfilename;
char *shmfilename_delaypool;
apr_global_mutex_t *stats_mutex;
apr_global_mutex_t *delay_mutex;
apr_global_mutex_t *storage_mutex;
char *mutexfilename;
int layerCount = 0;
int global_max_zoom = 0;
int foreground = 0;
struct storage_backends {
struct storage_backend ** stores;
int noBackends;
};
static int error_message(request_rec *r, const char *format, ...)
__attribute__((format(printf, 2, 3)));
static int error_message(request_rec *r, const char *format, ...)
{
va_list ap;
char *msg;
va_start(ap, format);
msg = malloc(1000 * sizeof(char));
if (msg) {
vsnprintf(msg, 1000, format, ap);
//ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "%s", msg);
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "%s", msg);
r->content_type = "text/plain";
if (!r->header_only) {
ap_rputs(msg, r);
}
free(msg);
}
va_end(ap);
return OK;
}
static int socket_init(request_rec *r)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
struct sockaddr_un addr;
char portnum[16];
char ipstring[INET6_ADDRSTRLEN];
int fd, s;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
if (scfg->renderd_socket_port > 0) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Connecting to renderd on %s:%i via TCP", scfg->renderd_socket_name, scfg->renderd_socket_port);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* TCP socket */
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
sprintf(portnum, "%i", scfg->renderd_socket_port);
s = getaddrinfo(scfg->renderd_socket_name, portnum, &hints, &result);
if (s != 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "failed to resolve hostname of rendering daemon");
return FD_INVALID;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
switch (rp->ai_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)rp->ai_addr)->sin_addr), ipstring, rp->ai_addrlen);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)rp->ai_addr)->sin6_addr), ipstring, rp->ai_addrlen);
break;
default:
snprintf(ipstring, sizeof(ipstring), "address family %d", rp->ai_family);
break;
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Connecting TCP socket to rendering daemon at %s", ipstring);
fd = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (fd < 0) {
continue;
}
if (connect(fd, rp->ai_addr, rp->ai_addrlen) != 0) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "failed to connect to rendering daemon (%s), trying next ip", ipstring);
close(fd);
fd = -1;
continue;
} else {
break;
}
}
freeaddrinfo(result);
if (fd < 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "failed to create tcp socket");
return FD_INVALID;
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Connecting to renderd on Unix socket %s", scfg->renderd_socket_name);
fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (fd < 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "failed to create unix socket");
return FD_INVALID;
}
bzero(&addr, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path, scfg->renderd_socket_name, sizeof(addr.sun_path) - sizeof(char));
if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "socket connect failed for: %s with reason: %s", scfg->renderd_socket_name, strerror(errno));
close(fd);
return FD_INVALID;
}
}
return fd;
}
static int request_tile(request_rec *r, struct protocol *cmd, int renderImmediately)
{
int fd;
int ret = 0;
int retry = 1;
struct protocol resp;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
fd = socket_init(r);
if (fd == FD_INVALID) {
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r, "Failed to connect to renderer");
return 0;
}
// cmd has already been partial filled, fill in the rest
switch (renderImmediately) {
case 0: {
cmd->cmd = cmdDirty;
break;
}
case 1: {
cmd->cmd = cmdRenderLow;
break;
}
case 2: {
cmd->cmd = cmdRender;
break;
}
case 3: {
cmd->cmd = cmdRenderPrio;
break;
}
}
if (scfg->bulkMode) {
cmd->cmd = cmdRenderBulk;
}
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Requesting style(%s) z(%d) x(%d) y(%d) from renderer with priority %d", cmd->xmlname, cmd->z, cmd->x, cmd->y, cmd->cmd);
do {
switch (cmd->ver) {
case 2:
ret = send(fd, cmd, sizeof(struct protocol_v2), 0);
break;
case 3:
ret = send(fd, cmd, sizeof(struct protocol), 0);
break;
}
if ((ret == sizeof(struct protocol_v2)) || (ret == sizeof(struct protocol))) {
break;
}
if (errno != EPIPE) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "request_tile: Failed to send request to renderer: %s", strerror(errno));
close(fd);
return 0;
}
close(fd);
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "request_tile: Reconnecting to rendering socket after failed request due to sigpipe");
fd = socket_init(r);
if (fd == FD_INVALID) {
return 0;
}
} while (retry--);
if (renderImmediately) {
int timeout = (renderImmediately > 2 ? scfg->request_timeout_priority : scfg->request_timeout);
struct pollfd rx;
int s;
while (1) {
rx.fd = fd;
rx.events = POLLIN;
s = poll(&rx, 1, timeout * 1000);
if (s > 0) {
bzero(&resp, sizeof(struct protocol));
ret = recv(fd, &resp, sizeof(struct protocol_v2), 0);
if (ret != sizeof(struct protocol_v2)) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "request_tile: Failed to read response from rendering socket. Got %d bytes but expected %d. Errno %d (%s)",
ret, (int) sizeof(struct protocol_v2), errno, strerror(errno));
break;
}
if (resp.ver == 3) {
ret += recv(fd, ((void*)&resp) + sizeof(struct protocol_v2), sizeof(struct protocol) - sizeof(struct protocol_v2), 0);
}
if (cmd->x == resp.x && cmd->y == resp.y && cmd->z == resp.z && !strcmp(cmd->xmlname, resp.xmlname)) {
close(fd);
if (resp.cmd == cmdDone) {
return 1;
} else {
return 0;
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
"Response does not match request: xml(%s,%s) z(%d,%d) x(%d,%d) y(%d,%d)", cmd->xmlname,
resp.xmlname, cmd->z, resp.z, cmd->x, resp.x, cmd->y, resp.y);
}
} else if (s == 0) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"request_tile: Request xml(%s) z(%d) x(%d) y(%d) could not be rendered in %i seconds",
cmd->xmlname, cmd->z, cmd->x, cmd->y,
timeout);
break;
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
"request_tile: Request xml(%s) z(%d) x(%d) y(%d) timeout %i seconds failed with reason: %s",
cmd->xmlname, cmd->z, cmd->x, cmd->y,
timeout, strerror(errno));
break;
}
}
}
close(fd);
return 0;
}
static apr_status_t cleanup_storage_backend(void * data)
{
struct storage_backends * stores = (struct storage_backends *)data;
int i;
for (i = 0; i < stores->noBackends; i++) {
if (stores->stores[i]) {
stores->stores[i]->close_storage(stores->stores[i]);
}
}
return APR_SUCCESS;
}
static struct storage_backend * get_storage_backend(request_rec *r, int tile_layer)
{
struct storage_backends * stores = NULL;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
tile_config_rec *tile_configs = (tile_config_rec *) scfg->configs->elts;
tile_config_rec *tile_config = &tile_configs[tile_layer];
#ifdef APACHE24
apr_thread_t * current_thread = r->connection->current_thread;
apr_pool_t *lifecycle_pool = apr_thread_pool_get(current_thread);
#else
apr_pool_t *lifecycle_pool = r->server->process->pool;
#endif
char * memkey = apr_psprintf(r->pool, "mod_tile_storage_backends");
apr_os_thread_t os_thread = apr_os_thread_current();
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "get_storage_backend: Retrieving storage back end for tile layer %i in pool %pp and thread %li",
tile_layer, lifecycle_pool, os_thread);
/* In Apache 2.2, we are using the process memory pool, but with mpm_event and mpm_worker, each process has multiple threads.
* As apache's memory pool operations are not thread-safe, we need to wrap everything into a mutex to protect against
* segfaults. Apache 2.4 provides access to the per thread pool, in which case access to a specific pool is always single threaded.*/
#ifndef APACHE24
apr_global_mutex_lock(storage_mutex);
#endif
if (apr_pool_userdata_get((void **)&stores, memkey, lifecycle_pool) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "get_storage_backend: Failed horribly!");
}
if (stores == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "get_storage_backend: No storage backends for this lifecycle %pp, creating it in thread %li", lifecycle_pool, os_thread);
stores = apr_pcalloc(lifecycle_pool, sizeof(struct storage_backends));
stores->stores = apr_pcalloc(lifecycle_pool, sizeof(struct storage_backend *) * scfg->configs->nelts);
stores->noBackends = scfg->configs->nelts;
if (apr_pool_userdata_set(stores, memkey, &cleanup_storage_backend, lifecycle_pool) != APR_SUCCESS) {
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "get_storage_backend: Failed horribly to set user_data!");
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "get_storage_backend: Found backends (%pp) for this lifecycle %pp in thread %li", stores, lifecycle_pool, os_thread);
}
#ifndef APACHE24
apr_global_mutex_unlock(storage_mutex);
#endif
if (stores->stores[tile_layer] == NULL) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "get_storage_backend: No storage backend in current lifecycle %pp in thread %li for current tile layer %i",
lifecycle_pool, os_thread, tile_layer);
stores->stores[tile_layer] = init_storage_backend(tile_config->store);
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "get_storage_backend: Storage backend found in current lifecycle %pp for current tile layer %i in thread %li",
lifecycle_pool, tile_layer, os_thread);
}
return stores->stores[tile_layer];
}
static enum tileState tile_state(request_rec *r, struct protocol *cmd)
{
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
struct stat_info stat;
struct tile_request_data * rdata = (struct tile_request_data *)ap_get_module_config(r->request_config, &tile_module);
stat = rdata->store->tile_stat(rdata->store, cmd->xmlname, cmd->options, cmd->x, cmd->y, cmd->z);
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "tile_state: determined state of %s %i %i %i on store %pp: Tile size: %li, expired: %i created: %li",
cmd->xmlname, cmd->x, cmd->y, cmd->z, rdata->store, stat.size, stat.expired, stat.mtime);
r->finfo.mtime = stat.mtime * 1000000;
r->finfo.atime = stat.atime * 1000000;
r->finfo.ctime = stat.ctime * 1000000;
if (stat.size < 0) {
return tileMissing;
}
if (stat.expired) {
if ((r->request_time - r->finfo.mtime) < scfg->veryold_threshold) {
return tileOld;
} else {
return tileVeryOld;
}
}
return tileCurrent;
}
/**
* Add CORS ( Cross-origin resource sharing ) headers. http://www.w3.org/TR/cors/
* CORS allows requests that would otherwise be forbidden under the same origin policy.
*/
static int add_cors(request_rec *r, const char * cors)
{
const char* headers;
const char* origin = apr_table_get(r->headers_in, "Origin");
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking if CORS headers need to be added: Origin: %s Policy: %s", origin, cors);
if (!origin) {
return DONE;
} else {
if ((strcmp(cors, "*") == 0) || strstr(cors, origin)) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Origin header is allowed under the CORS policy. Adding Access-Control-Allow-Origin");
if (strcmp(cors, "*") == 0) {
apr_table_setn(r->headers_out, "Access-Control-Allow-Origin",
apr_psprintf(r->pool, "%s", cors));
} else {
apr_table_setn(r->headers_out, "Access-Control-Allow-Origin",
apr_psprintf(r->pool, "%s", origin));
apr_table_setn(r->headers_out, "Vary",
apr_psprintf(r->pool, "%s", "Origin"));
}
if (strcmp(r->method, "OPTIONS") == 0 &&
apr_table_get(r->headers_in, "Access-Control-Request-Method")) {
headers = apr_table_get(r->headers_in, "Access-Control-Request-Headers");
if (headers) {
apr_table_setn(r->headers_out, "Access-Control-Allow-Headers",
apr_psprintf(r->pool, "%s", headers));
}
apr_table_setn(r->headers_out, "Access-Control-Max-Age",
apr_psprintf(r->pool, "%i", 604800));
return OK;
} else {
return DONE;
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Origin header (%s)is NOT allowed under the CORS policy(%s). Rejecting request", origin, cors);
return HTTP_FORBIDDEN;
}
}
}
static void add_expiry(request_rec *r, struct protocol * cmd)
{
apr_time_t holdoff;
apr_table_t *t = r->headers_out;
enum tileState state = tile_state(r, cmd);
apr_finfo_t *finfo = &r->finfo;
char *timestr;
long int maxAge, minCache, lastModified;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
struct tile_request_data * rdata = (struct tile_request_data *)ap_get_module_config(r->request_config, &tile_module);
tile_config_rec *tile_configs = (tile_config_rec *) scfg->configs->elts;
tile_config_rec *tile_config = &tile_configs[rdata->layerNumber];
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "expires(%s), uri(%s),, path_info(%s)\n",
r->handler, r->uri, r->path_info);
/* If the hostname matches the "extended caching hostname" then set the cache age accordingly */
if ((scfg->cache_extended_hostname[0] != 0) && (strstr(r->hostname,
scfg->cache_extended_hostname) != NULL)) {
maxAge = scfg->cache_extended_duration;
} else {
/* Test if the tile we are serving is out of date, then set a low maxAge*/
if (state == tileOld) {
holdoff = (scfg->cache_duration_dirty / 2) * (rand() / (RAND_MAX
+ 1.0));
maxAge = scfg->cache_duration_dirty + holdoff;
} else {
// cache heuristic based on zoom level
if (cmd->z > tile_config->maxzoom) {
minCache = 0;
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r,
"z (%i) is larger than MAXZOOM %i\n", cmd->z, tile_config->maxzoom);
} else {
minCache = scfg->mincachetime[cmd->z];
}
// Time to the next known complete rerender
//planetTimestamp = apr_time_sec(getPlanetTime(r)
// + apr_time_from_sec(PLANET_INTERVAL) - r->request_time);
// Time since the last render of this tile
lastModified = (int)(((double) apr_time_sec(r->request_time
- finfo->mtime))
* scfg->cache_duration_last_modified_factor);
// Add a random jitter of 3 hours to space out cache expiry
holdoff = (3 * 60 * 60) * (rand() / (RAND_MAX + 1.0));
//maxAge = MAX(minCache, planetTimestamp);
maxAge = minCache;
maxAge = MAX(maxAge, lastModified);
maxAge += holdoff;
ap_log_rerror(
APLOG_MARK,
APLOG_DEBUG,
0,
r,
"caching heuristics: zoom level based %ld; last modified %ld\n",
minCache, lastModified);
}
maxAge = MIN(maxAge, scfg->cache_duration_max);
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Setting tiles maxAge to %ld\n", maxAge);
apr_table_mergen(t, "Cache-Control",
apr_psprintf(r->pool, "max-age=%" APR_TIME_T_FMT,
maxAge));
timestr = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
apr_rfc822_date(timestr, (apr_time_from_sec(maxAge) + r->request_time));
apr_table_setn(t, "Expires", timestr);
}
static int get_global_lock(request_rec *r, apr_global_mutex_t * mutex)
{
apr_status_t rs;
int camped;
for (camped = 0; camped < MAXCAMP; camped++) {
rs = apr_global_mutex_trylock(mutex);
if (APR_STATUS_IS_EBUSY(rs)) {
apr_sleep(CAMPOUT);
} else if (rs == APR_SUCCESS) {
return 1;
} else if (APR_STATUS_IS_ENOTIMPL(rs)) {
/* If it's not implemented, just hang in the mutex. */
rs = apr_global_mutex_lock(mutex);
if (rs == APR_SUCCESS) {
return 1;
} else {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Could not get hardlock");
return 0;
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r, "Unknown return status from trylock");
return 0;
}
}
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Timedout trylock");
return 0;
}
static int incRespCounter(int resp, request_rec *r, struct protocol * cmd, int layerNumber)
{
stats_data *stats;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
if (!scfg->enableGlobalStats) {
/* If tile stats reporting is not enable
* pretend we correctly updated the counter to
* not fill the logs with warnings about failed
* stats
*/
return 1;
}
if (get_global_lock(r, stats_mutex) != 0) {
stats = (stats_data *)apr_shm_baseaddr_get(stats_shm);
switch (resp) {
case OK: {
stats->noResp200++;
if (cmd != NULL) {
stats->noRespZoom[cmd->z]++;
stats->noResp200Layer[layerNumber]++;
}
break;
}
case HTTP_NOT_MODIFIED: {
stats->noResp304++;
if (cmd != NULL) {
stats->noRespZoom[cmd->z]++;
stats->noResp200Layer[layerNumber]++;
}
break;
}
case HTTP_NOT_FOUND: {
stats->noResp404++;
stats->noResp404Layer[layerNumber]++;
break;
}
case HTTP_SERVICE_UNAVAILABLE: {
stats->noResp503++;
break;
}
case HTTP_INTERNAL_SERVER_ERROR: {
stats->noResp5XX++;
break;
}
default: {
stats->noRespOther++;
}
}
apr_global_mutex_unlock(stats_mutex);
/* Swallowing the result because what are we going to do with it at
* this stage?
*/
return 1;
} else {
return 0;
}
}
static int incFreshCounter(int status, request_rec *r)
{
stats_data *stats;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
if (!scfg->enableGlobalStats) {
/* If tile stats reporting is not enable
* pretend we correctly updated the counter to
* not fill the logs with warnings about failed
* stats
*/
return 1;
}
if (get_global_lock(r, stats_mutex) != 0) {
stats = (stats_data *)apr_shm_baseaddr_get(stats_shm);
switch (status) {
case FRESH: {
stats->noFreshCache++;
break;
}
case FRESH_RENDER: {
stats->noFreshRender++;
break;
}
case OLD: {
stats->noOldCache++;
break;
}
case VERYOLD: {
stats->noVeryOldCache++;
break;
}
case OLD_RENDER: {
stats->noOldRender++;
break;
}
case VERYOLD_RENDER: {
stats->noVeryOldRender++;
break;
}
}
apr_global_mutex_unlock(stats_mutex);
/* Swallowing the result because what are we going to do with it at
* this stage?
*/
return 1;
} else {
return 0;
}
}
static int incTimingCounter(apr_uint64_t duration, int z, request_rec *r)
{
stats_data *stats;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
if (!scfg->enableGlobalStats) {
/* If tile stats reporting is not enable
* pretend we correctly updated the counter to
* not fill the logs with warnings about failed
* stats
*/
return 1;
}
if (get_global_lock(r, stats_mutex) != 0) {
stats = (stats_data *)apr_shm_baseaddr_get(stats_shm);
stats->totalBufferRetrievalTime += duration;
stats->zoomBufferRetrievalTime[z] += duration;
stats->noTotalBufferRetrieval++;
stats->noZoomBufferRetrieval[z]++;
apr_global_mutex_unlock(stats_mutex);
/* Swallowing the result because what are we going to do with it at
* this stage?
*/
return 1;
} else {
return 0;
}
}
static int delay_allowed(request_rec *r, enum tileState state)
{
delaypool * delayp;
int delay = 0;
int i, j;
char ** strtok_state;
char * tmp;
const char * ip_addr = NULL;
apr_time_t now;
int tiles_topup;
int render_topup;
uint32_t hashkey;
struct in_addr sin_addr;
struct in6_addr ip;
ap_conf_vector_t *sconf = r->server->module_config;
tile_server_conf *scfg = ap_get_module_config(sconf, &tile_module);
delayp = (delaypool *)apr_shm_baseaddr_get(delaypool_shm);
#ifdef APACHE24
ip_addr = r->useragent_ip;
#else
ip_addr = r->connection->remote_ip;
#endif
if (scfg->enableTileThrottlingXForward) {
char * ip_addrs = apr_pstrdup(r->pool, apr_table_get(r->headers_in, "X-Forwarded-For"));
if (ip_addrs) {
#ifdef APACHE24
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking throttling delays: Found X-Forward-For header \"%s\", forwarded by %s", ip_addrs, r->connection->client_ip);
#else
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking throttling delays: Found X-Forward-For header \"%s\", forwarded by %s", ip_addrs, r->connection->remote_ip);
#endif
//X-Forwarded-For can be a chain of proxies deliminated by , The first entry in the list is the client, the last entry is the remote address seen by the proxy
//closest to the tileserver.
strtok_state = NULL;
tmp = apr_strtok(ip_addrs, ", ", strtok_state);
ip_addr = tmp;
//Use the last entry in the chain of X-Forwarded-For instead of the client, i.e. the entry added by the proxy closest to the tileserver
//If this is a reverse proxy under our control, its X-Forwarded-For can be trusted.
if (scfg->enableTileThrottlingXForward == 2) {
while ((tmp = apr_strtok(NULL, ", ", strtok_state)) != NULL) {
ip_addr = tmp;
}
}
#ifdef APACHE24
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking throttling delays for IP %s, forwarded by %s", ip_addr, r->connection->client_ip);
#else
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking throttling delays for IP %s, forwarded by %s", ip_addr, r->connection->remote_ip);
#endif
}
}
if (inet_pton(AF_INET, ip_addr, &sin_addr) > 0) {
//ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking delays: for IP %s appears to be an IPv4 address", ip_addr);
memset(ip.s6_addr, 0, 16);
memcpy(&(ip.s6_addr[12]), &(sin_addr.s_addr), 4);
hashkey = sin_addr.s_addr % DELAY_HASHTABLE_WHITELIST_SIZE;
if (delayp->whitelist[hashkey] == sin_addr.s_addr) {
return 1;
}
} else {
if (inet_pton(AF_INET6, ip_addr, &ip) <= 0) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Checking delays: for IP %s. Don't know what it is", ip_addr);
return 0;
}
}
hashkey = (ip.s6_addr32[0] ^ ip.s6_addr32[1] ^ ip.s6_addr32[2] ^ ip.s6_addr32[3]) % DELAY_HASHTABLE_SIZE;
/* If a delaypool fillup is ongoing, just skip accounting to not block on a lock */
if (delayp->locked) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "skipping delay pool accounting, during fillup procedure\n");
return 1;
}
if (get_global_lock(r, delay_mutex) == 0) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Could not acquire lock, skipping delay pool accounting\n");
return 1;
};
if (memcmp(&(delayp->users[hashkey].ip_addr), &ip, sizeof(struct in6_addr)) == 0) {
/* Repeat the process to determine if we have tockens in the bucket, as the fillup only runs once a client hits an empty bucket,
so in the mean time, the bucket might have been filled */
for (j = 0; j < 3; j++) {
//ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Checking delays: Current poolsize: %i tiles and %i renders\n", delayp->users[hashkey].available_tiles, delayp->users[hashkey].available_render_req);
delay = 0;
if (delayp->users[hashkey].available_tiles > 0) {
delayp->users[hashkey].available_tiles--;
} else {
delay = 1;
}
if (state == tileMissing) {
if (delayp->users[hashkey].available_render_req > 0) {
delayp->users[hashkey].available_render_req--;
} else {
delay = 2;
}
}
if (delay > 0) {
/* If we are on the second round, we really hit an empty delaypool, timeout for a while to slow down clients */
if (j > 0) {
apr_global_mutex_unlock(delay_mutex);
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Delaypool: Client %s has hit its limits, throttling (%i)\n", ip_addr, delay);
sleep(CLIENT_PENALTY);
if (get_global_lock(r, delay_mutex) == 0) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Could not acquire lock, but had to delay\n");
return 0;
};
}
/* We hit an empty bucket, so run the bucket fillup procedure to check if new tokens should have arrived in the mean time. */
now = apr_time_now();
tiles_topup = (now - delayp->last_tile_fillup) / scfg->delaypoolTileRate;
render_topup = (now - delayp->last_render_fillup) / scfg->delaypoolRenderRate;
//ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Filling up pools with %i tiles and %i renders\n", tiles_topup, render_topup);
if ((tiles_topup > 0) || (render_topup > 0)) {
delayp->locked = 1;
for (i = 0; i < DELAY_HASHTABLE_SIZE; i++) {
delayp->users[i].available_tiles += tiles_topup;
delayp->users[i].available_render_req += render_topup;
if (delayp->users[i].available_tiles > scfg->delaypoolTileSize) {
delayp->users[i].available_tiles = scfg->delaypoolTileSize;
}
if (delayp->users[i].available_render_req > scfg->delaypoolRenderSize) {
delayp->users[i].available_render_req = scfg->delaypoolRenderSize;
}
}
delayp->locked = 0;
}
delayp->last_tile_fillup += scfg->delaypoolTileRate * tiles_topup;
delayp->last_render_fillup += scfg->delaypoolRenderRate * render_topup;
} else {
break;
}
}
} else {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, "Creating a new delaypool for ip %s\n", ip_addr);
memcpy(&(delayp->users[hashkey].ip_addr), &ip, sizeof(struct in6_addr));
delayp->users[hashkey].available_tiles = scfg->delaypoolTileSize;
delayp->users[hashkey].available_render_req = scfg->delaypoolRenderSize;
delay = 0;
}
apr_global_mutex_unlock(delay_mutex);
if (delay > 0) {
ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, "Delaypool: Client %s has hit its limits, rejecting (%i)\n", ip_addr, delay);
return 0;
} else {
return 1;
}
}
static int tile_handler_dirty(request_rec *r)
{
ap_conf_vector_t *sconf;
tile_server_conf *scfg;
struct tile_request_data * rdata;
struct protocol * cmd;
if (strcmp(r->handler, "tile_dirty")) {
return DECLINED;
}
rdata = (struct tile_request_data *)ap_get_module_config(r->request_config, &tile_module);
cmd = rdata->cmd;
if (cmd == NULL) {
return DECLINED;
}
sconf = r->server->module_config;
scfg = ap_get_module_config(sconf, &tile_module);
// Is /dirty URL enabled?
if (!scfg->enableDirtyUrl) {
ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "tile_handler_dirty: /dirty URL is not enabled");
return HTTP_NOT_FOUND;
}
if (scfg->bulkMode) {
return OK;
}