bug in "search_headers_in"

shanlei nginx-forum at forum.nginx.org
Fri Apr 15 04:29:28 UTC 2022


Inside nginx blog: "Managing request headers" , there is a method:
search_headers_in which can search for arbitrary headers, however this
method use ngx_strcasecmp( "ngx_strcasecmp(u_char *s1, u_char *s2)") which
assume the input s1 must be '\0' terminated. 

so inside the code below, this function may get wrong result , beause name
is not '\0\ terminated.
" 
if (len != h[i].key.len || ngx_strcasecmp(name, h[i].key.data) != 0) {
            /* This header doesn't match. */
            continue;
        }
"

the right way use "search_headers_in" is:

ngx_strsearch_header2;
ngx_str_t search_header=ngx_string("to_be_searched");
search_header2.data=ngx_pnlloc(search_header.len+1);
search_header2.len=search_header.len;

search_headers_in(r, search_header2.data, search_header2.len);



========================== 
static ngx_table_elt_t *
search_headers_in(ngx_http_request_t *r, u_char *name, size_t len) {
    ngx_list_part_t            *part;
    ngx_table_elt_t            *h;
    ngx_uint_t                  i;

    /*
    Get the first part of the list. There is usual only one part.
    */
    part = &r->headers_in.headers.part;
    h = part->elts;

    /*
    Headers list array may consist of more than one part,
    so loop through all of it
    */
    for (i = 0; /* void */ ; i++) {
        if (i >= part->nelts) {
            if (part->next == NULL) {
                /* The last part, search is done. */
                break;
            }

            part = part->next;
            h = part->elts;
            i = 0;
        }

        /*
        Just compare the lengths and then the names case insensitively.
        */
        if (len != h[i].key.len || ngx_strcasecmp(name, h[i].key.data) != 0)
{
            /* This header doesn't match. */
            continue;
        }

        /*
        Ta-da, we got one!
        Note, we'v stop the search at the first matched header
        while more then one header may fit.
        */
        return &h[i];
    }

    /*
    No headers was found
    */
    return NULL;
}
=============================

Posted at Nginx Forum: https://forum.nginx.org/read.php?2,293970,293970#msg-293970



More information about the nginx mailing list