An AC_LIBOBJ, from gnulib.
[gsasl.git] / lib / md5pwd.c
blob72116dcd6468b9006f63272a074f57cd91e14aae
1 /* md5pwd.c find passwords in UoW imapd MD5 type password files
2 * Copyright (C) 2002 Simon Josefsson
4 * This file is part of libgsasl.
6 * Libgsasl is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * Libgsasl is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with libgsasl; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "internal.h"
24 /**
25 * gsasl_md5pwd_get_password:
26 * @filename: filename of file containing passwords.
27 * @username: username string.
28 * @key: output character array.
29 * @keylen: input maximum size of output character array, on output
30 * contains actual length of output array.
32 * Retrieve password for user from specified file. To find out how
33 * large the output array must be, call this function with out=NULL.
35 * The file should be on the UoW "MD5 Based Authentication" format,
36 * which means it is in text format with comments denoted by # first
37 * on the line, with user entries looking as username\tpassword. This
38 * function removes \r and \n at the end of lines before processing.
40 * Return value: Return GSASL_OK if output buffer contains the
41 * password, GSASL_AUTHENTICATION_ERROR if the user could not be
42 * found, or other error code.
43 **/
44 int
45 gsasl_md5pwd_get_password (const char *filename,
46 const char *username, char *key, size_t * keylen)
48 char matchbuf[BUFSIZ];
49 char line[BUFSIZ];
50 FILE *fh;
52 fh = fopen (filename, "r");
53 if (fh == NULL)
54 return GSASL_FOPEN_ERROR;
56 sprintf (matchbuf, "%s\t", username);
58 while (!feof (fh))
60 if (fgets (line, BUFSIZ, fh) == NULL)
61 break;
63 if (line[0] == '#')
64 continue;
66 while (strlen (line) > 0 && (line[strlen (line) - 1] == '\n' ||
67 line[strlen (line) - 1] == '\r'))
68 line[strlen (line) - 1] = '\0';
70 if (strlen (line) <= strlen (matchbuf))
71 continue;
73 if (strncmp (matchbuf, line, strlen (matchbuf)) == 0)
75 if (*keylen < strlen (line) - strlen (matchbuf))
77 fclose (fh);
78 return GSASL_TOO_SMALL_BUFFER;
81 *keylen = strlen (line) - strlen (matchbuf);
83 if (key)
84 memcpy (key, &line[strlen (matchbuf)], *keylen);
86 fclose (fh);
88 return GSASL_OK;
92 if (fclose (fh) != 0)
93 return GSASL_FCLOSE_ERROR;
95 return GSASL_AUTHENTICATION_ERROR;