Line data Source code
1 : /* conversion.c - String conversion helper functions.
2 : Copyright (C) 2000 Werner Koch (dd9jn)
3 : Copyright (C) 2001, 2002, 2003, 2004, 2007, 2009 g10 Code GmbH
4 :
5 : This file is part of Assuan.
6 :
7 : Assuan is free software; you can redistribute it and/or modify it
8 : under the terms of the GNU Lesser General Public License as
9 : published by the Free Software Foundation; either version 2.1 of
10 : the License, or (at your option) any later version.
11 :
12 : Assuan is distributed in the hope that it will be useful, but
13 : WITHOUT ANY WARRANTY; without even the implied warranty of
14 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 : Lesser General Public License for more details.
16 :
17 : You should have received a copy of the GNU Lesser General Public
18 : License along with this program; if not, write to the Free Software
19 : Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 : 02111-1307, USA. */
21 :
22 : #if HAVE_CONFIG_H
23 : #include <config.h>
24 : #endif
25 :
26 : #include <stdlib.h>
27 : #include <string.h>
28 : #include <errno.h>
29 : #include <ctype.h>
30 :
31 : #include "assuan-defs.h"
32 : #include "debug.h"
33 :
34 :
35 : /* Convert the number NR to a hexadecimal string. Returns the tail
36 : pointer. */
37 : static char *
38 0 : _assuan_bytetohex (int nr, char *str)
39 : {
40 : static char hexdigits[] = "0123456789abcdef";
41 : int i;
42 :
43 : #define NROFHEXDIGITS 2
44 0 : for (i = 0; i < NROFHEXDIGITS; i++)
45 : {
46 0 : int digit = (nr >> (i << 2)) & 0xf;
47 0 : *(str++) = hexdigits[digit];
48 : }
49 0 : return str;
50 : }
51 :
52 :
53 : /* Encode the C formatted string SRC and return the malloc'ed result. */
54 : char *
55 0 : _assuan_encode_c_string (assuan_context_t ctx, const char *src)
56 : {
57 : const unsigned char *istr;
58 : char *res;
59 : char *ostr;
60 :
61 0 : ostr = _assuan_malloc (ctx, 4 * strlen (src) + 1);
62 0 : if (! *ostr)
63 0 : return NULL;
64 :
65 0 : res = ostr;
66 :
67 0 : for (istr = (const unsigned char *) src; *istr; istr++)
68 : {
69 0 : int c = 0;
70 :
71 0 : switch (*istr)
72 : {
73 : case '\r':
74 0 : c = 'r';
75 0 : break;
76 :
77 : case '\n':
78 0 : c = 'n';
79 0 : break;
80 :
81 : case '\f':
82 0 : c = 'f';
83 0 : break;
84 :
85 : case '\v':
86 0 : c = 'v';
87 0 : break;
88 :
89 : case '\b':
90 0 : c = 'b';
91 0 : break;
92 :
93 : default:
94 0 : if ((isascii (*istr) && isprint (*istr)) || (*istr >= 0x80))
95 0 : *(ostr++) = *istr;
96 : else
97 : {
98 0 : *(ostr++) = '\\';
99 0 : *(ostr++) = 'x';
100 0 : ostr = _assuan_bytetohex (*istr, ostr);
101 : }
102 : }
103 :
104 0 : if (c)
105 : {
106 0 : *(ostr++) = '\\';
107 0 : *(ostr++) = c;
108 : }
109 : }
110 0 : *(ostr) = '\0';
111 :
112 0 : return res;
113 : }
|