~rbdr/ngx_http_office_hours_filter_module

407e2e8fb8a5f825ff644a834688844ac0c4a86a — Ben Beltran 5 years ago 0312f22 + 478c3b2 1.0.0
Merge branch 'release/1.0.0'
A .gitignore => .gitignore +1 -0
@@ 0,0 1,1 @@
*.orig

A CHANGELOG.md => CHANGELOG.md +21 -0
@@ 0,0 1,21 @@
# Changelog
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

## 1.0.0 - 2018-12-28
### Added
- This CHANGELOG
- A README
- A CONTRIBUTING guide
- Formatting using astyle
- Git hook to format code before commit
- Makefile with tasks to format and install git hooks
- A gitignore file
- Parsing of directive time ranges in UTC only
- Dynamically generate HTML based on hours directive

[Unreleased]: https://gitlab.com/rbdr/ngx_office_hours/compare/master...develop

A CONTRIBUTING.md => CONTRIBUTING.md +29 -0
@@ 0,0 1,29 @@
# Contributing to ngx_http_office_hours_filter_module

This NGINX module has the simple goal of allowing you to specify office
hours for your server and not serving anything outside those hours.

Any contributions are welcome especially if it works towards that goal.

You can check the `README` for a list of **Further Improvements** if
you want inspiration. Also, since I'm not great at C, any improvements
to the code itself are also welcome!

## The objective of ngx_http_office_hours_filter_module

Give your web server the benefit of a regulated work schedule, and
notify the consumers of the appropriate office hours to visit the
website.

Providing better ways to specify the working schedule of the server
are in line with the objective.

## How to contribute

Above All: Be nice, always.

* Always make sure the code is properly formatted with `make format`
* Make the PRs according to [Git Flow][gitflow]: (features go to
  develop, hotfixes go to master)

[gitflow]: https://github.com/nvie/gitflow

A LICENSE => LICENSE +201 -0
@@ 0,0 1,201 @@
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright 2018 Rubén Beltrán del Río

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

A Makefile => Makefile +5 -0
@@ 0,0 1,5 @@
setup_hooks:
	ln -s ../../scripts/git-hooks/pre-commit .git/hooks/pre-commit

format:
	astyle --lineend=linux --style=kr *.c

M README.md => README.md +91 -1
@@ 1,3 1,93 @@
# Nginx Office Hours

A victory for the server's labor rights: An nginx module that allows you to serve your content only during office hours.
\ No newline at end of file
A victory for the server's labor rights: An nginx module that allows you to serve your content only during office hours.

## Using the directive

The `office_hours` directive expects a list of time ranges separated by
spaces. The first range will be used as the default, and the rest will
be read from right to left, ending with *sunday*

### Example 1: Open 24 hours

Don't use this directive.

### Example 2: Open every day from 08:30 AM to 7:00 PM

```
office_hours 8:30-19;
```

Some things worth noting here: the format of time ranges uses 24 hour
style, so no pesky AMs or PMs. Likewise, minutes are optional. Finally,
note that since only one range was defined, this is applied to all days
of the week. Another noteworthy 

### Example 3: Open every day from 08:30 AM to 7:00 PM, but closed sundays

```
office_hours 8:30-19 closed;
```

Two important things here: first notice that the closed keyword
specifies that the server is closed on a specific day; second, notice
how the last element is used for sunday, while the first one still
applies to Monday-Saturday.

### Example 4: Open weekdays from 08:30 AM to 7:00 PM, Saturdays 10:00 AM to 4:00 PM, closed on sundays

```
office_hours 8:30-19 10-16 closed;
```

Now hopefully you can see the pattern: The first time range applies to
Monday-Friday, next one to Saturday and last one to Sunday.

### Example 5: Open weekdays from 08:30 AM to 7:00 PM, closed on thursdays, reduced hours on weekends.

```
office_hours 8:30-19 closed 8:30-19 10-16 10-16;
```

Since we had to specify from Thursday, we have to explicitly set the
values for Friday, Saturday and Sunday.

### Example 6: Closed every day.

Uninstall nginx.

## What you will need to get started

* [astyle][astyle]: Used to format the code
* An `nginx` [source distribution][nginx] to compile the code.
* A way to compile `nginx`. Check out [their guide][nginx-guide]!

## Building the module

You can build office hours as a dynamic module. From the `nginx` source
directory run:

