]> git.r.bdr.sh - rbdr/ngx_http_office_hours_filter_module/blob - ngx_http_office_hours_filter_module.c
Formatting
[rbdr/ngx_http_office_hours_filter_module] / ngx_http_office_hours_filter_module.c
1 /*
2 * Copyright 2018 Rubén Beltrán del Río
3 *
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
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
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 #include <ngx_config.h>
15 #include <ngx_core.h>
16 #include <ngx_http.h>
17
18 /*
19 * Declarations
20 */
21
22 /* Constants */
23
24 const ngx_uint_t WEEK_LENGTH = 7;
25 const char * CLOSED_TOKEN = "closed";
26 const ngx_str_t TIME_REGEX = ngx_string("([0-9]{1,2})(?:\\:([0-9]{2}))?\\-([0-9]{1,2})(?:\\:([0-9]{2}))?");
27 const 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>");
28 const ngx_str_t OPEN_SERVER_TIME_HTML = ngx_string("</ul><p><em>Current Server Time is: ");
29 const ngx_str_t CLOSE_SERVER_TIME_HTML = ngx_string("</em></p>");
30 const ngx_str_t FOOT_HTML = ngx_string("</body></html>");
31 const char * DAY_NAMES[7] = {
32 "Monday",
33 "Tuesday",
34 "Wednesday",
35 "Thursday",
36 "Friday",
37 "Saturday",
38 "Sunday"
39 };
40
41 /* Main Configuration Structure */
42
43 typedef struct {
44 ngx_array_t *office_hours;
45 ngx_str_t additional_information;
46 } ngx_http_office_hours_conf_t;
47
48 /* Lifecycle Functions For Module Context */
49
50 static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf);
51 static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
52 void *parent, void *child);
53 static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf);
54
55 /* Configuration Handler */
56
57 static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
58 void *conf);
59
60 /* Filter Storage */
61
62 static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
63 static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
64
65 /* Utility Functions */
66 static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours);
67 static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours);
68 static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours);
69 static ngx_uint_t get_day_of_week(time_t time);
70 static ngx_uint_t get_seconds_of_day(time_t time);
71 static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end);
72 static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf);
73 static char * format_hours(ngx_uint_t * seconds, char * day);
74 static char * format_seconds(ngx_uint_t seconds);
75 static char * left_pad(unsigned int number);
76
77 /* Globals */
78 ngx_regex_compile_t rc;
79 ngx_str_t OUTPUT_HTML;
80
81 /*
82 * Module Definitions
83 */
84
85 /* Module Directives */
86
87 static ngx_command_t ngx_http_office_hours_commands[] = {
88 {
89 ngx_string("office_hours"),
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,
91 ngx_http_office_hours,
92 NGX_HTTP_LOC_CONF_OFFSET,
93 offsetof(ngx_http_office_hours_conf_t, office_hours),
94 NULL
95 },
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 },
104
105 ngx_null_command
106 };
107
108 /* Module Context */
109
110 static ngx_http_module_t ngx_http_office_hours_filter_module_ctx = {
111 NULL, /* Preconfiguration */
112 ngx_http_office_hours_init, /* Postconfiguration */
113
114 NULL, /* Create main configuration */
115 NULL, /* Initialize main configuration */
116
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 */
122 };
123
124 /* Module Definition */
125
126 ngx_module_t ngx_http_office_hours_filter_module = {
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
139 };
140
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
147 static ngx_int_t
148 ngx_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
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
175 if (OUTPUT_HTML.data == NULL) {
176 OUTPUT_HTML = create_output_html(conf);
177 }
178
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
185 /*
186 * Main Body Filter
187 * If the current time is within office hours, it goes to the next
188 * handler. Otherwise it replaces the body with the office hours.
189 */
190
191 static ngx_int_t
192 ngx_http_office_hours_body_filter(ngx_http_request_t * r, ngx_chain_t *in)
193 {
194
195 ngx_buf_t *b;
196 ngx_uint_t ** parsed_office_hours;
197 ngx_chain_t out;
198 ngx_http_office_hours_conf_t *conf;
199
200 conf =
201 ngx_http_get_module_loc_conf(r,
202 ngx_http_office_hours_filter_module);
203
204 if (conf->office_hours == NULL) {
205 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
206 "Office hours disabled");
207 return ngx_http_next_body_filter(r, in);
208 }
209
210 parsed_office_hours = parse_office_hours(conf->office_hours);
211
212 if (within_office_hours(parsed_office_hours)) {
213 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
214 "Within office hours");
215 return ngx_http_next_body_filter(r, in);
216 }
217
218 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
219 "Outside office hours");
220
221 if (OUTPUT_HTML.data == NULL) {
222 OUTPUT_HTML = create_output_html(conf);
223 }
224
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);
243 }
244
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 */
250
251 static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
252 void *conf)
253 {
254
255 char *conf_structure = conf;
256
257 ngx_str_t *hours, *value;
258 ngx_array_t **office_hours;
259 ngx_uint_t i;
260
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);
267
268 if (*office_hours == NGX_CONF_UNSET_PTR) {
269 *office_hours = ngx_array_create(cf->pool, cf->args->nelts - 1,
270 sizeof(ngx_str_t));
271
272 if (*office_hours == NULL) {
273 return NGX_CONF_ERROR;
274 }
275 }
276 value = cf->args->elts;
277
278 for (i = 1; i < cf->args->nelts; ++i) {
279 hours = ngx_array_push(*office_hours);
280 if (hours == NULL) {
281 return NGX_CONF_ERROR;
282 }
283 *hours = value[i];
284 }
285
286 return NGX_CONF_OK;
287 }
288
289 /*
290 * Config Creator
291 * Initializes the configuration structure
292 */
293
294 static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf)
295 {
296
297 ngx_http_office_hours_conf_t *conf;
298
299 conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_office_hours_conf_t));
300
301 if (conf == NULL) {
302 return NULL;
303 }
304 conf->office_hours = NGX_CONF_UNSET_PTR;
305
306 return conf;
307 }
308
309 /*
310 * Merge Config Values
311 * Sets the defaults for the configuration and merges
312 * with other configurations
313 */
314
315 static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
316 void *parent, void *child)
317 {
318
319 ngx_http_office_hours_conf_t *prev = parent;
320 ngx_http_office_hours_conf_t *conf = child;
321
322 ngx_conf_merge_ptr_value(conf->office_hours, prev->office_hours, NULL);
323
324 return NGX_CONF_OK;
325 }
326
327 /*
328 * Parse the office hour strings in the configuration file
329 * to fill out the hours array (in seconds)
330 */
331
332 static 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
368 static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours)
369 {
370
371 int captures[(1 + 4) * 3];
372 ngx_int_t n;
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
383 n = ngx_regex_exec(rc.regex, &office_hours, captures, (1 + 4) * 3);
384
385 if (n >= 0) {
386 /* Opening Hours */
387
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]);
390
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]);
393
394 return parsed_hours;
395 }
396
397 /* Non-matching strings count as open */
398
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
409 static 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 */
428
429 static 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 */
439
440 static ngx_uint_t get_seconds_of_day(time_t time)
441 {
442
443 return time - (time / 86400) * 86400;
444 }
445
446 /*
447 * Parses a string, returns 0 if match was not found
448 */
449
450 static 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
460 /*
461 * Given the current office hours configuration it creates the custom
462 * HTML
463 */
464
465 static 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
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
486 parsed_office_hours = parse_office_hours(conf->office_hours);
487 now = ngx_time();
488 seconds_of_day = get_seconds_of_day(now);
489
490 int written = 0;
491
492 written += snprintf(output_buffer + written, buffer_size - written, "%s", (char *) HEAD_HTML.data);
493
494 for (i = 0; i < 7; ++i) {
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);
507 }
508
509 snprintf(output_buffer + written, buffer_size - written, "%s", (char *) FOOT_HTML.data);
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
522 static 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
549 static 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
572 static char * left_pad(unsigned int number)
573 {
574
575 char * output_string;
576 char * padding;
577
578 padding = "";
579 output_string = malloc(4 * sizeof(char));
580
581 if (number < 10) {
582 padding = "0";
583 }
584
585 snprintf(output_string, 4, "%s%u", padding, number);
586
587 return output_string;
588 }
589
590 /*
591 * Postconfig Initialization Handler
592 * Sets the request filter at the top of the chain
593 */
594
595 static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf)
596 {
597
598 ngx_http_next_header_filter = ngx_http_top_header_filter;
599 ngx_http_top_header_filter = ngx_http_office_hours_header_filter;
600
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 }