xref: /netbsd-src/external/ibm-public/postfix/dist/src/util/printable.c (revision 796c32c94f6e154afc9de0f63da35c91bb739b45)
1 /*	$NetBSD: printable.c,v 1.2 2017/02/14 01:16:49 christos Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	printable 3
6 /* SUMMARY
7 /*	mask non-printable characters
8 /* SYNOPSIS
9 /*	#include <stringops.h>
10 /*
11 /*	int	util_utf8_enable;
12 /*
13 /*	char	*printable(buffer, replacement)
14 /*	char	*buffer;
15 /*	int	replacement;
16 /* DESCRIPTION
17 /*	printable() replaces non-printable characters
18 /*	in its input with the given replacement.
19 /*
20 /*	util_utf8_enable controls whether UTF8 is considered printable.
21 /*	With util_utf8_enable equal to zero, non-ASCII text is replaced.
22 /*
23 /*	Arguments:
24 /* .IP buffer
25 /*	The null-terminated input string.
26 /* .IP replacement
27 /*	Replacement value for characters in \fIbuffer\fR that do not
28 /*	pass the ASCII isprint(3) test or that are not valid UTF8.
29 /* LICENSE
30 /* .ad
31 /* .fi
32 /*	The Secure Mailer license must be distributed with this software.
33 /* AUTHOR(S)
34 /*	Wietse Venema
35 /*	IBM T.J. Watson Research
36 /*	P.O. Box 704
37 /*	Yorktown Heights, NY 10598, USA
38 /*--*/
39 
40 /* System library. */
41 
42 #include "sys_defs.h"
43 #include <ctype.h>
44 
45 /* Utility library. */
46 
47 #include "stringops.h"
48 
49 int util_utf8_enable = 0;
50 
51 char   *printable(char *string, int replacement)
52 {
53     unsigned char *cp;
54     int     ch;
55 
56     /*
57      * XXX Replace invalid UTF8 sequences (too short, over-long encodings,
58      * out-of-range code points, etc). See valid_utf8_string.c.
59      */
60     cp = (unsigned char *) string;
61     while ((ch = *cp) != 0) {
62 	if (ISASCII(ch) && ISPRINT(ch)) {
63 	    /* ok */
64 	} else if (util_utf8_enable && ch >= 194 && ch <= 254
65 		   && cp[1] >= 128 && cp[1] < 192) {
66 	    /* UTF8; skip the rest of the bytes in the character. */
67 	    while (cp[1] >= 128 && cp[1] < 192)
68 		cp++;
69 	} else {
70 	    /* Not ASCII and not UTF8. */
71 	    *cp = replacement;
72 	}
73 	cp++;
74     }
75     return (string);
76 }
77