```
./configure --add-dynamic-module=/path/to/ngx_http_office_hours_filter_module
make
```

For more information check the [nginx docs][nginx-module-docs]

## Installing git hooks

This repo contains a pre-commit git hook so indent will run before every
commit. Run `make setup_hooks` to install it.

## Further Improvements

* Add support for timezones (currently only GMT)
* Add support for public holidays
* Add support to respect the time zone of the visitor and not just the
  server
* Add support for double shifts in the same day

[astyle]: http://astyle.sourceforge.net
[nginx]: https://nginx.org/en/download.html
[nginx-guide]: https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/#sources
[nginx-module-docs]: https://www.nginx.com/resources/wiki/extending/

A config => config +24 -0
@@ 0,0 1,24 @@
#
# Copyright 2018 Rubén Beltrán del Río
# 
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.

ngx_addon_name=ngx_http_office_hours_filter_module

if test -n "$ngx_module_link"; then
  ngx_module_type=HTTP
  ngx_module_name=ngx_http_office_hours_filter_module
  ngx_module_srcs="$ngx_addon_dir/ngx_http_office_hours_filter_module.c"

  . auto/module
else
  HTTP_MODULES="$HTTP_MODULES ngx_http_office_hours_filter_module"
  NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_office_hours_filter_module.c"
fi

A doc/example_configuration => doc/example_configuration +15 -0
@@ 0,0 1,15 @@
server {

        listen 80;

        root /var/www/blog;
        index index.html index.htm;

        server_name blog.unlimited.pizza;

        office_hours 8:30-20 10-16 closed;

        location / {
                try_files $uri $uri/ =404;
        }
}

A ngx_http_office_hours_filter_module.c => ngx_http_office_hours_filter_module.c +587 -0
@@ 0,0 1,587 @@
/*
 * Copyright 2018 Rubén Beltrán del Río
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */


#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>

/*
 * Declarations
 */

/* Constants */

const ngx_uint_t WEEK_LENGTH = 7;
const char * CLOSED_TOKEN = "closed";
const ngx_str_t TIME_REGEX = ngx_string("([0-9]{1,2})(?:\\:([0-9]{2}))?\\-([0-9]{1,2})(?:\\:([0-9]{2}))?");
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>");
const ngx_str_t MIDDLE_HTML = ngx_string("</ul><p><em>Current Server Time is: ");
const ngx_str_t FOOT_HTML = ngx_string("</em></p></body></html>");
const char * DAY_NAMES[7] = {
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
};

/* Main Configuration Structure */

typedef struct {
    ngx_array_t *office_hours;
} ngx_http_office_hours_conf_t;

/* Lifecycle Functions For Module Context */

static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf);
static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
        void *parent, void *child);
static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf);

/* Configuration Handler */

static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
                                   void *conf);

/* Filter Storage */

static ngx_http_output_header_filter_pt ngx_http_next_header_filter;
static ngx_http_output_body_filter_pt ngx_http_next_body_filter;

/* Utility Functions */
static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours);
static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours);
static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours);
static ngx_uint_t get_day_of_week(time_t time);
static ngx_uint_t get_seconds_of_day(time_t time);
static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end);
static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf);
static char * format_hours(ngx_uint_t * seconds, char * day);
static char * format_seconds(ngx_uint_t seconds);
static char * left_pad(unsigned int number);

/* Globals */
ngx_regex_compile_t rc;
ngx_str_t OUTPUT_HTML;

/*
 * Module Definitions
 */

/* Module Directives */

static ngx_command_t ngx_http_office_hours_commands[] = {
    {
        ngx_string("office_hours"),
        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,
        ngx_http_office_hours,
        NGX_HTTP_LOC_CONF_OFFSET,
        offsetof(ngx_http_office_hours_conf_t, office_hours),
        NULL
    },

    ngx_null_command
};


/* Module Context */

static ngx_http_module_t ngx_http_office_hours_filter_module_ctx = {
    NULL,			/* Preconfiguration */
    ngx_http_office_hours_init,	/* Postconfiguration */

    NULL,			/* Create main configuration */
    NULL,			/* Initialize main configuration */

    NULL,			/* Create server configuration */
    NULL,			/* Merge server configuration */

    ngx_http_office_hours_create_conf,	/* Create location configuration */
    ngx_http_office_hours_merge_conf	/* Merge location configuration */
};


