gsasl  2.2.1
nonascii.c
Go to the documentation of this file.
1 /* server.c --- DIGEST-MD5 mechanism from RFC 2831, server side.
2  * Copyright (C) 2002-2024 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 #include <config.h>
24 
25 /* Get specification. */
26 #include "nonascii.h"
27 
28 #include <stdlib.h>
29 #include <string.h>
30 
31 /* C89 compliant way to cast 'char' to 'unsigned char'. */
32 static inline unsigned char
33 to_uchar (char ch)
34 {
35  return ch;
36 }
37 
38 char *
39 latin1toutf8 (const char *str)
40 {
41  char *p = malloc (2 * strlen (str) + 1);
42  if (p)
43  {
44  size_t i, j = 0;
45  for (i = 0; str[i]; i++)
46  {
47  if (to_uchar (str[i]) < 0x80)
48  p[j++] = str[i];
49  else if (to_uchar (str[i]) < 0xC0)
50  {
51  p[j++] = (unsigned char) 0xC2;
52  p[j++] = str[i];
53  }
54  else
55  {
56  p[j++] = (unsigned char) 0xC3;
57  p[j++] = str[i] - 64;
58  }
59  }
60  p[j] = 0x00;
61  }
62 
63  return p;
64 }
65 
66 char *
67 utf8tolatin1ifpossible (const char *passwd)
68 {
69  char *p;
70  size_t i;
71 
72  for (i = 0; passwd[i]; i++)
73  {
74  if (to_uchar (passwd[i]) > 0x7F)
75  {
76  if (to_uchar (passwd[i]) < 0xC0 || to_uchar (passwd[i]) > 0xC3)
77  return strdup (passwd);
78  i++;
79  if (to_uchar (passwd[i]) < 0x80 || to_uchar (passwd[i]) > 0xBF)
80  return strdup (passwd);
81  }
82  }
83 
84  p = malloc (strlen (passwd) + 1);
85  if (p)
86  {
87  size_t j = 0;
88  for (i = 0; passwd[i]; i++)
89  {
90  if (to_uchar (passwd[i]) > 0x7F)
91  {
92  /* p[i+1] can't be zero here */
93  p[j++] =
94  ((to_uchar (passwd[i]) & 0x3) << 6)
95  | (to_uchar (passwd[i + 1]) & 0x3F);
96  i++;
97  }
98  else
99  p[j++] = passwd[i];
100  }
101  p[j] = 0x00;
102  }
103  return p;
104 }
char * latin1toutf8(const char *str)
Definition: nonascii.c:39
char * utf8tolatin1ifpossible(const char *passwd)
Definition: nonascii.c:67