1/* server.c --- DIGEST-MD5 mechanism from RFC 2831, server side.
2 * Copyright (C) 2002-2012 Simon Josefsson
3 *
4 * This file is part of GNU SASL Library.
5 *
6 * GNU SASL Library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public License
8 * as published by the Free Software Foundation; either version 2.1 of
9 * the License, or (at your option) any later version.
10 *
11 * GNU SASL Library 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.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with GNU SASL Library; if not, write to the Free
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
20 *
21 */
22
23#ifdef HAVE_CONFIG_H
24#include "config.h"
25#endif
26
27/* Get specification. */
28#include "nonascii.h"
29
30#include <stdlib.h>
31#include <string.h>
32
33/* C89 compliant way to cast 'char' to 'unsigned char'. */
34static inline unsigned char
35to_uchar (char ch)
36{
37 return ch;
38}
39
40char *
41latin1toutf8 (const char *str)
42{
43 char *p = malloc (2 * strlen (str) + 1);
44 if (p)
45 {
46 size_t i, j = 0;
47 for (i = 0; str[i]; i++)
48 {
49 if (to_uchar (str[i]) < 0x80)
50 p[j++] = str[i];
51 else if (to_uchar (str[i]) < 0xC0)
52 {
53 p[j++] = (unsigned char) 0xC2;
54 p[j++] = str[i];
55 }
56 else
57 {
58 p[j++] = (unsigned char) 0xC3;
59 p[j++] = str[i] - 64;
60 }
61 }
62 p[j] = 0x00;
63 }
64
65 return p;
66}
67
68char *
69utf8tolatin1ifpossible (const char *passwd)
70{
71 char *p;
72 size_t i;
73
74 for (i = 0; passwd[i]; i++)
75 {
76 if (to_uchar (passwd[i]) > 0x7F)
77 {
78 if (to_uchar (passwd[i]) < 0xC0 || to_uchar (passwd[i]) > 0xC3)
79 return strdup (passwd);
80 i++;
81 if (to_uchar (passwd[i]) < 0x80 || to_uchar (passwd[i]) > 0xBF)
82 return strdup (passwd);
83 }
84 }
85
86 p = malloc (strlen (passwd) + 1);
87 if (p)
88 {
89 size_t j = 0;
90 for (i = 0; passwd[i]; i++)
91 {
92 if (to_uchar (passwd[i]) > 0x7F)
93 {
94 /* p[i+1] can't be zero here */
95 p[j++] =
96 ((to_uchar (passwd[i]) & 0x3) << 6)
97 | (to_uchar (passwd[i + 1]) & 0x3F);
98 i++;
99 }
100 else
101 p[j++] = passwd[i];
102 }
103 p[j] = 0x00;
104 }
105 return p;
106}
107