File: nonascii.c

package info (click to toggle)
gsasl 2.2.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 3,600 kB
  • sloc: ansic: 16,551; sh: 1,739; makefile: 676; xml: 301; php: 172; perl: 4
file content (103 lines) | stat: -rw-r--r-- 2,281 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* server.c --- DIGEST-MD5 mechanism from RFC 2831, server side.
 * Copyright (C) 2002-2025 Simon Josefsson
 *
 * This file is part of GNU SASL Library.
 *
 * GNU SASL Library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * GNU SASL Library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with GNU SASL Library; if not, see
 * <https://www.gnu.org/licenses/>.
 *
 */

#include <config.h>

/* Get specification. */
#include "nonascii.h"

#include <stdlib.h>
#include <string.h>

/* C89 compliant way to cast 'char' to 'unsigned char'. */
static inline unsigned char
to_uchar (char ch)
{
  return ch;
}

char *
latin1toutf8 (const char *str)
{
  char *p = malloc (2 * strlen (str) + 1);
  if (p)
    {
      size_t i, j = 0;
      for (i = 0; str[i]; i++)
	{
	  if (to_uchar (str[i]) < 0x80)
	    p[j++] = str[i];
	  else if (to_uchar (str[i]) < 0xC0)
	    {
	      p[j++] = (unsigned char) 0xC2;
	      p[j++] = str[i];
	    }
	  else
	    {
	      p[j++] = (unsigned char) 0xC3;
	      p[j++] = str[i] - 64;
	    }
	}
      p[j] = 0x00;
    }

  return p;
}

char *
utf8tolatin1ifpossible (const char *passwd)
{
  char *p;
  size_t i;

  for (i = 0; passwd[i]; i++)
    {
      if (to_uchar (passwd[i]) > 0x7F)
	{
	  if (to_uchar (passwd[i]) < 0xC0 || to_uchar (passwd[i]) > 0xC3)
	    return strdup (passwd);
	  i++;
	  if (to_uchar (passwd[i]) < 0x80 || to_uchar (passwd[i]) > 0xBF)
	    return strdup (passwd);
	}
    }

  p = malloc (strlen (passwd) + 1);
  if (p)
    {
      size_t j = 0;
      for (i = 0; passwd[i]; i++)
	{
	  if (to_uchar (passwd[i]) > 0x7F)
	    {
	      /* p[i+1] can't be zero here */
	      p[j++] =
		((to_uchar (passwd[i]) & 0x3) << 6)
		| (to_uchar (passwd[i + 1]) & 0x3F);
	      i++;
	    }
	  else
	    p[j++] = passwd[i];
	}
      p[j] = 0x00;
    }
  return p;
}