2 * Copyright 2018 Rubén Beltrán del Río
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
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
15 #include <ngx_config.h>
25 const ngx_uint_t WEEK_LENGTH
= 7;
26 const char * CLOSED_TOKEN
= "closed";
27 const ngx_str_t TIME_REGEX
= ngx_string("([0-9]{1,2})(?:\\:([0-9]{2}))?\\-([0-9]{1,2})(?:\\:([0-9]{2}))?");
28 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>");
29 const ngx_str_t MIDDLE_HTML
= ngx_string("</ul><p><em>Current Server Time is: ");
30 const ngx_str_t FOOT_HTML
= ngx_string("</em></p></body></html>");
31 const char * DAY_NAMES
[7] = {
41 /* Main Configuration Structure */
44 ngx_array_t
*office_hours
;
45 } ngx_http_office_hours_conf_t
;
47 /* Lifecycle Functions For Module Context */
49 static void *ngx_http_office_hours_create_conf(ngx_conf_t
* cf
);
50 static char *ngx_http_office_hours_merge_conf(ngx_conf_t
* cf
,
51 void *parent
, void *child
);
52 static ngx_int_t
ngx_http_office_hours_init(ngx_conf_t
* cf
);
54 /* Configuration Handler */
56 static char *ngx_http_office_hours(ngx_conf_t
* cf
, ngx_command_t
* cmd
,
61 static ngx_http_output_header_filter_pt ngx_http_next_header_filter
;
62 static ngx_http_output_body_filter_pt ngx_http_next_body_filter
;
64 /* Utility Functions */
65 static ngx_uint_t
** parse_office_hours(ngx_array_t
* office_hours
);
66 static ngx_uint_t
* parse_office_hours_string(ngx_str_t office_hours
);
67 static ngx_flag_t
within_office_hours(ngx_uint_t
** office_hours
);
68 static ngx_uint_t
get_day_of_week(time_t time
);
69 static ngx_uint_t
get_seconds_of_day(time_t time
);
70 static ngx_uint_t
parse_number(ngx_str_t string
, ngx_uint_t start
, ngx_uint_t end
);
71 static ngx_str_t
create_output_html(ngx_http_office_hours_conf_t
* conf
);
72 static char * format_hours(ngx_uint_t
* seconds
, char * day
);
73 static char * format_seconds(ngx_uint_t seconds
);
74 static char * left_pad(unsigned int number
);
77 ngx_regex_compile_t rc
;
78 ngx_str_t OUTPUT_HTML
;
84 /* Module Directives */
86 static ngx_command_t ngx_http_office_hours_commands
[] = {
88 ngx_string("office_hours"),
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
,
90 ngx_http_office_hours
,
91 NGX_HTTP_LOC_CONF_OFFSET
,
92 offsetof(ngx_http_office_hours_conf_t
, office_hours
),
102 static ngx_http_module_t ngx_http_office_hours_filter_module_ctx
= {
103 NULL
, /* Preconfiguration */
104 ngx_http_office_hours_init
, /* Postconfiguration */
106 NULL
, /* Create main configuration */
107 NULL
, /* Initialize main configuration */
109 NULL
, /* Create server configuration */
110 NULL
, /* Merge server configuration */
112 ngx_http_office_hours_create_conf
, /* Create location configuration */
113 ngx_http_office_hours_merge_conf
/* Merge location configuration */
117 /* Module Definition */
119 ngx_module_t ngx_http_office_hours_filter_module
= {
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
131 NGX_MODULE_V1_PADDING
137 * If the current time is within office hours, it goes to the next
138 * handler. Otherwise it sets the headers to 403
142 ngx_http_office_hours_header_filter(ngx_http_request_t
* r
)
145 ngx_uint_t
** parsed_office_hours
;
146 ngx_http_office_hours_conf_t
*conf
;
149 ngx_http_get_module_loc_conf(r
,
150 ngx_http_office_hours_filter_module
);
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
);
159 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
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
);
167 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
168 "Outside office hours");
170 if (OUTPUT_HTML
.data
== NULL
) {
171 OUTPUT_HTML
= create_output_html(conf
);
174 r
->headers_out
.status
= NGX_HTTP_FORBIDDEN
;
175 r
->headers_out
.content_length_n
= OUTPUT_HTML
.len
;
177 return ngx_http_next_header_filter(r
);
182 * If the current time is within office hours, it goes to the next
183 * handler. Otherwise it replaces the body with the office hours.
187 ngx_http_office_hours_body_filter(ngx_http_request_t
* r
, ngx_chain_t
*in
)
191 ngx_uint_t
** parsed_office_hours
;
193 ngx_http_office_hours_conf_t
*conf
;
196 ngx_http_get_module_loc_conf(r
,
197 ngx_http_office_hours_filter_module
);
200 if (conf
->office_hours
== NULL
) {
201 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
202 "Office hours disabled");
203 return ngx_http_next_body_filter(r
, in
);
206 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
208 if (within_office_hours(parsed_office_hours
)) {
209 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
210 "Within office hours");
211 return ngx_http_next_body_filter(r
, in
);
214 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
215 "Outside office hours");
217 if (OUTPUT_HTML
.data
== NULL
) {
218 OUTPUT_HTML
= create_output_html(conf
);
221 b
= ngx_pcalloc(r
->pool
, sizeof(ngx_buf_t
));
223 ngx_log_error(NGX_LOG_ERR
, r
->connection
->log
, 0, "Failed to allocate response buffer.");
224 return NGX_HTTP_INTERNAL_SERVER_ERROR
;
230 b
->start
= OUTPUT_HTML
.data
;
232 b
->end
= OUTPUT_HTML
.data
+ OUTPUT_HTML
.len
;
238 return ngx_http_next_body_filter(r
, &out
);
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)
247 static char *ngx_http_office_hours(ngx_conf_t
* cf
, ngx_command_t
* cmd
,
251 char *conf_structure
= conf
;
253 ngx_str_t
*hours
, *value
;
254 ngx_array_t
**office_hours
;
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
262 office_hours
= (ngx_array_t
**) (conf_structure
+ cmd
->offset
);
264 if (*office_hours
== NGX_CONF_UNSET_PTR
) {
265 *office_hours
= ngx_array_create(cf
->pool
, cf
->args
->nelts
- 1,
268 if (*office_hours
== NULL
) {
269 return NGX_CONF_ERROR
;
272 value
= cf
->args
->elts
;
274 for (i
= 1; i
< cf
->args
->nelts
; ++i
) {
275 hours
= ngx_array_push(*office_hours
);
277 return NGX_CONF_ERROR
;
288 * Initializes the configuration structure
291 static void *ngx_http_office_hours_create_conf(ngx_conf_t
* cf
)
294 ngx_http_office_hours_conf_t
*conf
;
296 conf
= ngx_pcalloc(cf
->pool
, sizeof(ngx_http_office_hours_conf_t
));
301 conf
->office_hours
= NGX_CONF_UNSET_PTR
;
307 * Merge Config Values
308 * Sets the defaults for the configuration and merges
309 * with other configurations
312 static char *ngx_http_office_hours_merge_conf(ngx_conf_t
* cf
,
313 void *parent
, void *child
)
316 ngx_http_office_hours_conf_t
*prev
= parent
;
317 ngx_http_office_hours_conf_t
*conf
= child
;
319 ngx_conf_merge_ptr_value(conf
->office_hours
, prev
->office_hours
, NULL
);
325 * Parse the office hour strings in the configuration file
326 * to fill out the hours array (in seconds)
329 static ngx_uint_t
** parse_office_hours(ngx_array_t
* office_hours
)
333 ngx_uint_t
** parsed_office_hours
;
336 parsed_office_hours
= malloc(7 * sizeof(ngx_uint_t
*));
338 hours
= office_hours
->elts
;
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
348 for (i
= 0; i
< WEEK_LENGTH
+ 1 - office_hours
->nelts
; ++i
) {
349 parsed_office_hours
[i
] = parse_office_hours_string(hours
[0]);
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
]);
357 return parsed_office_hours
;
361 * Given a time string or the closed token, return a tuple
362 * of numbers representing opening and closing hours
365 static ngx_uint_t
* parse_office_hours_string(ngx_str_t office_hours
)
368 int captures
[(1 + 4) * 3];
370 ngx_uint_t
* parsed_hours
;
372 parsed_hours
= malloc(2 * sizeof(ngx_uint_t
));
374 if(ngx_strcmp(office_hours
.data
, CLOSED_TOKEN
) == 0) {
380 n
= ngx_regex_exec(rc
.regex
, &office_hours
, captures
, (1 + 4) * 3);
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]);
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]);
394 /* Non-matching strings count as open */
397 parsed_hours
[1] = 86400;
402 * Given an office hours array, it returns whether or not
403 * it is currently within office hours.
406 static ngx_flag_t
within_office_hours(ngx_uint_t
** office_hours
)
410 ngx_uint_t day_of_week
, seconds_of_day
;
411 ngx_uint_t
* current_hours
;
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
];
419 return seconds_of_day
>= current_hours
[0] && seconds_of_day
<= current_hours
[1];
423 * Calculate the day of the week given a timestamp
426 static ngx_uint_t
get_day_of_week(time_t time
)
429 /* Epoch was thursday, so add 3 so we start on monday */
430 return (time
/ 86400 + 3) % 7;
434 * Calculate the number of seconds elapsed today
437 static ngx_uint_t
get_seconds_of_day(time_t time
)
440 return time
- (time
/ 86400) * 86400;
444 * Parses a string, returns 0 if match was not found
447 static ngx_uint_t
parse_number(ngx_str_t string
, ngx_uint_t start
, ngx_uint_t end
)
450 if (end
- start
== 0) {
454 return ngx_atoi(&string
.data
[start
], end
- start
);
458 * Given the current office hours configuration it creates the custom
462 static ngx_str_t
create_output_html(ngx_http_office_hours_conf_t
* conf
)
465 char * output_buffer
;
467 ngx_str_t output_html
;
468 ngx_uint_t i
, seconds_of_day
;
469 ngx_uint_t
** parsed_office_hours
;
472 output_buffer
= malloc(1024 * sizeof(char));
473 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
475 seconds_of_day
= get_seconds_of_day(now
);
477 sprintf(output_buffer
, "%s", (char *) HEAD_HTML
.data
);
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
]));
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
);
487 output_html
.data
= (unsigned char *) output_buffer
;
488 output_html
.len
= strlen(output_buffer
);
494 * Given a tuple of seconds and a day name, outputs an HTML
495 * string containing the formatted data as a list item
498 static char * format_hours(ngx_uint_t
* hours
, char * day
)
503 output_html
= malloc(64 * sizeof(char));
504 if (hours
[0] == hours
[1]) {
505 sprintf(output_html
, "<li><strong>%s</strong>: CLOSED</li>",
511 sprintf(output_html
, "<li><strong>%s</strong>: %s - %s</li>",
513 (char *) format_seconds(hours
[0]),
514 (char *) format_seconds(hours
[1])
521 * Given seconds of the day, it returns a string showing
522 * HH:MM in 24 hour format
525 static char * format_seconds(ngx_uint_t seconds
)
529 unsigned int hours
, minutes
;
531 output_html
= malloc(6 * sizeof(char));
533 hours
= seconds
/ 60 / 60;
534 minutes
= (seconds
/ 60) % 60;
536 sprintf(output_html
, "%s:%s",
545 * Returns a number as a string adding 0 if < 10
548 static char * left_pad(unsigned int number
)
551 char * output_string
;
555 output_string
= malloc(3 * sizeof(char));
561 sprintf(output_string
, "%s%u", padding
, number
);
563 return output_string
;
567 * Postconfig Initialization Handler
568 * Sets the request filter at the top of the chain
571 static ngx_int_t
ngx_http_office_hours_init(ngx_conf_t
* cf
)
574 ngx_http_next_header_filter
= ngx_http_top_header_filter
;
575 ngx_http_top_header_filter
= ngx_http_office_hours_header_filter
;
577 ngx_http_next_body_filter
= ngx_http_top_body_filter
;
578 ngx_http_top_body_filter
= ngx_http_office_hours_body_filter
;
580 rc
.pattern
= TIME_REGEX
;
582 if (ngx_regex_compile(&rc
) != NGX_OK
) {