da7263f7120e0daab393d56d9a88a69f4ef3fb8b
[project/uhttpd.git] / auth.c
1 /*
2  * uhttpd - Tiny single-threaded httpd
3  *
4  *   Copyright (C) 2010-2012 Jo-Philipp Wich <xm@subsignal.org>
5  *   Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org>
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS,
15  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19
20 #include "uhttpd.h"
21
22 static LIST_HEAD(auth_realms);
23
24 void uh_auth_add(const char *path, const char *user, const char *pass)
25 {
26         struct auth_realm *new = NULL;
27         struct passwd *pwd;
28         const char *new_pass = NULL;
29
30 #ifdef HAVE_SHADOW
31         struct spwd *spwd;
32 #endif
33
34         /* given password refers to a passwd entry */
35         if ((strlen(pass) > 3) && !strncmp(pass, "$p$", 3)) {
36 #ifdef HAVE_SHADOW
37                 /* try to resolve shadow entry */
38                 spwd = getspnam(&pass[3]);
39                 if (spwd)
40                         new_pass = spwd->sp_pwdp;
41 #endif
42                 if (!new_pass) {
43                         pwd = getpwnam(&pass[3]);
44                         if (pwd && pwd->pw_passwd && pwd->pw_passwd[0] &&
45                             pwd->pw_passwd[0] != '!')
46                                 new_pass = pwd->pw_passwd;
47                 }
48         } else {
49                 new_pass = pass;
50         }
51
52         if (!new_pass || !new_pass[0])
53                 return;
54
55         new = calloc(1, sizeof(*new));
56         if (!new)
57                 return;
58
59         snprintf(new->path, sizeof(new->path), "%s", path);
60         snprintf(new->user, sizeof(new->user), "%s", user);
61         snprintf(new->pass, sizeof(new->user), "%s", new_pass);
62         list_add(&new->list, &auth_realms);
63 }