[En-Nut-Discussion] HTTP password protection - better solution

Edwin van den Oetelaar edwin at oetelaar.com
Tue Aug 29 16:13:27 CEST 2006


Peter Sodermanns wrote:

> Hi all,
>
> as Edwin pointed out, my first routine was buggy because of access to 
> already freed objects.
>
> Now - after several tests - I come up with a hopefully better solution.
>
>
> In httpd.h I changed the declaration of AUTHINFO into fixed size in 
> order to free allocated memory in NutClearAuth(). A directory name can 
> have up to 255 characters, for username and password I provided 20 
> char, each.
>
> struct _AUTHINFO {
>     AUTHINFO *auth_next;        /*!< \brief Link to next AUTHINFO 
> structure */
>     char auth_dirname[256];   /*!< \brief Pathname of protected 
> directory */
>     char auth_login[42];     /*!< \brief Login user and password, 
> separated by a colon. 20 characters each. */
> };
>
Question ? Why do you allocate full size when you might just need very 
small number of memory?
We are talking embedded here !
Each entry now consumes about 300 bytes. This could be dynamicly 
allocated and free'd.

> int NutClearAuth(void)
> {
>     AUTHINFO *idx;
>     u_char n, m, count;
>
>     /*
>      * any entries at all?
>      */
>     if (authList) {
>         count = 0;
>         idx = authList;
>         /*
>          * count entries
>          */
>         while (idx) {
>             count++;
>             idx = idx->auth_next;
>         }
>         /*
>          * delete counted number of entries
>          */
>         for (n=count; n>0;n--) {
>             idx = authList;
>             /*
>              * walk to end of list
>              */
>             for (m=1; m<n;m++) {
>                 idx = idx->auth_next;
>             }
>             /*
>              * free last item
>              */
>             NutHeapFree(idx);
>             idx = 0;
>         }
>         /*
>          * indicate empty list
>          */
>         authList = 0;
>     }
>
>     return 0;
> }
>
Like Ulrich showed this can be more compact.

I would strongly recommend using Alloc and Free functions instead of 
static size array allocation.
So it would be something like this :

AUTHINFO *auth = authList;
while (auth) {
    AUTHINFO * next = auth->next;
    NutHeapFree(auth_dirname);
    NutHeapFree(auth_login);
    NutHeapFree(auth);
    auth = next;
}



Just my opinion. Not intended to make you feel bad.

Good luck,
Edwin van den Oetelaar




More information about the En-Nut-Discussion mailing list