/* Module Definition */

ngx_module_t ngx_http_office_hours_filter_module = {
    NGX_MODULE_V1,		//Module Version
    &ngx_http_office_hours_filter_module_ctx,	//Module context
    ngx_http_office_hours_commands,	//Module commands
    NGX_HTTP_MODULE,		//Module Type
    NULL,			//Initialize Master
    NULL,			//Initialize Module
    NULL,			//Initialize Process
    NULL,			//Initialize Thread
    NULL,			//Exit Thread
    NULL,			//Exit Process
    NULL,			//Exit Master
    NGX_MODULE_V1_PADDING
};


/*
 * Main Header Filter
 * If the current time is within office hours, it goes to the next
 * handler. Otherwise it sets the headers to 403
 */

static ngx_int_t
ngx_http_office_hours_header_filter(ngx_http_request_t * r)
{

    ngx_uint_t ** parsed_office_hours;
    ngx_http_office_hours_conf_t *conf;

    conf =
        ngx_http_get_module_loc_conf(r,
                                     ngx_http_office_hours_filter_module);


    if (conf->office_hours == NULL) {
        ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                      "Office hours disabled");
        return ngx_http_next_header_filter(r);
    }

    parsed_office_hours = parse_office_hours(conf->office_hours);

    if (within_office_hours(parsed_office_hours)) {
        ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                      "Within office hours");
        return ngx_http_next_header_filter(r);
    }

    ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                  "Outside office hours");

    if (OUTPUT_HTML.data == NULL) {
        OUTPUT_HTML = create_output_html(conf);
    }

    r->headers_out.status = NGX_HTTP_FORBIDDEN;
    r->headers_out.content_length_n = OUTPUT_HTML.len;

    return ngx_http_next_header_filter(r);
}

/*
 * Main Body Filter
 * If the current time is within office hours, it goes to the next
 * handler. Otherwise it replaces the body with the office hours.
 */

static ngx_int_t
ngx_http_office_hours_body_filter(ngx_http_request_t * r, ngx_chain_t *in)
{

    ngx_buf_t    *b;
    ngx_uint_t ** parsed_office_hours;
    ngx_chain_t   out;
    ngx_http_office_hours_conf_t *conf;

    conf =
        ngx_http_get_module_loc_conf(r,
                                     ngx_http_office_hours_filter_module);


    if (conf->office_hours == NULL) {
        ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                      "Office hours disabled");
        return ngx_http_next_body_filter(r, in);
    }

    parsed_office_hours = parse_office_hours(conf->office_hours);

    if (within_office_hours(parsed_office_hours)) {
        ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                      "Within office hours");
        return ngx_http_next_body_filter(r, in);
    }

    ngx_log_error(NGX_LOG_DEBUG, r->connection->log, 0,
                  "Outside office hours");

    if (OUTPUT_HTML.data == NULL) {
        OUTPUT_HTML = create_output_html(conf);
    }

    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
    if (b == NULL) {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "Failed to allocate response buffer.");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    out.buf = b;
    out.next = NULL;

    b->start = OUTPUT_HTML.data;
    b->pos = b->start;
    b->end = OUTPUT_HTML.data + OUTPUT_HTML.len;
    b->last = b->end;

    b->memory = 1;
    b->last_buf = 1;

    return ngx_http_next_body_filter(r, &out);
}

/*
 * Callback for `office_hours ` directive
 * Reads the configuration loaded from the config file(cf)
 * And writes it to the right place in the module configuration(conf)
 */

static char *ngx_http_office_hours(ngx_conf_t * cf, ngx_command_t * cmd,
                                   void *conf)
{

    char *conf_structure = conf;

    ngx_str_t *hours, *value;
    ngx_array_t **office_hours;
    ngx_uint_t i;

    /* Gets the array from the config structure using the defined
     * offset, and if the pointer is unset it creates a new one.
     * (The first element is the directive itself, so we should be
     * offset by 1)
     */
    office_hours = (ngx_array_t **) (conf_structure + cmd->offset);

    if (*office_hours == NGX_CONF_UNSET_PTR) {
        *office_hours = ngx_array_create(cf->pool, cf->args->nelts - 1,
                                         sizeof(ngx_str_t));

        if (*office_hours == NULL) {
            return NGX_CONF_ERROR;
        }
    }
    value = cf->args->elts;

    for (i = 1; i < cf->args->nelts; ++i) {
        hours = ngx_array_push(*office_hours);
        if (hours == NULL) {
            return NGX_CONF_ERROR;
        }
        *hours = value[i];
    }

    return NGX_CONF_OK;
}


