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