]> git.r.bdr.sh - rbdr/ngx_http_office_hours_filter_module/blame - ngx_http_office_hours_filter_module.c
Add support for office_hours_additional_information
[rbdr/ngx_http_office_hours_filter_module] / ngx_http_office_hours_filter_module.c
CommitLineData
e4db4a20
BB
1/*
2 * Copyright 2018 Rubén Beltrán del Río
af4b488f 3 *
e4db4a20
BB
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
5 * License. You may obtain a copy of the License at
af4b488f 6 *
e4db4a20 7 * http://www.apache.org/licenses/LICENSE-2.0
af4b488f 8 *
e4db4a20
BB
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
10 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11 * specific language governing permissions and limitations under the License.
12 */
13
e4db4a20
BB
14#include <ngx_config.h>
15#include <ngx_core.h>
16#include <ngx_http.h>
17
fa2b280d
BB
18/*
19 * Declarations
20 */
21
fbdf81df
BB
22/* Constants */
23
24const ngx_uint_t WEEK_LENGTH = 7;
25const char * CLOSED_TOKEN = "closed";
80c4c3cc 26const ngx_str_t TIME_REGEX = ngx_string("([0-9]{1,2})(?:\\:([0-9]{2}))?\\-([0-9]{1,2})(?:\\:([0-9]{2}))?");
8b830d84
RBR
27const ngx_str_t HEAD_HTML = ngx_string("<!doctype html><html><head><title>This website is currently closed!</title></head><body><h1>This website is currently closed!</h1><p>This website has closed for the day, please check our office hours below:</p><ul>");
28const ngx_str_t OPEN_SERVER_TIME_HTML = ngx_string("</ul><p><em>Current Server Time is: ");
29const ngx_str_t CLOSE_SERVER_TIME_HTML = ngx_string("</em></p>");
30const ngx_str_t FOOT_HTML = ngx_string("</body></html>");
61fca89b
BB
31const char * DAY_NAMES[7] = {
32 "Monday",
33 "Tuesday",
34 "Wednesday",
35 "Thursday",
36 "Friday",
37 "Saturday",
38 "Sunday"
39};
fbdf81df 40
fa2b280d 41/* Main Configuration Structure */
e4db4a20
BB
42
43typedef struct {
af4b488f 44 ngx_array_t *office_hours;
8b830d84 45 ngx_str_t additional_information;
af4b488f 46} ngx_http_office_hours_conf_t;
e4db4a20 47
fa2b280d
BB
48/* Lifecycle Functions For Module Context */
49
af4b488f 50static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf);
fa2b280d 51static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
f34685bb 52 void *parent, void *child);
e4db4a20
BB
53static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf);
54
fa2b280d
BB
55/* Configuration Handler */
56
57static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
58 void *conf);
59
67206816 60/* Filter Storage */
fa2b280d 61
67206816 62static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
fa2b280d
BB
63static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
64
fbdf81df
BB
65/* Utility Functions */
66static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours);
67static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours);
68static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours);
69static ngx_uint_t get_day_of_week(time_t time);
70static ngx_uint_t get_seconds_of_day(time_t time);
bbe15175 71static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end);
61fca89b
BB
72static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf);
73static char * format_hours(ngx_uint_t * seconds, char * day);
74static char * format_seconds(ngx_uint_t seconds);
75static char * left_pad(unsigned int number);
fbdf81df 76
61fca89b 77/* Globals */
80c4c3cc 78ngx_regex_compile_t rc;
61fca89b 79ngx_str_t OUTPUT_HTML;
80c4c3cc 80
fa2b280d
BB
81/*
82 * Module Definitions
83 */
e4db4a20 84
fa2b280d 85/* Module Directives */
e4db4a20
BB
86
87static ngx_command_t ngx_http_office_hours_commands[] = {
88 {
fa2b280d 89 ngx_string("office_hours"),
fbdf81df 90 NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1 | NGX_CONF_TAKE2 | NGX_CONF_TAKE3 | NGX_CONF_TAKE4 | NGX_CONF_TAKE5 | NGX_CONF_TAKE6 | NGX_CONF_TAKE7,
fa2b280d
BB
91 ngx_http_office_hours,
92 NGX_HTTP_LOC_CONF_OFFSET,
93 offsetof(ngx_http_office_hours_conf_t, office_hours),
94 NULL
e4db4a20 95 },
8b830d84
RBR
96 {
97 ngx_string("office_hours_additional_information"),
98 NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1 | NGX_CONF_TAKE2 | NGX_CONF_TAKE3 | NGX_CONF_TAKE4 | NGX_CONF_TAKE5 | NGX_CONF_TAKE6 | NGX_CONF_TAKE7,
99 ngx_conf_set_str_slot,
100 NGX_HTTP_LOC_CONF_OFFSET,
101 offsetof(ngx_http_office_hours_conf_t, additional_information),
102 NULL
103 },
e4db4a20
BB
104
105 ngx_null_command
106};
107
fa2b280d 108/* Module Context */
e4db4a20
BB
109
110static ngx_http_module_t ngx_http_office_hours_filter_module_ctx = {
fa2b280d
BB
111 NULL, /* Preconfiguration */
112 ngx_http_office_hours_init, /* Postconfiguration */
e4db4a20 113
fa2b280d
BB
114 NULL, /* Create main configuration */
115 NULL, /* Initialize main configuration */
e4db4a20 116
fa2b280d
BB
117 NULL, /* Create server configuration */
118 NULL, /* Merge server configuration */
119
120 ngx_http_office_hours_create_conf, /* Create location configuration */
121 ngx_http_office_hours_merge_conf /* Merge location configuration */
e4db4a20
BB
122};
123
fa2b280d 124/* Module Definition */
e4db4a20
BB
125
126ngx_module_t ngx_http_office_hours_filter_module = {
fa2b280d
BB
127 NGX_MODULE_V1, //Module Version
128 &ngx_http_office_hours_filter_module_ctx, //Module context
129 ngx_http_office_hours_commands, //Module commands
130 NGX_HTTP_MODULE, //Module Type
131 NULL, //Initialize Master
132 NULL, //Initialize Module
133 NULL, //Initialize Process
134 NULL, //Initialize Thread
135 NULL, //Exit Thread
136 NULL, //Exit Process
137 NULL, //Exit Master
138 NGX_MODULE_V1_PADDING
e4db4a20
BB
139};
140
67206816
BB
141/*
142 * Main Header Filter
143 * If the current time is within office hours, it goes to the next
144 * handler. Otherwise it sets the headers to 403
145 */
146
147static ngx_int_t
148ngx_http_office_hours_header_filter(ngx_http_request_t * r)
149{
150
151 ngx_uint_t ** parsed_office_hours;
152 ngx_http_office_hours_conf_t *conf;
153
154 conf =
155 ngx_http_get_module_loc_conf(r,
156 ngx_http_office_hours_filter_module);
157
67206816
BB
158 if (conf->office_hours == NULL) {
159 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
160 "Office hours disabled");
161 return ngx_http_next_header_filter(r);
162 }
163
164 parsed_office_hours = parse_office_hours(conf->office_hours);
165
166 if (within_office_hours(parsed_office_hours)) {
167 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
168 "Within office hours");
169 return ngx_http_next_header_filter(r);
170 }
171
172 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
173 "Outside office hours");
174
61fca89b
BB
175 if (OUTPUT_HTML.data == NULL) {
176 OUTPUT_HTML = create_output_html(conf);
177 }
178
67206816
BB
179 r->headers_out.status = NGX_HTTP_FORBIDDEN;
180 r->headers_out.content_length_n = OUTPUT_HTML.len;
181
182 return ngx_http_next_header_filter(r);
183}
184
fa2b280d
BB
185/*
186 * Main Body Filter
187 * If the current time is within office hours, it goes to the next
67206816 188 * handler. Otherwise it replaces the body with the office hours.
fa2b280d 189 */
e4db4a20 190
af4b488f 191static ngx_int_t
67206816 192ngx_http_office_hours_body_filter(ngx_http_request_t * r, ngx_chain_t *in)
af4b488f 193{
e4db4a20 194
67206816 195 ngx_buf_t *b;
fbdf81df 196 ngx_uint_t ** parsed_office_hours;
67206816 197 ngx_chain_t out;
af4b488f 198 ngx_http_office_hours_conf_t *conf;
e4db4a20 199
fa2b280d
BB
200 conf =
201 ngx_http_get_module_loc_conf(r,
202 ngx_http_office_hours_filter_module);
e4db4a20
BB
203
204 if (conf->office_hours == NULL) {
fa2b280d 205 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
fbdf81df 206 "Office hours disabled");
fa2b280d 207 return ngx_http_next_body_filter(r, in);
e4db4a20 208 }
fa2b280d 209
fbdf81df 210 parsed_office_hours = parse_office_hours(conf->office_hours);
e4db4a20 211
fbdf81df 212 if (within_office_hours(parsed_office_hours)) {
fa2b280d 213 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
fbdf81df
BB
214 "Within office hours");
215 return ngx_http_next_body_filter(r, in);
e4db4a20
BB
216 }
217
fbdf81df
BB
218 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
219 "Outside office hours");
220
61fca89b
BB
221 if (OUTPUT_HTML.data == NULL) {
222 OUTPUT_HTML = create_output_html(conf);
223 }
224
67206816
BB
225 b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
226 if (b == NULL) {
227 ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer.");
228 return NGX_HTTP_INTERNAL_SERVER_ERROR;
229 }
230
231 out.buf = b;
232 out.next = NULL;
233
234 b->start = OUTPUT_HTML.data;
235 b->pos = b->start;
236 b->end = OUTPUT_HTML.data + OUTPUT_HTML.len;
237 b->last = b->end;
238
239 b->memory = 1;
240 b->last_buf = 1;
241
242 return ngx_http_next_body_filter(r, &out);
e4db4a20
BB
243}
244
fa2b280d
BB
245/*
246 * Callback for `office_hours ` directive
247 * Reads the configuration loaded from the config file(cf)
248 * And writes it to the right place in the module configuration(conf)
249 */
e4db4a20 250
fa2b280d
BB
251static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
252 void *conf)
af4b488f 253{
e4db4a20 254
af4b488f 255 char *conf_structure = conf;
e4db4a20 256
fbdf81df 257 ngx_str_t *hours, *value;
af4b488f 258 ngx_array_t **office_hours;
af4b488f 259 ngx_uint_t i;
e4db4a20 260
fa2b280d
BB
261 /* Gets the array from the config structure using the defined
262 * offset, and if the pointer is unset it creates a new one.
263 * (The first element is the directive itself, so we should be
264 * offset by 1)
265 */
266 office_hours = (ngx_array_t **) (conf_structure + cmd->offset);
e4db4a20
BB
267
268 if (*office_hours == NGX_CONF_UNSET_PTR) {
fa2b280d
BB
269 *office_hours = ngx_array_create(cf->pool, cf->args->nelts - 1,
270 sizeof(ngx_str_t));
e4db4a20 271
fa2b280d
BB
272 if (*office_hours == NULL) {
273 return NGX_CONF_ERROR;
274 }
e4db4a20 275 }
e4db4a20
BB
276 value = cf->args->elts;
277
278 for (i = 1; i < cf->args->nelts; ++i) {
fa2b280d
BB
279 hours = ngx_array_push(*office_hours);
280 if (hours == NULL) {
281 return NGX_CONF_ERROR;
282 }
283 *hours = value[i];
e4db4a20
BB
284 }
285
286 return NGX_CONF_OK;
287}
288
fa2b280d
BB
289/*
290 * Config Creator
291 * Initializes the configuration structure
292 */
e4db4a20 293
fa2b280d 294static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf)
af4b488f 295{
e4db4a20 296
af4b488f 297 ngx_http_office_hours_conf_t *conf;
e4db4a20
BB
298
299 conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_office_hours_conf_t));
300
301 if (conf == NULL) {
fa2b280d 302 return NULL;
e4db4a20 303 }
e4db4a20
BB
304 conf->office_hours = NGX_CONF_UNSET_PTR;
305
306 return conf;
307}
308
fa2b280d
BB
309/*
310 * Merge Config Values
311 * Sets the defaults for the configuration and merges
312 * with other configurations
313 */
e4db4a20 314
fa2b280d 315static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
f34685bb 316 void *parent, void *child)
af4b488f 317{
e4db4a20 318
af4b488f
BB
319 ngx_http_office_hours_conf_t *prev = parent;
320 ngx_http_office_hours_conf_t *conf = child;
e4db4a20
BB
321
322 ngx_conf_merge_ptr_value(conf->office_hours, prev->office_hours, NULL);
323
324 return NGX_CONF_OK;
325}
326
fbdf81df
BB
327/*
328 * Parse the office hour strings in the configuration file
329 * to fill out the hours array (in seconds)
330 */
331
332static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours)
333{
334
335 ngx_str_t *hours;
336 ngx_uint_t ** parsed_office_hours;
337 ngx_uint_t i, j;
338
339 parsed_office_hours = malloc(7 * sizeof(ngx_uint_t *));
340
341 hours = office_hours->elts;
342
343 /*
344 * On the configuration file, the leftmost element
345 * always applies to all remaining days, all others
346 * are read from right to left. So first we will apply
347 * the initial override, and then iterate based on the
348 * number of overrides
349 */
350
351 for (i = 0; i < WEEK_LENGTH + 1 - office_hours->nelts; ++i) {
352 parsed_office_hours[i] = parse_office_hours_string(hours[0]);
353 }
354
355 for (i = 1; i < office_hours->nelts; ++i) {
356 j = WEEK_LENGTH - office_hours->nelts + i;
357 parsed_office_hours[j] = parse_office_hours_string(hours[i]);
358 }
359
360 return parsed_office_hours;
361}
362
363/*
364 * Given a time string or the closed token, return a tuple
365 * of numbers representing opening and closing hours
366 */
367
368static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours)
369{
370
80c4c3cc
BB
371 int captures[(1 + 4) * 3];
372 ngx_int_t n;
fbdf81df
BB
373 ngx_uint_t * parsed_hours;
374
375 parsed_hours = malloc(2 * sizeof(ngx_uint_t));
376
377 if(ngx_strcmp(office_hours.data, CLOSED_TOKEN) == 0) {
378 parsed_hours[0] = 0;
379 parsed_hours[1] = 0;
380 return parsed_hours;
381 }
382
80c4c3cc
BB
383 n = ngx_regex_exec(rc.regex, &office_hours, captures, (1 + 4) * 3);
384
385 if (n >= 0) {
386 /* Opening Hours */
387
bbe15175
BB
388 parsed_hours[0] = 60 * 60 * parse_number(office_hours, captures[2], captures[3]);
389 parsed_hours[0] = parsed_hours[0] + 60 * parse_number(office_hours, captures[4], captures[5]);
80c4c3cc 390
bbe15175
BB
391 parsed_hours[1] = 60 * 60 * parse_number(office_hours, captures[6], captures[7]);
392 parsed_hours[1] = parsed_hours[1] + 60 * parse_number(office_hours, captures[8], captures[9]);
80c4c3cc
BB
393
394 return parsed_hours;
395 }
396
397 /* Non-matching strings count as open */
398
fbdf81df
BB
399 parsed_hours[0] = 0;
400 parsed_hours[1] = 86400;
401 return parsed_hours;
402}
403
404/*
405 * Given an office hours array, it returns whether or not
406 * it is currently within office hours.
407 */
408
409static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours)
410{
411
412 time_t now;
413 ngx_uint_t day_of_week, seconds_of_day;
414 ngx_uint_t * current_hours;
415
416 ngx_time_update();
417 now = ngx_time();
418 day_of_week = get_day_of_week(now);
419 seconds_of_day = get_seconds_of_day(now);
420 current_hours = office_hours[day_of_week];
421
422 return seconds_of_day >= current_hours[0] && seconds_of_day <= current_hours[1];
423}
424
425/*
426 * Calculate the day of the week given a timestamp
427 */
61fca89b 428
fbdf81df
BB
429static ngx_uint_t get_day_of_week(time_t time)
430{
431
432 /* Epoch was thursday, so add 3 so we start on monday */
433 return (time / 86400 + 3) % 7;
434}
435
436/*
437 * Calculate the number of seconds elapsed today
438 */
61fca89b 439
fbdf81df
BB
440static ngx_uint_t get_seconds_of_day(time_t time)
441{
442
443 return time - (time / 86400) * 86400;
444}
bbe15175
BB
445
446/*
447 * Parses a string, returns 0 if match was not found
448 */
61fca89b 449
bbe15175
BB
450static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end)
451{
452
453 if (end - start == 0) {
454 return 0;
455 }
456
457 return ngx_atoi(&string.data[start], end - start);
458}
459
61fca89b
BB
460/*
461 * Given the current office hours configuration it creates the custom
462 * HTML
463 */
464
465static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf)
466{
467
468 char * output_buffer;
469 time_t now;
470 ngx_str_t output_html;
471 ngx_uint_t i, seconds_of_day;
472 ngx_uint_t ** parsed_office_hours;
473
8b830d84
RBR
474 size_t base_size = 1024;
475 size_t additional_info_size = conf->additional_information.len;
476 size_t buffer_size = base_size + additional_info_size + 1;
477 output_buffer = malloc(buffer_size * sizeof(char));
478
479 /* UH-OH we couldn't allocate the bufer */
480 if (!output_buffer) {
481 output_html.data = NULL;
482 output_html.len = 0;
483 return output_html;
484 }
485
61fca89b
BB
486 parsed_office_hours = parse_office_hours(conf->office_hours);
487 now = ngx_time();
488 seconds_of_day = get_seconds_of_day(now);
489
8b830d84
RBR
490 int written = 0;
491
492 written += snprintf(output_buffer + written, buffer_size - written, "%s", (char *) HEAD_HTML.data);
61fca89b
BB
493
494 for (i = 0; i < 7; ++i) {
8b830d84
RBR
495 written += snprintf(output_buffer + written, buffer_size - written, "%s", format_hours(parsed_office_hours[i], (char *) DAY_NAMES[i]));
496 }
497
498 written += snprintf(output_buffer + written, buffer_size - written, "%s", (char *) OPEN_SERVER_TIME_HTML.data);
499 written += snprintf(output_buffer + written, buffer_size - written, "%s", format_seconds(seconds_of_day));
500 written += snprintf(output_buffer + written, buffer_size - written, "%s", (char *) CLOSE_SERVER_TIME_HTML.data);
501
502 if (conf->additional_information.len > 0) {
503 char additional_info[conf->additional_information.len + 1];
504 ngx_memcpy(additional_info, conf->additional_information.data, conf->additional_information.len);
505 additional_info[conf->additional_information.len] = '\0';
506 written += snprintf(output_buffer + written, buffer_size - written, "%s", additional_info);
61fca89b
BB
507 }
508
8b830d84 509 snprintf(output_buffer + written, buffer_size - written, "%s", (char *) FOOT_HTML.data);
61fca89b
BB
510
511 output_html.data = (unsigned char *) output_buffer;
512 output_html.len = strlen(output_buffer);
513
514 return output_html;
515}
516
517/*
518 * Given a tuple of seconds and a day name, outputs an HTML
519 * string containing the formatted data as a list item
520 */
521
522static char * format_hours(ngx_uint_t * hours, char * day)
523{
524
525 char * output_html;
526
527 output_html = malloc(64 * sizeof(char));
528 if (hours[0] == hours[1]) {
529 sprintf(output_html, "<li><strong>%s</strong>: CLOSED</li>",
530 day
531 );
532 return output_html;
533 }
534
535 sprintf(output_html, "<li><strong>%s</strong>: %s - %s</li>",
536 day,
537 (char *) format_seconds(hours[0]),
538 (char *) format_seconds(hours[1])
539 );
540
541 return output_html;
542}
543
544/*
545 * Given seconds of the day, it returns a string showing
546 * HH:MM in 24 hour format
547 */
548
549static char * format_seconds(ngx_uint_t seconds)
550{
551
552 char * output_html;
553 unsigned int hours, minutes;
554
555 output_html = malloc(6 * sizeof(char));
556
557 hours = seconds / 60 / 60;
558 minutes = (seconds / 60) % 60;
559
560 sprintf(output_html, "%s:%s",
561 left_pad(hours),
562 left_pad(minutes)
563 );
564
565 return output_html;
566}
567
568/*
569 * Returns a number as a string adding 0 if < 10
570 */
571
572static char * left_pad(unsigned int number)
573{
574
575 char * output_string;
576 char * padding;
577
578 padding = "";
f34685bb 579 output_string = malloc(4 * sizeof(char));
61fca89b
BB
580
581 if (number < 10) {
582 padding = "0";
583 }
584
f34685bb 585 snprintf(output_string, 4, "%s%u", padding, number);
61fca89b
BB
586
587 return output_string;
588}
589
bbe15175
BB
590/*
591 * Postconfig Initialization Handler
592 * Sets the request filter at the top of the chain
593 */
594
595static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf)
596{
597
67206816
BB
598 ngx_http_next_header_filter = ngx_http_top_header_filter;
599 ngx_http_top_header_filter = ngx_http_office_hours_header_filter;
600
bbe15175
BB
601 ngx_http_next_body_filter = ngx_http_top_body_filter;
602 ngx_http_top_body_filter = ngx_http_office_hours_body_filter;
603
604 rc.pattern = TIME_REGEX;
605 rc.pool = cf->pool;
606 if (ngx_regex_compile(&rc) != NGX_OK) {
607 return NGX_ERROR;
608 }
609
610 return NGX_OK;
611}