/*
 * Config Creator
 * Initializes the configuration structure
 */

static void *ngx_http_office_hours_create_conf(ngx_conf_t * cf)
{

    ngx_http_office_hours_conf_t *conf;

    conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_office_hours_conf_t));

    if (conf == NULL) {
        return NULL;
    }
    conf->office_hours = NGX_CONF_UNSET_PTR;

    return conf;
}

/*
 * Merge Config Values
 * Sets the defaults for the configuration and merges
 * with other configurations
 */

static char *ngx_http_office_hours_merge_conf(ngx_conf_t * cf,
        void *parent, void *child)
{

    ngx_http_office_hours_conf_t *prev = parent;
    ngx_http_office_hours_conf_t *conf = child;

    ngx_conf_merge_ptr_value(conf->office_hours, prev->office_hours, NULL);

    return NGX_CONF_OK;
}

/*
 * Parse the office hour strings in the configuration file
 * to fill out the hours array (in seconds)
 */

static ngx_uint_t ** parse_office_hours(ngx_array_t * office_hours)
{

    ngx_str_t *hours;
    ngx_uint_t ** parsed_office_hours;
    ngx_uint_t i, j;

    parsed_office_hours = malloc(7 * sizeof(ngx_uint_t *));

    hours = office_hours->elts;

    /*
     * On the configuration file, the leftmost element
     * always applies to all remaining days, all others
     * are read from right to left. So first we will apply
     * the initial override, and then iterate based on the
     * number of overrides
     */

    for (i = 0; i < WEEK_LENGTH + 1 - office_hours->nelts; ++i) {
        parsed_office_hours[i] = parse_office_hours_string(hours[0]);
    }

    for (i = 1; i < office_hours->nelts; ++i) {
        j = WEEK_LENGTH - office_hours->nelts + i;
        parsed_office_hours[j] = parse_office_hours_string(hours[i]);
    }

    return parsed_office_hours;
}

/*
 * Given a time string or the closed token, return a tuple
 * of numbers representing opening and closing hours
 */

static ngx_uint_t * parse_office_hours_string(ngx_str_t office_hours)
{

    int captures[(1 + 4) * 3];
    ngx_int_t n;
    ngx_uint_t * parsed_hours;

    parsed_hours = malloc(2 * sizeof(ngx_uint_t));

    if(ngx_strcmp(office_hours.data, CLOSED_TOKEN) == 0) {
        parsed_hours[0] = 0;
        parsed_hours[1] = 0;
        return parsed_hours;
    }

    n = ngx_regex_exec(rc.regex, &office_hours, captures, (1 + 4) * 3);

    if (n >= 0) {
        /* Opening Hours */

        parsed_hours[0] = 60 * 60 * parse_number(office_hours, captures[2], captures[3]);
        parsed_hours[0] = parsed_hours[0] + 60 * parse_number(office_hours, captures[4], captures[5]);

        parsed_hours[1] = 60 * 60 * parse_number(office_hours, captures[6], captures[7]);
        parsed_hours[1] = parsed_hours[1] + 60 * parse_number(office_hours, captures[8], captures[9]);

        return parsed_hours;
    }

    /* Non-matching strings count as open */

    parsed_hours[0] = 0;
    parsed_hours[1] = 86400;
    return parsed_hours;
}

/*
 * Given an office hours array, it returns whether or not
 * it is currently within office hours.
 */

static ngx_flag_t within_office_hours(ngx_uint_t ** office_hours)
{

    time_t now;
    ngx_uint_t day_of_week, seconds_of_day;
    ngx_uint_t * current_hours;

    ngx_time_update();
    now = ngx_time();
    day_of_week = get_day_of_week(now);
    seconds_of_day = get_seconds_of_day(now);
    current_hours = office_hours[day_of_week];

    return seconds_of_day >= current_hours[0] && seconds_of_day <= current_hours[1];
}

/*
 * Calculate the day of the week given a timestamp
 */

