]> git.r.bdr.sh - rbdr/ngx_http_office_hours_filter_module/blob - ngx_http_office_hours_filter_module.c
49fe50f55d66fbf8f9c4ff26fb43360d0857fcde
[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 MIDDLE_HTML = ngx_string("</ul><p><em>Current Server Time is: ");
29 const ngx_str_t FOOT_HTML = ngx_string("</em></p></body></html>");
30 const char * DAY_NAMES[7] = {
31 "Monday",
32 "Tuesday",
33 "Wednesday",
34 "Thursday",
35 "Friday",
36 "Saturday",
37 "Sunday"
38 };
39
40 /* Main Configuration Structure */
41
42 typedef struct {
43 ngx_array_t *office_hours;
44 } ngx_http_office_hours_conf_t;
45
46 /* Lifecycle Functions For Module Context */
47
48 static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf);
49 static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
50 void *parent, void *child);
51 static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf);
52
53 /* Configuration Handler */
54
55 static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
56 void *conf);
57
58 /* Filter Storage */
59
60 static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
61 static ngx_http_output_body_filter_pt ngx_http_next_body_filter;
62
63 /* Utility Functions */
64 static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours);
65 static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours);
66 static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours);
67 static ngx_uint_t get_day_of_week(time_t time);
68 static ngx_uint_t get_seconds_of_day(time_t time);
69 static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end);
70 static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf);
71 static char * format_hours(ngx_uint_t * seconds, char * day);
72 static char * format_seconds(ngx_uint_t seconds);
73 static char * left_pad(unsigned int number);
74
75 /* Globals */
76 ngx_regex_compile_t rc;
77 ngx_str_t OUTPUT_HTML;
78
79 /*
80 * Module Definitions
81 */
82
83 /* Module Directives */
84
85 static ngx_command_t ngx_http_office_hours_commands[] = {
86 {
87 ngx_string("office_hours"),
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,
89 ngx_http_office_hours,
90 NGX_HTTP_LOC_CONF_OFFSET,
91 offsetof(ngx_http_office_hours_conf_t, office_hours),
92 NULL
93 },
94
95 ngx_null_command
96 };
97
98 /* Module Context */
99
100 static ngx_http_module_t ngx_http_office_hours_filter_module_ctx = {
101 NULL, /* Preconfiguration */
102 ngx_http_office_hours_init, /* Postconfiguration */
103
104 NULL, /* Create main configuration */
105 NULL, /* Initialize main configuration */
106
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 */
112 };
113
114 /* Module Definition */
115
116 ngx_module_t ngx_http_office_hours_filter_module = {
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
129 };
130
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
137 static ngx_int_t
138 ngx_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
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
165 if (OUTPUT_HTML.data == NULL) {
166 OUTPUT_HTML = create_output_html(conf);
167 }
168
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
175 /*
176 * Main Body Filter
177 * If the current time is within office hours, it goes to the next
178 * handler. Otherwise it replaces the body with the office hours.
179 */
180
181 static ngx_int_t
182 ngx_http_office_hours_body_filter(ngx_http_request_t * r, ngx_chain_t *in)
183 {
184
185 ngx_buf_t *b;
186 ngx_uint_t ** parsed_office_hours;
187 ngx_chain_t out;
188 ngx_http_office_hours_conf_t *conf;
189
190 conf =
191 ngx_http_get_module_loc_conf(r,
192 ngx_http_office_hours_filter_module);
193
194 if (conf->office_hours == NULL) {
195 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
196 "Office hours disabled");
197 return ngx_http_next_body_filter(r, in);
198 }
199
200 parsed_office_hours = parse_office_hours(conf->office_hours);
201
202 if (within_office_hours(parsed_office_hours)) {
203 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
204 "Within office hours");
205 return ngx_http_next_body_filter(r, in);
206 }
207
208 ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
209 "Outside office hours");
210
211 if (OUTPUT_HTML.data == NULL) {
212 OUTPUT_HTML = create_output_html(conf);
213 }
214
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);
233 }
234
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 */
240
241 static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
242 void *conf)
243 {
244
245 char *conf_structure = conf;
246
247 ngx_str_t *hours, *value;
248 ngx_array_t **office_hours;
249 ngx_uint_t i;
250
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);
257
258 if (*office_hours == NGX_CONF_UNSET_PTR) {
259 *office_hours = ngx_array_create(cf->pool, cf->args->nelts - 1,
260 sizeof(ngx_str_t));
261
262 if (*office_hours == NULL) {
263 return NGX_CONF_ERROR;
264 }
265 }
266 value = cf->args->elts;
267
268 for (i = 1; i < cf->args->nelts; ++i) {
269 hours = ngx_array_push(*office_hours);
270 if (hours == NULL) {
271 return NGX_CONF_ERROR;
272 }
273 *hours = value[i];
274 }
275
276 return NGX_CONF_OK;
277 }
278
279 /*
280 * Config Creator
281 * Initializes the configuration structure
282 */
283
284 static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf)
285 {
286
287 ngx_http_office_hours_conf_t *conf;
288
289 conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_office_hours_conf_t));
290
291 if (conf == NULL) {
292 return NULL;
293 }
294 conf->office_hours = NGX_CONF_UNSET_PTR;
295
296 return conf;
297 }
298
299 /*
300 * Merge Config Values
301 * Sets the defaults for the configuration and merges
302 * with other configurations
303 */
304
305 static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
306 void *parent, void *child)
307 {
308
309 ngx_http_office_hours_conf_t *prev = parent;
310 ngx_http_office_hours_conf_t *conf = child;
311
312 ngx_conf_merge_ptr_value(conf->office_hours, prev->office_hours, NULL);
313
314 return NGX_CONF_OK;
315 }
316
317 /*
318 * Parse the office hour strings in the configuration file
319 * to fill out the hours array (in seconds)
320 */
321
322 static 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
358 static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours)
359 {
360
361 int captures[(1 + 4) * 3];
362 ngx_int_t n;
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
373 n = ngx_regex_exec(rc.regex, &office_hours, captures, (1 + 4) * 3);
374
375 if (n >= 0) {
376 /* Opening Hours */
377
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]);
380
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]);
383
384 return parsed_hours;
385 }
386
387 /* Non-matching strings count as open */
388
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
399 static 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 */
418
419 static 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 */
429
430 static ngx_uint_t get_seconds_of_day(time_t time)
431 {
432
433 return time - (time / 86400) * 86400;
434 }
435
436 /*
437 * Parses a string, returns 0 if match was not found
438 */
439
440 static 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
450 /*
451 * Given the current office hours configuration it creates the custom
452 * HTML
453 */
454
455 static 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
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
490 static 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
517 static 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
540 static char * left_pad(unsigned int number)
541 {
542
543 char * output_string;
544 char * padding;
545
546 padding = "";
547 output_string = malloc(4 * sizeof(char));
548
549 if (number < 10) {
550 padding = "0";
551 }
552
553 snprintf(output_string, 4, "%s%u", padding, number);
554
555 return output_string;
556 }
557
558 /*
559 * Postconfig Initialization Handler
560 * Sets the request filter at the top of the chain
561 */
562
563 static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf)
564 {
565
566 ngx_http_next_header_filter = ngx_http_top_header_filter;
567 ngx_http_top_header_filter = ngx_http_office_hours_header_filter;
568
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 }