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.
14 #include <ngx_config.h>
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] = {
40 /* Main Configuration Structure */
43 ngx_array_t
*office_hours
;
44 } ngx_http_office_hours_conf_t
;
46 /* Lifecycle Functions For Module Context */
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
);
53 /* Configuration Handler */
55 static char *ngx_http_office_hours(ngx_conf_t
* cf
, ngx_command_t
* cmd
,
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
;
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
);
76 ngx_regex_compile_t rc
;
77 ngx_str_t OUTPUT_HTML
;
83 /* Module Directives */
85 static ngx_command_t ngx_http_office_hours_commands
[] = {
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
),
100 static ngx_http_module_t ngx_http_office_hours_filter_module_ctx
= {
101 NULL
, /* Preconfiguration */
102 ngx_http_office_hours_init
, /* Postconfiguration */
104 NULL
, /* Create main configuration */
105 NULL
, /* Initialize main configuration */
107 NULL
, /* Create server configuration */
108 NULL
, /* Merge server configuration */
110 ngx_http_office_hours_create_conf
, /* Create location configuration */
111 ngx_http_office_hours_merge_conf
/* Merge location configuration */
114 /* Module Definition */
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
128 NGX_MODULE_V1_PADDING
133 * If the current time is within office hours, it goes to the next
134 * handler. Otherwise it sets the headers to 403
138 ngx_http_office_hours_header_filter(ngx_http_request_t
* r
)
141 ngx_uint_t
** parsed_office_hours
;
142 ngx_http_office_hours_conf_t
*conf
;
145 ngx_http_get_module_loc_conf(r
,
146 ngx_http_office_hours_filter_module
);
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
);
154 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
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
);
162 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
163 "Outside office hours");
165 if (OUTPUT_HTML
.data
== NULL
) {
166 OUTPUT_HTML
= create_output_html(conf
);
169 r
->headers_out
.status
= NGX_HTTP_FORBIDDEN
;
170 r
->headers_out
.content_length_n
= OUTPUT_HTML
.len
;
172 return ngx_http_next_header_filter(r
);
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.
182 ngx_http_office_hours_body_filter(ngx_http_request_t
* r
, ngx_chain_t
*in
)
186 ngx_uint_t
** parsed_office_hours
;
188 ngx_http_office_hours_conf_t
*conf
;
191 ngx_http_get_module_loc_conf(r
,
192 ngx_http_office_hours_filter_module
);
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
);
200 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
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
);
208 ngx_log_error(NGX_LOG_DEBUG
, r
->connection
->log
, 0,
209 "Outside office hours");
211 if (OUTPUT_HTML
.data
== NULL
) {
212 OUTPUT_HTML
= create_output_html(conf
);
215 b
= ngx_pcalloc(r
->pool
, sizeof(ngx_buf_t
));
217 ngx_log_error(NGX_LOG_ERR
, r
->connection
->log
, 0, "Failed to allocate response buffer.");
218 return NGX_HTTP_INTERNAL_SERVER_ERROR
;
224 b
->start
= OUTPUT_HTML
.data
;
226 b
->end
= OUTPUT_HTML
.data
+ OUTPUT_HTML
.len
;
232 return ngx_http_next_body_filter(r
, &out
);
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)
241 static char *ngx_http_office_hours(ngx_conf_t
* cf
, ngx_command_t
* cmd
,
245 char *conf_structure
= conf
;
247 ngx_str_t
*hours
, *value
;
248 ngx_array_t
**office_hours
;
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
256 office_hours
= (ngx_array_t
**) (conf_structure
+ cmd
->offset
);
258 if (*office_hours
== NGX_CONF_UNSET_PTR
) {
259 *office_hours
= ngx_array_create(cf
->pool
, cf
->args
->nelts
- 1,
262 if (*office_hours
== NULL
) {
263 return NGX_CONF_ERROR
;
266 value
= cf
->args
->elts
;
268 for (i
= 1; i
< cf
->args
->nelts
; ++i
) {
269 hours
= ngx_array_push(*office_hours
);
271 return NGX_CONF_ERROR
;
281 * Initializes the configuration structure
284 static void *ngx_http_office_hours_create_conf(ngx_conf_t
* cf
)
287 ngx_http_office_hours_conf_t
*conf
;
289 conf
= ngx_pcalloc(cf
->pool
, sizeof(ngx_http_office_hours_conf_t
));
294 conf
->office_hours
= NGX_CONF_UNSET_PTR
;
300 * Merge Config Values
301 * Sets the defaults for the configuration and merges
302 * with other configurations
305 static char *ngx_http_office_hours_merge_conf(ngx_conf_t
* cf
,
306 void *parent
, void *child
)
309 ngx_http_office_hours_conf_t
*prev
= parent
;
310 ngx_http_office_hours_conf_t
*conf
= child
;
312 ngx_conf_merge_ptr_value(conf
->office_hours
, prev
->office_hours
, NULL
);
318 * Parse the office hour strings in the configuration file
319 * to fill out the hours array (in seconds)
322 static ngx_uint_t
** parse_office_hours(ngx_array_t
* office_hours
)
326 ngx_uint_t
** parsed_office_hours
;
329 parsed_office_hours
= malloc(7 * sizeof(ngx_uint_t
*));
331 hours
= office_hours
->elts
;
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
341 for (i
= 0; i
< WEEK_LENGTH
+ 1 - office_hours
->nelts
; ++i
) {
342 parsed_office_hours
[i
] = parse_office_hours_string(hours
[0]);
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
]);
350 return parsed_office_hours
;
354 * Given a time string or the closed token, return a tuple
355 * of numbers representing opening and closing hours
358 static ngx_uint_t
* parse_office_hours_string(ngx_str_t office_hours
)
361 int captures
[(1 + 4) * 3];
363 ngx_uint_t
* parsed_hours
;
365 parsed_hours
= malloc(2 * sizeof(ngx_uint_t
));
367 if(ngx_strcmp(office_hours
.data
, CLOSED_TOKEN
) == 0) {
373 n
= ngx_regex_exec(rc
.regex
, &office_hours
, captures
, (1 + 4) * 3);
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]);
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]);
387 /* Non-matching strings count as open */
390 parsed_hours
[1] = 86400;
395 * Given an office hours array, it returns whether or not
396 * it is currently within office hours.
399 static ngx_flag_t
within_office_hours(ngx_uint_t
** office_hours
)
403 ngx_uint_t day_of_week
, seconds_of_day
;
404 ngx_uint_t
* current_hours
;
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
];
412 return seconds_of_day
>= current_hours
[0] && seconds_of_day
<= current_hours
[1];
416 * Calculate the day of the week given a timestamp
419 static ngx_uint_t
get_day_of_week(time_t time
)
422 /* Epoch was thursday, so add 3 so we start on monday */
423 return (time
/ 86400 + 3) % 7;
427 * Calculate the number of seconds elapsed today
430 static ngx_uint_t
get_seconds_of_day(time_t time
)
433 return time
- (time
/ 86400) * 86400;
437 * Parses a string, returns 0 if match was not found
440 static ngx_uint_t
parse_number(ngx_str_t string
, ngx_uint_t start
, ngx_uint_t end
)
443 if (end
- start
== 0) {
447 return ngx_atoi(&string
.data
[start
], end
- start
);
451 * Given the current office hours configuration it creates the custom
455 static ngx_str_t
create_output_html(ngx_http_office_hours_conf_t
* conf
)
458 char * output_buffer
;
460 ngx_str_t output_html
;
461 ngx_uint_t i
, seconds_of_day
;
462 ngx_uint_t
** parsed_office_hours
;
464 output_buffer
= malloc(1024 * sizeof(char));
465 parsed_office_hours
= parse_office_hours(conf
->office_hours
);
467 seconds_of_day
= get_seconds_of_day(now
);
469 sprintf(output_buffer
, "%s", (char *) HEAD_HTML
.data
);
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
]));
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
);
479 output_html
.data
= (unsigned char *) output_buffer
;
480 output_html
.len
= strlen(output_buffer
);
486 * Given a tuple of seconds and a day name, outputs an HTML
487 * string containing the formatted data as a list item
490 static char * format_hours(ngx_uint_t
* hours
, char * day
)
495 output_html
= malloc(64 * sizeof(char));
496 if (hours
[0] == hours
[1]) {
497 sprintf(output_html
, "<li><strong>%s</strong>: CLOSED</li>",
503 sprintf(output_html
, "<li><strong>%s</strong>: %s - %s</li>",
505 (char *) format_seconds(hours
[0]),
506 (char *) format_seconds(hours
[1])
513 * Given seconds of the day, it returns a string showing
514 * HH:MM in 24 hour format
517 static char * format_seconds(ngx_uint_t seconds
)
521 unsigned int hours
, minutes
;
523 output_html
= malloc(6 * sizeof(char));
525 hours
= seconds
/ 60 / 60;
526 minutes
= (seconds
/ 60) % 60;
528 sprintf(output_html
, "%s:%s",
537 * Returns a number as a string adding 0 if < 10
540 static char * left_pad(unsigned int number
)
543 char * output_string
;
547 output_string
= malloc(4 * sizeof(char));
553 snprintf(output_string
, 4, "%s%u", padding
, number
);
555 return output_string
;
559 * Postconfig Initialization Handler
560 * Sets the request filter at the top of the chain
563 static ngx_int_t
ngx_http_office_hours_init(ngx_conf_t
* cf
)
566 ngx_http_next_header_filter
= ngx_http_top_header_filter
;
567 ngx_http_top_header_filter
= ngx_http_office_hours_header_filter
;
569 ngx_http_next_body_filter
= ngx_http_top_body_filter
;
570 ngx_http_top_body_filter
= ngx_http_office_hours_body_filter
;
572 rc
.pattern
= TIME_REGEX
;
574 if (ngx_regex_compile(&rc
) != NGX_OK
) {