GNU libmicrohttpd  0.9.5
basicauth.c
Go to the documentation of this file.
1 /*
2  This file is part of libmicrohttpd
3  (C) 2010, 2011, 2012 Daniel Pittman and Christian Grothoff
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Lesser General Public
7  License as published by the Free Software Foundation; either
8  version 2.1 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
25 #include "platform.h"
26 #include <limits.h>
27 #include "internal.h"
28 #include "base64.h"
29 
33 #define _BASIC_BASE "Basic "
34 
35 
44 char *
46  char** password)
47 {
48  const char *header;
49  char *decode;
50  const char *separator;
51  char *user;
52 
53  if ( (NULL == (header = MHD_lookup_connection_value (connection,
56  (0 != strncmp (header, _BASIC_BASE, strlen(_BASIC_BASE))) )
57  return NULL;
58  header += strlen (_BASIC_BASE);
59  if (NULL == (decode = BASE64Decode (header)))
60  {
61 #if HAVE_MESSAGES
62  MHD_DLOG (connection->daemon,
63  "Error decoding basic authentication\n");
64 #endif
65  return NULL;
66  }
67  /* Find user:password pattern */
68  if (NULL == (separator = strchr (decode, ':')))
69  {
70 #if HAVE_MESSAGES
71  MHD_DLOG(connection->daemon,
72  "Basic authentication doesn't contain ':' separator\n");
73 #endif
74  free (decode);
75  return NULL;
76  }
77  if (NULL == (user = strdup (decode)))
78  {
79  free (decode);
80  return NULL;
81  }
82  user[separator - decode] = '\0'; /* cut off at ':' */
83  if (NULL != password)
84  {
85  *password = strdup (separator + 1);
86  if (NULL == *password)
87  {
88 #if HAVE_MESSAGES
89  MHD_DLOG(connection->daemon,
90  "Failed to allocate memory for password\n");
91 #endif
92  free (decode);
93  free (user);
94  return NULL;
95  }
96  }
97  free (decode);
98  return user;
99 }
100 
101 
109 int
111  const char *realm,
112  struct MHD_Response *response)
113 {
114  int ret;
115  size_t hlen = strlen(realm) + strlen("Basic realm=\"\"") + 1;
116  char header[hlen];
117 
118  snprintf (header,
119  sizeof (header),
120  "Basic realm=\"%s\"",
121  realm);
122  ret = MHD_add_response_header (response,
124  header);
125  if (MHD_YES == ret)
126  ret = MHD_queue_response (connection,
128  response);
129  return ret;
130 }
131 
132 /* end of basicauth.c */