static ngx_uint_t get_day_of_week(time_t time)
{

    /* Epoch was thursday, so add 3 so we start on monday */
    return (time / 86400 + 3) % 7;
}

/*
 * Calculate the number of seconds elapsed today
 */

static ngx_uint_t get_seconds_of_day(time_t time)
{

    return time - (time / 86400) * 86400;
}

/*
 * Parses a string, returns 0 if match was not found
 */

static ngx_uint_t parse_number(ngx_str_t string, ngx_uint_t start, ngx_uint_t end)
{

    if (end - start == 0) {
        return 0;
    }

    return ngx_atoi(&string.data[start], end - start);
}

/*
 * Given the current office hours configuration it creates the custom
 * HTML
 */

static ngx_str_t create_output_html(ngx_http_office_hours_conf_t * conf)
{

    char * output_buffer;
    time_t now;
    ngx_str_t output_html;
    ngx_uint_t i, seconds_of_day;
    ngx_uint_t ** parsed_office_hours;


    output_buffer = malloc(1024 * sizeof(char));
    parsed_office_hours = parse_office_hours(conf->office_hours);
    now = ngx_time();
    seconds_of_day = get_seconds_of_day(now);

    sprintf(output_buffer, "%s", (char *) HEAD_HTML.data);

    for (i = 0; i < 7; ++i) {
        sprintf(output_buffer + strlen(output_buffer), "%s", format_hours(parsed_office_hours[i], (char *) DAY_NAMES[i]));
    }

    sprintf(output_buffer + strlen(output_buffer), "%s", (char *) MIDDLE_HTML.data);
    sprintf(output_buffer + strlen(output_buffer), "%s", format_seconds(seconds_of_day));
    sprintf(output_buffer + strlen(output_buffer), "%s", (char *) FOOT_HTML.data);

    output_html.data = (unsigned char *) output_buffer;
    output_html.len = strlen(output_buffer);

    return output_html;
}

/*
 * Given a tuple of seconds and a day name, outputs an HTML
 * string containing the formatted data as a list item
 */

static char * format_hours(ngx_uint_t * hours, char * day)
{

    char * output_html;

    output_html = malloc(64 * sizeof(char));
    if (hours[0] == hours[1]) {
        sprintf(output_html, "<li><strong>%s</strong>: CLOSED</li>",
                day
               );
        return output_html;
    }

    sprintf(output_html, "<li><strong>%s</strong>: %s - %s</li>",
            day,
            (char *) format_seconds(hours[0]),
            (char *) format_seconds(hours[1])
           );

    return output_html;
}

/*
 * Given seconds of the day, it returns a string showing
 * HH:MM in 24 hour format
 */

static char * format_seconds(ngx_uint_t seconds)
{

    char * output_html;
    unsigned int hours, minutes;

    output_html = malloc(6 * sizeof(char));

    hours = seconds / 60 / 60;
    minutes = (seconds / 60) % 60;

    sprintf(output_html, "%s:%s",
            left_pad(hours),
            left_pad(minutes)
           );

    return output_html;
}

/*
 * Returns a number as a string adding 0 if < 10
 */

static char * left_pad(unsigned int number)
{

    char * output_string;
    char * padding;

    padding = "";
    output_string = malloc(3 * sizeof(char));

    if (number < 10) {
        padding = "0";
    }

    sprintf(output_string, "%s%u", padding, number);

    return output_string;
}

/*
 * Postconfig Initialization Handler
 * Sets the request filter at the top of the chain
 */

static ngx_int_t ngx_http_office_hours_init(ngx_conf_t * cf)
{

    ngx_http_next_header_filter = ngx_http_top_header_filter;
    ngx_http_top_header_filter = ngx_http_office_hours_header_filter;

    ngx_http_next_body_filter = ngx_http_top_body_filter;
    ngx_http_top_body_filter = ngx_http_office_hours_body_filter;

    rc.pattern = TIME_REGEX;
    rc.pool = cf->pool;
    if (ngx_regex_compile(&rc) != NGX_OK) {
        return NGX_ERROR;
    }

    return NGX_OK;
}

A scripts/git-hooks/pre-commit => scripts/git-hooks/pre-commit +10 -0
@@ 0,0 1,10 @@
#!/usr/bin/env sh

SOURCES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E "\.c$")

set -e
make format

for SOURCE in ${SOURCES}; do
    git add ${SOURCE}
done