Как заставить модуль nginx выполняться только для блока местоположения, в котором он указан? - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь создать модуль nginx на этапе доступа для чтения http-запросов, которые сопоставлены с данным блоком местоположения, и выгрузки информации URI запроса на локальный порт UDP.

#include <ngx_core.h>
#include <ngx_http.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define PORT 8888
#define LOCALHOST "127.0.0.1"

/* Location Configuration */
typedef struct {
    ngx_str_t name;
} ngx_dash_access_loc_conf_t;

/* core functionalities */
static ngx_int_t ngx_dash_access_handler(ngx_http_request_t *r);
static void *ngx_dash_access_create_loc_conf(ngx_conf_t *cf);
static char *ngx_dash_access_merge_loc_conf(ngx_conf_t *cf, void *parent,
            void *child);
static ngx_int_t ngx_dash_access_init(ngx_conf_t *cf);

/* static file descriptor for udp socket*/
static struct sockaddr_in c_addr;
static ngx_int_t dash_req_fd;

/* commands */
static ngx_command_t ngx_dash_access_commands[] = {

    { ngx_string("dash_access"),
      NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_dash_access_loc_conf_t, name),
      NULL },
    ngx_null_command
};

/* module context */
static ngx_http_module_t ngx_dash_access_module_ctx = {
    NULL,                           /* preconfiguration */
    ngx_dash_access_init,           /* postconfiguration */

    NULL,                           /* create main configuration */
    NULL,                           /* init main configuration */

    NULL,                           /* create server configuration */
    NULL,                           /* merge server configuration */

    ngx_dash_access_create_loc_conf,/* create location configuration */
    ngx_dash_access_merge_loc_conf  /* merge location configuration */

};

/* module definition */
ngx_module_t ngx_dash_access_module = {
    NGX_MODULE_V1,
    &ngx_dash_access_module_ctx,
    ngx_dash_access_commands,
    NGX_HTTP_MODULE,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NGX_MODULE_V1_PADDING
};

/* create loc config */
static void*
ngx_dash_access_create_loc_conf(ngx_conf_t *cf)
{
    ngx_dash_access_loc_conf_t *conf;
    conf = ngx_palloc(cf->pool,
                    sizeof(ngx_dash_access_loc_conf_t));
    if (conf == NULL) {
            return NULL;
    }

    return conf;
}

/* merge the location config */
static char*
ngx_dash_access_merge_loc_conf(ngx_conf_t *cf, void *parent,
            void *child)
{
    ngx_dash_access_loc_conf_t *prev = parent;
    ngx_dash_access_loc_conf_t *conf = child;

    ngx_conf_merge_str_value(conf->name, prev->name, "");

    return NGX_CONF_OK;
}


/* initial config, add the handler to the access phase queue*/
static ngx_int_t
ngx_dash_access_init(ngx_conf_t *cf)
{
    ngx_http_handler_pt *h;
    ngx_http_core_main_conf_t *cmcf;

    cmcf = ngx_http_conf_get_module_main_conf(cf,
                    ngx_http_core_module);

    h = ngx_array_push(&cmcf->phases[NGX_HTTP_ACCESS_PHASE].handlers);
    if (h == NULL) {
            return NGX_ERROR;
    }

    *h = ngx_dash_access_handler;

    /* create socket file descriptor */
    if ((dash_req_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
            return NGX_ERROR;
    }

    memset(&c_addr, 0, sizeof(c_addr));
    c_addr.sin_family = AF_INET;
    c_addr.sin_port = htons(PORT);

    if(inet_aton(LOCALHOST, &c_addr.sin_addr) == 0){
            return NGX_ERROR;
    }

    return NGX_OK;
}

/* Here is the actual module definition */
static ngx_int_t
ngx_dash_access_handler(ngx_http_request_t *r)
{
    char content_buf[200];
    ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
                    "dash_access_handler");

    /* log the request uri, the byte range request */
    /* to be used in accordance with vod requests only */
    if (r->uri.len != 0) {
            sendto(dash_req_fd, r->uri.data, r->uri.len, 0, (struct sockaddr *)&c_addr, sizeof(struct sockaddr_in));
    }

    if (r->headers_in.range != NULL){
            sprintf(content_buf, "key:%s val:%s", r->headers_in.range->key.data,
                           r->headers_in.range->value.data);
            sendto(dash_req_fd, content_buf, strlen(content_buf),
                            0, (struct sockaddr *)&c_addr,
                            sizeof(struct sockaddr_in));
    }
    else {
            sprintf(content_buf, "%s", "Content-Range unavailable");
            sendto(dash_req_fd, content_buf, strlen(content_buf), 0,
                            (struct sockaddr *)&c_addr,
                            sizeof(struct sockaddr_in));
    }

    return NGX_DECLINED;
}

КонфигурацияЯ использую:

#user  nobody;
worker_processes  1;

error_log  logs/error.log;
error_log  logs/error.log  debug;
error_log  logs/error.log error;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;

    keepalive_timeout  65;


    server {
        listen       80;
        server_name  localhost;
        root /etc/nginx/html/dash/;

        gzip on;
        gzip_types application/vnd.apple.mpegurl application/dash+xml mpd;

        #vod settings
        vod_mode local;
        vod_last_modified 'Sun, 15 Sep 2019 12:00:00 GMT';
        vod_last_modified_types *;
        vod_align_segments_to_key_frames on;
        vod_manifest_duration_policy min;

        #file handle caching / aio
        open_file_cache          max=1000 inactive=5m;
        open_file_cache_valid    2m;
        open_file_cache_min_uses 1;
        open_file_cache_errors   on;
        aio on;

        location /content/$ {
            root /etc/nginx/html/dash/;
            dash_access foo;
            vod dash;
            add_header Access-Control-Allow-Headers '*';
            add_header Access-Control-Expose-Headers 'Server,range,Content-Length,Content-Range';
            add_header Access-Control-Allow-Methods 'GET, HEAD, OPTIONS';
            add_header Access-Control-Allow-Origin '*';
            expires 100d;
        }


        location /dist/ {
            root /etc/nginx/html/dash/shaka-player/;
        }

        location /javascript/ {
            root /etc/nginx/html/dash/;
        }

        location / {
            root /etc/nginx/html/dash/;
            index pages/main.html;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }
}

Я хочу, чтобы мой модуль выполнялся только для запросов http в блоке местоположения, в котором он определен, в моем случае в блоке location /content/$. Но я обнаружил, что информация, сбрасываемая на порт UDP, также содержит Uris, которые обычно соответствуют другим блокам местоположения. Что я делаю неправильно? Извините за мои ограниченные знания с nginx, потому что я все еще новичок в этом.

...