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