diff --git a/contrib/libc-pwcache/pwcache.c b/contrib/libc-pwcache/pwcache.c index 321e43900bd1..180935c75b42 100644 --- a/contrib/libc-pwcache/pwcache.c +++ b/contrib/libc-pwcache/pwcache.c @@ -1,646 +1,645 @@ /* $NetBSD: pwcache.c,v 1.31 2010/03/23 20:28:59 drochner Exp $ */ /*- * Copyright (c) 1992 Keith Muller. * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Keith Muller of the University of California, San Diego. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 2002 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_NBTOOL_CONFIG_H #include "nbtool_config.h" /* * XXX Undefine the renames of these functions so that we don't * XXX rename the versions found in the host's by mistake! */ #undef group_from_gid #undef user_from_uid #endif #include #if defined(LIBC_SCCS) && !defined(lint) #if 0 static char sccsid[] = "@(#)cache.c 8.1 (Berkeley) 5/31/93"; #else __RCSID("$NetBSD: pwcache.c,v 1.31 2010/03/23 20:28:59 drochner Exp $"); #endif #endif /* LIBC_SCCS and not lint */ -__FBSDID("$FreeBSD$"); #include "namespace.h" #include #include #include #include #include #include #include #include #include #define _DIAGASSERT(x) assert((x)) #if HAVE_NBTOOL_CONFIG_H /* XXX Now, re-apply the renaming that we undid above. */ #define group_from_gid __nbcompat_group_from_gid #define user_from_uid __nbcompat_user_from_uid #endif #ifdef __weak_alias __weak_alias(user_from_uid,_user_from_uid) __weak_alias(group_from_gid,_group_from_gid) __weak_alias(pwcache_groupdb,_pwcache_groupdb) #endif #if !HAVE_PWCACHE_USERDB || HAVE_NBTOOL_CONFIG_H #include "pwcache.h" /* * routines that control user, group, uid and gid caches (for the archive * member print routine). * IMPORTANT: * these routines cache BOTH hits and misses, a major performance improvement */ /* * function pointers to various name lookup routines. * these may be changed as necessary. */ static int (*_pwcache_setgroupent)(int) = setgroupent; static void (*_pwcache_endgrent)(void) = endgrent; static struct group * (*_pwcache_getgrnam)(const char *) = getgrnam; static struct group * (*_pwcache_getgrgid)(gid_t) = getgrgid; static int (*_pwcache_setpassent)(int) = setpassent; static void (*_pwcache_endpwent)(void) = endpwent; static struct passwd * (*_pwcache_getpwnam)(const char *) = getpwnam; static struct passwd * (*_pwcache_getpwuid)(uid_t) = getpwuid; /* * internal state */ static int pwopn; /* is password file open */ static int gropn; /* is group file open */ static UIDC **uidtb; /* uid to name cache */ static GIDC **gidtb; /* gid to name cache */ static UIDC **usrtb; /* user name to uid cache */ static GIDC **grptb; /* group name to gid cache */ static int uidtb_fail; /* uidtb_start() failed ? */ static int gidtb_fail; /* gidtb_start() failed ? */ static int usrtb_fail; /* usrtb_start() failed ? */ static int grptb_fail; /* grptb_start() failed ? */ static u_int st_hash(const char *, size_t, int); static int uidtb_start(void); static int gidtb_start(void); static int usrtb_start(void); static int grptb_start(void); static u_int st_hash(const char *name, size_t len, int tabsz) { u_int key = 0; _DIAGASSERT(name != NULL); while (len--) { key += *name++; key = (key << 8) | (key >> 24); } return (key % tabsz); } /* * uidtb_start * creates an an empty uidtb * Return: * 0 if ok, -1 otherwise */ static int uidtb_start(void) { if (uidtb != NULL) return (0); if (uidtb_fail) return (-1); if ((uidtb = (UIDC **)calloc(UID_SZ, sizeof(UIDC *))) == NULL) { ++uidtb_fail; return (-1); } return (0); } /* * gidtb_start * creates an an empty gidtb * Return: * 0 if ok, -1 otherwise */ static int gidtb_start(void) { if (gidtb != NULL) return (0); if (gidtb_fail) return (-1); if ((gidtb = (GIDC **)calloc(GID_SZ, sizeof(GIDC *))) == NULL) { ++gidtb_fail; return (-1); } return (0); } /* * usrtb_start * creates an an empty usrtb * Return: * 0 if ok, -1 otherwise */ static int usrtb_start(void) { if (usrtb != NULL) return (0); if (usrtb_fail) return (-1); if ((usrtb = (UIDC **)calloc(UNM_SZ, sizeof(UIDC *))) == NULL) { ++usrtb_fail; return (-1); } return (0); } /* * grptb_start * creates an an empty grptb * Return: * 0 if ok, -1 otherwise */ static int grptb_start(void) { if (grptb != NULL) return (0); if (grptb_fail) return (-1); if ((grptb = (GIDC **)calloc(GNM_SZ, sizeof(GIDC *))) == NULL) { ++grptb_fail; return (-1); } return (0); } /* * user_from_uid() * caches the name (if any) for the uid. If noname clear, we always * return the stored name (if valid or invalid match). * We use a simple hash table. * Return * Pointer to stored name (or a empty string) */ const char * user_from_uid(uid_t uid, int noname) { struct passwd *pw; UIDC *ptr, **pptr; if ((uidtb == NULL) && (uidtb_start() < 0)) return (NULL); /* * see if we have this uid cached */ pptr = uidtb + (uid % UID_SZ); ptr = *pptr; if ((ptr != NULL) && (ptr->valid > 0) && (ptr->uid == uid)) { /* * have an entry for this uid */ if (!noname || (ptr->valid == VALID)) return (ptr->name); return (NULL); } /* * No entry for this uid, we will add it */ if (!pwopn) { if (_pwcache_setpassent != NULL) (*_pwcache_setpassent)(1); ++pwopn; } if (ptr == NULL) *pptr = ptr = (UIDC *)malloc(sizeof(UIDC)); if ((pw = (*_pwcache_getpwuid)(uid)) == NULL) { /* * no match for this uid in the local password file * a string that is the uid in numeric format */ if (ptr == NULL) return (NULL); ptr->uid = uid; (void)snprintf(ptr->name, UNMLEN, "%lu", (long) uid); ptr->valid = INVALID; if (noname) return (NULL); } else { /* * there is an entry for this uid in the password file */ if (ptr == NULL) return (pw->pw_name); ptr->uid = uid; (void)strlcpy(ptr->name, pw->pw_name, UNMLEN); ptr->valid = VALID; } return (ptr->name); } /* * group_from_gid() * caches the name (if any) for the gid. If noname clear, we always * return the stored name (if valid or invalid match). * We use a simple hash table. * Return * Pointer to stored name (or a empty string) */ const char * group_from_gid(gid_t gid, int noname) { struct group *gr; GIDC *ptr, **pptr; if ((gidtb == NULL) && (gidtb_start() < 0)) return (NULL); /* * see if we have this gid cached */ pptr = gidtb + (gid % GID_SZ); ptr = *pptr; if ((ptr != NULL) && (ptr->valid > 0) && (ptr->gid == gid)) { /* * have an entry for this gid */ if (!noname || (ptr->valid == VALID)) return (ptr->name); return (NULL); } /* * No entry for this gid, we will add it */ if (!gropn) { if (_pwcache_setgroupent != NULL) (*_pwcache_setgroupent)(1); ++gropn; } if (ptr == NULL) *pptr = ptr = (GIDC *)malloc(sizeof(GIDC)); if ((gr = (*_pwcache_getgrgid)(gid)) == NULL) { /* * no match for this gid in the local group file, put in * a string that is the gid in numberic format */ if (ptr == NULL) return (NULL); ptr->gid = gid; (void)snprintf(ptr->name, GNMLEN, "%lu", (long) gid); ptr->valid = INVALID; if (noname) return (NULL); } else { /* * there is an entry for this group in the group file */ if (ptr == NULL) return (gr->gr_name); ptr->gid = gid; (void)strlcpy(ptr->name, gr->gr_name, GNMLEN); ptr->valid = VALID; } return (ptr->name); } /* * uid_from_user() * caches the uid for a given user name. We use a simple hash table. * Return * the uid (if any) for a user name, or a -1 if no match can be found */ int uid_from_user(const char *name, uid_t *uid) { struct passwd *pw; UIDC *ptr, **pptr; size_t namelen; /* * return -1 for mangled names */ if (name == NULL || ((namelen = strlen(name)) == 0)) return (-1); if ((usrtb == NULL) && (usrtb_start() < 0)) return (-1); /* * look up in hash table, if found and valid return the uid, * if found and invalid, return a -1 */ pptr = usrtb + st_hash(name, namelen, UNM_SZ); ptr = *pptr; if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) { if (ptr->valid == INVALID) return (-1); *uid = ptr->uid; return (0); } if (!pwopn) { if (_pwcache_setpassent != NULL) (*_pwcache_setpassent)(1); ++pwopn; } if (ptr == NULL) *pptr = ptr = (UIDC *)malloc(sizeof(UIDC)); /* * no match, look it up, if no match store it as an invalid entry, * or store the matching uid */ if (ptr == NULL) { if ((pw = (*_pwcache_getpwnam)(name)) == NULL) return (-1); *uid = pw->pw_uid; return (0); } (void)strlcpy(ptr->name, name, UNMLEN); if ((pw = (*_pwcache_getpwnam)(name)) == NULL) { ptr->valid = INVALID; return (-1); } ptr->valid = VALID; *uid = ptr->uid = pw->pw_uid; return (0); } /* * gid_from_group() * caches the gid for a given group name. We use a simple hash table. * Return * the gid (if any) for a group name, or a -1 if no match can be found */ int gid_from_group(const char *name, gid_t *gid) { struct group *gr; GIDC *ptr, **pptr; size_t namelen; /* * return -1 for mangled names */ if (name == NULL || ((namelen = strlen(name)) == 0)) return (-1); if ((grptb == NULL) && (grptb_start() < 0)) return (-1); /* * look up in hash table, if found and valid return the uid, * if found and invalid, return a -1 */ pptr = grptb + st_hash(name, namelen, GID_SZ); ptr = *pptr; if ((ptr != NULL) && (ptr->valid > 0) && !strcmp(name, ptr->name)) { if (ptr->valid == INVALID) return (-1); *gid = ptr->gid; return (0); } if (!gropn) { if (_pwcache_setgroupent != NULL) (*_pwcache_setgroupent)(1); ++gropn; } if (ptr == NULL) *pptr = ptr = (GIDC *)malloc(sizeof(GIDC)); /* * no match, look it up, if no match store it as an invalid entry, * or store the matching gid */ if (ptr == NULL) { if ((gr = (*_pwcache_getgrnam)(name)) == NULL) return (-1); *gid = gr->gr_gid; return (0); } (void)strlcpy(ptr->name, name, GNMLEN); if ((gr = (*_pwcache_getgrnam)(name)) == NULL) { ptr->valid = INVALID; return (-1); } ptr->valid = VALID; *gid = ptr->gid = gr->gr_gid; return (0); } #define FLUSHTB(arr, len, fail) \ do { \ if (arr != NULL) { \ for (i = 0; i < len; i++) \ if (arr[i] != NULL) \ free(arr[i]); \ arr = NULL; \ } \ fail = 0; \ } while (/* CONSTCOND */0); int pwcache_userdb( int (*a_setpassent)(int), void (*a_endpwent)(void), struct passwd * (*a_getpwnam)(const char *), struct passwd * (*a_getpwuid)(uid_t)) { int i; /* a_setpassent and a_endpwent may be NULL */ if (a_getpwnam == NULL || a_getpwuid == NULL) return (-1); if (_pwcache_endpwent != NULL) (*_pwcache_endpwent)(); FLUSHTB(uidtb, UID_SZ, uidtb_fail); FLUSHTB(usrtb, UNM_SZ, usrtb_fail); pwopn = 0; _pwcache_setpassent = a_setpassent; _pwcache_endpwent = a_endpwent; _pwcache_getpwnam = a_getpwnam; _pwcache_getpwuid = a_getpwuid; return (0); } int pwcache_groupdb( int (*a_setgroupent)(int), void (*a_endgrent)(void), struct group * (*a_getgrnam)(const char *), struct group * (*a_getgrgid)(gid_t)) { int i; /* a_setgroupent and a_endgrent may be NULL */ if (a_getgrnam == NULL || a_getgrgid == NULL) return (-1); if (_pwcache_endgrent != NULL) (*_pwcache_endgrent)(); FLUSHTB(gidtb, GID_SZ, gidtb_fail); FLUSHTB(grptb, GNM_SZ, grptb_fail); gropn = 0; _pwcache_setgroupent = a_setgroupent; _pwcache_endgrent = a_endgrent; _pwcache_getgrnam = a_getgrnam; _pwcache_getgrgid = a_getgrgid; return (0); } #ifdef TEST_PWCACHE struct passwd * test_getpwnam(const char *name) { static struct passwd foo; memset(&foo, 0, sizeof(foo)); if (strcmp(name, "toor") == 0) { foo.pw_uid = 666; return &foo; } return (getpwnam(name)); } int main(int argc, char *argv[]) { uid_t u; int r, i; printf("pass 1 (default userdb)\n"); for (i = 1; i < argc; i++) { printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n", i, pwopn, usrtb_fail, usrtb); r = uid_from_user(argv[i], &u); if (r == -1) printf(" uid_from_user %s: failed\n", argv[i]); else printf(" uid_from_user %s: %d\n", argv[i], u); } printf("pass 1 finish: pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb); puts(""); printf("pass 2 (replacement userdb)\n"); printf("pwcache_userdb returned %d\n", pwcache_userdb(setpassent, test_getpwnam, getpwuid)); printf("pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb); for (i = 1; i < argc; i++) { printf("i: %d, pwopn %d usrtb_fail %d usrtb %p\n", i, pwopn, usrtb_fail, usrtb); u = -1; r = uid_from_user(argv[i], &u); if (r == -1) printf(" uid_from_user %s: failed\n", argv[i]); else printf(" uid_from_user %s: %d\n", argv[i], u); } printf("pass 2 finish: pwopn %d usrtb_fail %d usrtb %p\n", pwopn, usrtb_fail, usrtb); puts(""); printf("pass 3 (null pointers)\n"); printf("pwcache_userdb returned %d\n", pwcache_userdb(NULL, NULL, NULL)); return (0); } #endif /* TEST_PWCACHE */ #endif /* !HAVE_PWCACHE_USERDB */ diff --git a/contrib/libc-vis/unvis.c b/contrib/libc-vis/unvis.c index f290d8db271a..62a350bfa912 100644 --- a/contrib/libc-vis/unvis.c +++ b/contrib/libc-vis/unvis.c @@ -1,568 +1,567 @@ /* $NetBSD: unvis.c,v 1.45 2022/04/19 20:32:15 rillig Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #if defined(LIBC_SCCS) && !defined(lint) #if 0 static char sccsid[] = "@(#)unvis.c 8.1 (Berkeley) 6/4/93"; #else __RCSID("$NetBSD: unvis.c,v 1.45 2022/04/19 20:32:15 rillig Exp $"); #endif #endif /* LIBC_SCCS and not lint */ -__FBSDID("$FreeBSD$"); #include "namespace.h" #include #include #include #include #include #include #include #define _DIAGASSERT(x) assert(x) /* * Return the number of elements in a statically-allocated array, * __x. */ #define __arraycount(__x) (sizeof(__x) / sizeof(__x[0])) #ifdef __weak_alias __weak_alias(strnunvisx,_strnunvisx) #endif #if !HAVE_VIS /* * decode driven by state machine */ #define S_GROUND 0 /* haven't seen escape char */ #define S_START 1 /* start decoding special sequence */ #define S_META 2 /* metachar started (M) */ #define S_META1 3 /* metachar more, regular char (-) */ #define S_CTRL 4 /* control char started (^) */ #define S_OCTAL2 5 /* octal digit 2 */ #define S_OCTAL3 6 /* octal digit 3 */ #define S_HEX 7 /* mandatory hex digit */ #define S_HEX1 8 /* http hex digit */ #define S_HEX2 9 /* http hex digit 2 */ #define S_MIME1 10 /* mime hex digit 1 */ #define S_MIME2 11 /* mime hex digit 2 */ #define S_EATCRNL 12 /* mime eating CRNL */ #define S_AMP 13 /* seen & */ #define S_NUMBER 14 /* collecting number */ #define S_STRING 15 /* collecting string */ #define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7') #define xtod(c) (isdigit(c) ? (c - '0') : ((tolower(c) - 'a') + 10)) #define XTOD(c) (isdigit(c) ? (c - '0') : ((c - 'A') + 10)) /* * RFC 1866 */ static const struct nv { char name[7]; uint8_t value; } nv[] = { { "AElig", 198 }, /* capital AE diphthong (ligature) */ { "Aacute", 193 }, /* capital A, acute accent */ { "Acirc", 194 }, /* capital A, circumflex accent */ { "Agrave", 192 }, /* capital A, grave accent */ { "Aring", 197 }, /* capital A, ring */ { "Atilde", 195 }, /* capital A, tilde */ { "Auml", 196 }, /* capital A, dieresis or umlaut mark */ { "Ccedil", 199 }, /* capital C, cedilla */ { "ETH", 208 }, /* capital Eth, Icelandic */ { "Eacute", 201 }, /* capital E, acute accent */ { "Ecirc", 202 }, /* capital E, circumflex accent */ { "Egrave", 200 }, /* capital E, grave accent */ { "Euml", 203 }, /* capital E, dieresis or umlaut mark */ { "Iacute", 205 }, /* capital I, acute accent */ { "Icirc", 206 }, /* capital I, circumflex accent */ { "Igrave", 204 }, /* capital I, grave accent */ { "Iuml", 207 }, /* capital I, dieresis or umlaut mark */ { "Ntilde", 209 }, /* capital N, tilde */ { "Oacute", 211 }, /* capital O, acute accent */ { "Ocirc", 212 }, /* capital O, circumflex accent */ { "Ograve", 210 }, /* capital O, grave accent */ { "Oslash", 216 }, /* capital O, slash */ { "Otilde", 213 }, /* capital O, tilde */ { "Ouml", 214 }, /* capital O, dieresis or umlaut mark */ { "THORN", 222 }, /* capital THORN, Icelandic */ { "Uacute", 218 }, /* capital U, acute accent */ { "Ucirc", 219 }, /* capital U, circumflex accent */ { "Ugrave", 217 }, /* capital U, grave accent */ { "Uuml", 220 }, /* capital U, dieresis or umlaut mark */ { "Yacute", 221 }, /* capital Y, acute accent */ { "aacute", 225 }, /* small a, acute accent */ { "acirc", 226 }, /* small a, circumflex accent */ { "acute", 180 }, /* acute accent */ { "aelig", 230 }, /* small ae diphthong (ligature) */ { "agrave", 224 }, /* small a, grave accent */ { "amp", 38 }, /* ampersand */ { "aring", 229 }, /* small a, ring */ { "atilde", 227 }, /* small a, tilde */ { "auml", 228 }, /* small a, dieresis or umlaut mark */ { "brvbar", 166 }, /* broken (vertical) bar */ { "ccedil", 231 }, /* small c, cedilla */ { "cedil", 184 }, /* cedilla */ { "cent", 162 }, /* cent sign */ { "copy", 169 }, /* copyright sign */ { "curren", 164 }, /* general currency sign */ { "deg", 176 }, /* degree sign */ { "divide", 247 }, /* divide sign */ { "eacute", 233 }, /* small e, acute accent */ { "ecirc", 234 }, /* small e, circumflex accent */ { "egrave", 232 }, /* small e, grave accent */ { "eth", 240 }, /* small eth, Icelandic */ { "euml", 235 }, /* small e, dieresis or umlaut mark */ { "frac12", 189 }, /* fraction one-half */ { "frac14", 188 }, /* fraction one-quarter */ { "frac34", 190 }, /* fraction three-quarters */ { "gt", 62 }, /* greater than */ { "iacute", 237 }, /* small i, acute accent */ { "icirc", 238 }, /* small i, circumflex accent */ { "iexcl", 161 }, /* inverted exclamation mark */ { "igrave", 236 }, /* small i, grave accent */ { "iquest", 191 }, /* inverted question mark */ { "iuml", 239 }, /* small i, dieresis or umlaut mark */ { "laquo", 171 }, /* angle quotation mark, left */ { "lt", 60 }, /* less than */ { "macr", 175 }, /* macron */ { "micro", 181 }, /* micro sign */ { "middot", 183 }, /* middle dot */ { "nbsp", 160 }, /* no-break space */ { "not", 172 }, /* not sign */ { "ntilde", 241 }, /* small n, tilde */ { "oacute", 243 }, /* small o, acute accent */ { "ocirc", 244 }, /* small o, circumflex accent */ { "ograve", 242 }, /* small o, grave accent */ { "ordf", 170 }, /* ordinal indicator, feminine */ { "ordm", 186 }, /* ordinal indicator, masculine */ { "oslash", 248 }, /* small o, slash */ { "otilde", 245 }, /* small o, tilde */ { "ouml", 246 }, /* small o, dieresis or umlaut mark */ { "para", 182 }, /* pilcrow (paragraph sign) */ { "plusmn", 177 }, /* plus-or-minus sign */ { "pound", 163 }, /* pound sterling sign */ { "quot", 34 }, /* double quote */ { "raquo", 187 }, /* angle quotation mark, right */ { "reg", 174 }, /* registered sign */ { "sect", 167 }, /* section sign */ { "shy", 173 }, /* soft hyphen */ { "sup1", 185 }, /* superscript one */ { "sup2", 178 }, /* superscript two */ { "sup3", 179 }, /* superscript three */ { "szlig", 223 }, /* small sharp s, German (sz ligature) */ { "thorn", 254 }, /* small thorn, Icelandic */ { "times", 215 }, /* multiply sign */ { "uacute", 250 }, /* small u, acute accent */ { "ucirc", 251 }, /* small u, circumflex accent */ { "ugrave", 249 }, /* small u, grave accent */ { "uml", 168 }, /* umlaut (dieresis) */ { "uuml", 252 }, /* small u, dieresis or umlaut mark */ { "yacute", 253 }, /* small y, acute accent */ { "yen", 165 }, /* yen sign */ { "yuml", 255 }, /* small y, dieresis or umlaut mark */ }; /* * unvis - decode characters previously encoded by vis */ int unvis(char *cp, int c, int *astate, int flag) { unsigned char uc = (unsigned char)c; unsigned char st, ia, is, lc; /* * Bottom 8 bits of astate hold the state machine state. * Top 8 bits hold the current character in the http 1866 nv string decoding */ #define GS(a) ((a) & 0xff) #define SS(a, b) (((uint32_t)(a) << 24) | (b)) #define GI(a) ((uint32_t)(a) >> 24) _DIAGASSERT(cp != NULL); _DIAGASSERT(astate != NULL); st = GS(*astate); if (flag & UNVIS_END) { switch (st) { case S_OCTAL2: case S_OCTAL3: case S_HEX2: *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_GROUND: return UNVIS_NOCHAR; default: return UNVIS_SYNBAD; } } switch (st) { case S_GROUND: *cp = 0; if ((flag & VIS_NOESCAPE) == 0 && c == '\\') { *astate = SS(0, S_START); return UNVIS_NOCHAR; } if ((flag & VIS_HTTP1808) && c == '%') { *astate = SS(0, S_HEX1); return UNVIS_NOCHAR; } if ((flag & VIS_HTTP1866) && c == '&') { *astate = SS(0, S_AMP); return UNVIS_NOCHAR; } if ((flag & VIS_MIMESTYLE) && c == '=') { *astate = SS(0, S_MIME1); return UNVIS_NOCHAR; } *cp = c; return UNVIS_VALID; case S_START: switch(c) { case '\\': *cp = c; *astate = SS(0, S_GROUND); return UNVIS_VALID; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *cp = (c - '0'); *astate = SS(0, S_OCTAL2); return UNVIS_NOCHAR; case 'M': *cp = (char)0200; *astate = SS(0, S_META); return UNVIS_NOCHAR; case '^': *astate = SS(0, S_CTRL); return UNVIS_NOCHAR; case 'n': *cp = '\n'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'r': *cp = '\r'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'b': *cp = '\b'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'a': *cp = '\007'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'v': *cp = '\v'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 't': *cp = '\t'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'f': *cp = '\f'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 's': *cp = ' '; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'E': *cp = '\033'; *astate = SS(0, S_GROUND); return UNVIS_VALID; case 'x': *astate = SS(0, S_HEX); return UNVIS_NOCHAR; case '\n': /* * hidden newline */ *astate = SS(0, S_GROUND); return UNVIS_NOCHAR; case '$': /* * hidden marker */ *astate = SS(0, S_GROUND); return UNVIS_NOCHAR; default: if (isgraph(c)) { *cp = c; *astate = SS(0, S_GROUND); return UNVIS_VALID; } } goto bad; case S_META: if (c == '-') *astate = SS(0, S_META1); else if (c == '^') *astate = SS(0, S_CTRL); else goto bad; return UNVIS_NOCHAR; case S_META1: *astate = SS(0, S_GROUND); *cp |= c; return UNVIS_VALID; case S_CTRL: if (c == '?') *cp |= 0177; else *cp |= c & 037; *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_OCTAL2: /* second possible octal digit */ if (isoctal(uc)) { /* * yes - and maybe a third */ *cp = (*cp << 3) + (c - '0'); *astate = SS(0, S_OCTAL3); return UNVIS_NOCHAR; } /* * no - done with current sequence, push back passed char */ *astate = SS(0, S_GROUND); return UNVIS_VALIDPUSH; case S_OCTAL3: /* third possible octal digit */ *astate = SS(0, S_GROUND); if (isoctal(uc)) { *cp = (*cp << 3) + (c - '0'); return UNVIS_VALID; } /* * we were done, push back passed char */ return UNVIS_VALIDPUSH; case S_HEX: if (!isxdigit(uc)) goto bad; /*FALLTHROUGH*/ case S_HEX1: if (isxdigit(uc)) { *cp = xtod(uc); *astate = SS(0, S_HEX2); return UNVIS_NOCHAR; } /* * no - done with current sequence, push back passed char */ *astate = SS(0, S_GROUND); return UNVIS_VALIDPUSH; case S_HEX2: *astate = S_GROUND; if (isxdigit(uc)) { *cp = xtod(uc) | (*cp << 4); return UNVIS_VALID; } return UNVIS_VALIDPUSH; case S_MIME1: if (uc == '\n' || uc == '\r') { *astate = SS(0, S_EATCRNL); return UNVIS_NOCHAR; } if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) { *cp = XTOD(uc); *astate = SS(0, S_MIME2); return UNVIS_NOCHAR; } goto bad; case S_MIME2: if (isxdigit(uc) && (isdigit(uc) || isupper(uc))) { *astate = SS(0, S_GROUND); *cp = XTOD(uc) | (*cp << 4); return UNVIS_VALID; } goto bad; case S_EATCRNL: switch (uc) { case '\r': case '\n': return UNVIS_NOCHAR; case '=': *astate = SS(0, S_MIME1); return UNVIS_NOCHAR; default: *cp = uc; *astate = SS(0, S_GROUND); return UNVIS_VALID; } case S_AMP: *cp = 0; if (uc == '#') { *astate = SS(0, S_NUMBER); return UNVIS_NOCHAR; } *astate = SS(0, S_STRING); /*FALLTHROUGH*/ case S_STRING: ia = *cp; /* index in the array */ is = GI(*astate); /* index in the string */ lc = is == 0 ? 0 : nv[ia].name[is - 1]; /* last character */ if (uc == ';') uc = '\0'; for (; ia < __arraycount(nv); ia++) { if (is != 0 && nv[ia].name[is - 1] != lc) goto bad; if (nv[ia].name[is] == uc) break; } if (ia == __arraycount(nv)) goto bad; if (uc != 0) { *cp = ia; *astate = SS(is + 1, S_STRING); return UNVIS_NOCHAR; } *cp = nv[ia].value; *astate = SS(0, S_GROUND); return UNVIS_VALID; case S_NUMBER: if (uc == ';') return UNVIS_VALID; if (!isdigit(uc)) goto bad; *cp += (*cp * 10) + uc - '0'; return UNVIS_NOCHAR; default: bad: /* * decoder in unknown state - (probably uninitialized) */ *astate = SS(0, S_GROUND); return UNVIS_SYNBAD; } } /* * strnunvisx - decode src into dst * * Number of chars decoded into dst is returned, -1 on error. * Dst is null terminated. */ int strnunvisx(char *dst, size_t dlen, const char *src, int flag) { char c; char t = '\0', *start = dst; int state = 0; _DIAGASSERT(src != NULL); _DIAGASSERT(dst != NULL); #define CHECKSPACE() \ do { \ if (dlen-- == 0) { \ errno = ENOSPC; \ return -1; \ } \ } while (0) while ((c = *src++) != '\0') { again: switch (unvis(&t, c, &state, flag)) { case UNVIS_VALID: CHECKSPACE(); *dst++ = t; break; case UNVIS_VALIDPUSH: CHECKSPACE(); *dst++ = t; goto again; case 0: case UNVIS_NOCHAR: break; case UNVIS_SYNBAD: errno = EINVAL; return -1; default: _DIAGASSERT(/*CONSTCOND*/0); errno = EINVAL; return -1; } } if (unvis(&t, c, &state, UNVIS_END) == UNVIS_VALID) { CHECKSPACE(); *dst++ = t; } CHECKSPACE(); *dst = '\0'; return (int)(dst - start); } int strunvisx(char *dst, const char *src, int flag) { return strnunvisx(dst, (size_t)~0, src, flag); } int strunvis(char *dst, const char *src) { return strnunvisx(dst, (size_t)~0, src, 0); } int strnunvis(char *dst, size_t dlen, const char *src) { return strnunvisx(dst, dlen, src, 0); } #endif diff --git a/contrib/libc-vis/vis.c b/contrib/libc-vis/vis.c index 2f9eab25b480..623acfe92e1d 100644 --- a/contrib/libc-vis/vis.c +++ b/contrib/libc-vis/vis.c @@ -1,854 +1,851 @@ /* $NetBSD: vis.c,v 1.83 2023/08/12 12:48:52 riastradh Exp $ */ /*- * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Copyright (c) 1999, 2005 The NetBSD Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: vis.c,v 1.83 2023/08/12 12:48:52 riastradh Exp $"); #endif /* LIBC_SCCS and not lint */ -#ifdef __FBSDID -__FBSDID("$FreeBSD$"); -#endif #include "namespace.h" #include #include #include #include #include #include #include #include #include #ifdef __weak_alias __weak_alias(strvisx,_strvisx) #endif #if !HAVE_VIS || !HAVE_SVIS #include #include #include #include #define _DIAGASSERT(x) assert(x) /* * The reason for going through the trouble to deal with character encodings * in vis(3), is that we use this to safe encode output of commands. This * safe encoding varies depending on the character set. For example if we * display ps output in French, we don't want to display French characters * as M-foo. */ static wchar_t *do_svis(wchar_t *, wint_t, int, wint_t, const wchar_t *); #undef BELL #define BELL L'\a' #if defined(LC_C_LOCALE) #define iscgraph(c) isgraph_l(c, LC_C_LOCALE) #else /* Keep it simple for now, no locale stuff */ #define iscgraph(c) isgraph(c) #ifdef notyet #include static int iscgraph(int c) { int rv; char *ol; ol = setlocale(LC_CTYPE, "C"); rv = isgraph(c); if (ol) setlocale(LC_CTYPE, ol); return rv; } #endif #endif #define ISGRAPH(flags, c) \ (((flags) & VIS_NOLOCALE) ? iscgraph(c) : iswgraph(c)) #define iswoctal(c) (((u_char)(c)) >= L'0' && ((u_char)(c)) <= L'7') #define iswwhite(c) (c == L' ' || c == L'\t' || c == L'\n') #define iswsafe(c) (c == L'\b' || c == BELL || c == L'\r') #define xtoa(c) L"0123456789abcdef"[c] #define XTOA(c) L"0123456789ABCDEF"[c] #define MAXEXTRAS 30 static const wchar_t char_shell[] = L"'`\";&<>()|{}]\\$!^~"; static const wchar_t char_glob[] = L"*?[#"; #if !HAVE_NBTOOL_CONFIG_H #ifndef __NetBSD__ /* * On NetBSD MB_LEN_MAX is currently 32 which does not fit on any integer * integral type and it is probably wrong, since currently the maximum * number of bytes and character needs is 6. Until this is fixed, the * loops below are using sizeof(uint64_t) - 1 instead of MB_LEN_MAX, and * the assertion is commented out. */ #ifdef __FreeBSD__ /* * On FreeBSD including for CTASSERT only works in kernel * mode. */ #ifndef CTASSERT #define CTASSERT(x) _CTASSERT(x, __LINE__) #define _CTASSERT(x, y) __CTASSERT(x, y) #define __CTASSERT(x, y) typedef char __assert ## y[(x) ? 1 : -1] #endif #endif /* __FreeBSD__ */ CTASSERT(MB_LEN_MAX <= sizeof(uint64_t)); #endif /* !__NetBSD__ */ #endif /* * This is do_hvis, for HTTP style (RFC 1808) */ static wchar_t * do_hvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { if (iswalnum(c) /* safe */ || c == L'$' || c == L'-' || c == L'_' || c == L'.' || c == L'+' /* extra */ || c == L'!' || c == L'*' || c == L'\'' || c == L'(' || c == L')' || c == L',') dst = do_svis(dst, c, flags, nextc, extra); else { *dst++ = L'%'; *dst++ = xtoa(((unsigned int)c >> 4) & 0xf); *dst++ = xtoa((unsigned int)c & 0xf); } return dst; } /* * This is do_mvis, for Quoted-Printable MIME (RFC 2045) * NB: No handling of long lines or CRLF. */ static wchar_t * do_mvis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { if ((c != L'\n') && /* Space at the end of the line */ ((iswspace(c) && (nextc == L'\r' || nextc == L'\n')) || /* Out of range */ (!iswspace(c) && (c < 33 || (c > 60 && c < 62) || c > 126)) || /* Specific char to be escaped */ wcschr(L"#$@[\\]^`{|}~", c) != NULL)) { *dst++ = L'='; *dst++ = XTOA(((unsigned int)c >> 4) & 0xf); *dst++ = XTOA((unsigned int)c & 0xf); } else dst = do_svis(dst, c, flags, nextc, extra); return dst; } /* * Output single byte of multibyte character. */ static wchar_t * do_mbyte(wchar_t *dst, wint_t c, int flags, wint_t nextc, int iswextra) { if (flags & VIS_CSTYLE) { switch (c) { case L'\n': *dst++ = L'\\'; *dst++ = L'n'; return dst; case L'\r': *dst++ = L'\\'; *dst++ = L'r'; return dst; case L'\b': *dst++ = L'\\'; *dst++ = L'b'; return dst; case BELL: *dst++ = L'\\'; *dst++ = L'a'; return dst; case L'\v': *dst++ = L'\\'; *dst++ = L'v'; return dst; case L'\t': *dst++ = L'\\'; *dst++ = L't'; return dst; case L'\f': *dst++ = L'\\'; *dst++ = L'f'; return dst; case L' ': *dst++ = L'\\'; *dst++ = L's'; return dst; case L'\0': *dst++ = L'\\'; *dst++ = L'0'; if (iswoctal(nextc)) { *dst++ = L'0'; *dst++ = L'0'; } return dst; /* We cannot encode these characters in VIS_CSTYLE * because they special meaning */ case L'n': case L'r': case L'b': case L'a': case L'v': case L't': case L'f': case L's': case L'0': case L'M': case L'^': case L'$': /* vis(1) -l */ break; default: if (ISGRAPH(flags, c) && !iswoctal(c)) { *dst++ = L'\\'; *dst++ = c; return dst; } } } if (iswextra || ((c & 0177) == L' ') || (flags & VIS_OCTAL)) { *dst++ = L'\\'; *dst++ = (u_char)(((u_int32_t)(u_char)c >> 6) & 03) + L'0'; *dst++ = (u_char)(((u_int32_t)(u_char)c >> 3) & 07) + L'0'; *dst++ = (c & 07) + L'0'; } else { if ((flags & VIS_NOSLASH) == 0) *dst++ = L'\\'; if (c & 0200) { c &= 0177; *dst++ = L'M'; } if (iswcntrl(c)) { *dst++ = L'^'; if (c == 0177) *dst++ = L'?'; else *dst++ = c + L'@'; } else { *dst++ = L'-'; *dst++ = c; } } return dst; } /* * This is do_vis, the central code of vis. * dst: Pointer to the destination buffer * c: Character to encode * flags: Flags word * nextc: The character following 'c' * extra: Pointer to the list of extra characters to be * backslash-protected. */ static wchar_t * do_svis(wchar_t *dst, wint_t c, int flags, wint_t nextc, const wchar_t *extra) { int iswextra, i, shft; uint64_t bmsk, wmsk; iswextra = wcschr(extra, c) != NULL; if (!iswextra && (ISGRAPH(flags, c) || iswwhite(c) || ((flags & VIS_SAFE) && iswsafe(c)))) { *dst++ = c; return dst; } /* See comment in istrsenvisx() output loop, below. */ wmsk = 0; for (i = sizeof(wmsk) - 1; i >= 0; i--) { shft = i * NBBY; bmsk = (uint64_t)0xffLL << shft; wmsk |= bmsk; if ((c & wmsk) || i == 0) dst = do_mbyte(dst, (wint_t)( (uint64_t)(c & bmsk) >> shft), flags, nextc, iswextra); } return dst; } typedef wchar_t *(*visfun_t)(wchar_t *, wint_t, int, wint_t, const wchar_t *); /* * Return the appropriate encoding function depending on the flags given. */ static visfun_t getvisfun(int flags) { if (flags & VIS_HTTPSTYLE) return do_hvis; if (flags & VIS_MIMESTYLE) return do_mvis; return do_svis; } /* * Expand list of extra characters to not visually encode. */ static wchar_t * makeextralist(int flags, const char *src) { wchar_t *dst, *d; size_t len; const wchar_t *s; mbstate_t mbstate; bzero(&mbstate, sizeof(mbstate)); len = strlen(src); if ((dst = calloc(len + MAXEXTRAS, sizeof(*dst))) == NULL) return NULL; memset(&mbstate, 0, sizeof(mbstate)); if ((flags & VIS_NOLOCALE) || mbsrtowcs(dst, &src, len, &mbstate) == (size_t)-1) { size_t i; for (i = 0; i < len; i++) dst[i] = (wchar_t)(u_char)src[i]; d = dst + len; } else d = dst + wcslen(dst); if (flags & VIS_GLOB) for (s = char_glob; *s; *d++ = *s++) continue; if (flags & VIS_SHELL) for (s = char_shell; *s; *d++ = *s++) continue; if (flags & VIS_SP) *d++ = L' '; if (flags & VIS_TAB) *d++ = L'\t'; if (flags & VIS_NL) *d++ = L'\n'; if (flags & VIS_DQ) *d++ = L'"'; if ((flags & VIS_NOSLASH) == 0) *d++ = L'\\'; *d = L'\0'; return dst; } /* * istrsenvisx() * The main internal function. * All user-visible functions call this one. */ static int istrsenvisx(char **mbdstp, size_t *dlen, const char *mbsrc, size_t mblength, int flags, const char *mbextra, int *cerr_ptr) { char mbbuf[MB_LEN_MAX]; wchar_t *dst, *src, *pdst, *psrc, *start, *extra; size_t len, olen; uint64_t bmsk, wmsk; wint_t c; visfun_t f; int clen = 0, cerr, error = -1, i, shft; char *mbdst, *mbwrite, *mdst; size_t mbslength; size_t maxolen; mbstate_t mbstate; _DIAGASSERT(mbdstp != NULL); _DIAGASSERT(mbsrc != NULL || mblength == 0); _DIAGASSERT(mbextra != NULL); mbslength = mblength; /* * When inputing a single character, must also read in the * next character for nextc, the look-ahead character. */ if (mbslength == 1) mbslength++; /* * Input (mbsrc) is a char string considered to be multibyte * characters. The input loop will read this string pulling * one character, possibly multiple bytes, from mbsrc and * converting each to wchar_t in src. * * The vis conversion will be done using the wide char * wchar_t string. * * This will then be converted back to a multibyte string to * return to the caller. */ /* * Guarantee the arithmetic on input to calloc won't overflow. */ if (mbslength > (SIZE_MAX - 1)/16) { errno = ENOMEM; return -1; } /* Allocate space for the wide char strings */ psrc = pdst = extra = NULL; mdst = NULL; if ((psrc = calloc(mbslength + 1, sizeof(*psrc))) == NULL) return -1; if ((pdst = calloc((16 * mbslength) + 1, sizeof(*pdst))) == NULL) goto out; if (*mbdstp == NULL) { if ((mdst = calloc((16 * mbslength) + 1, sizeof(*mdst))) == NULL) goto out; *mbdstp = mdst; } mbdst = *mbdstp; dst = pdst; src = psrc; if (flags & VIS_NOLOCALE) { /* Do one byte at a time conversion */ cerr = 1; } else { /* Use caller's multibyte conversion error flag. */ cerr = cerr_ptr ? *cerr_ptr : 0; } /* * Input loop. * Handle up to mblength characters (not bytes). We do not * stop at NULs because we may be processing a block of data * that includes NULs. */ memset(&mbstate, 0, sizeof(mbstate)); while (mbslength > 0) { /* Convert one multibyte character to wchar_t. */ if (!cerr) { clen = mbrtowc(src, mbsrc, (mbslength < MB_LEN_MAX ? mbslength : MB_LEN_MAX), &mbstate); assert(clen < 0 || (size_t)clen <= mbslength); assert(clen <= MB_LEN_MAX); } if (cerr || clen < 0) { /* Conversion error, process as a byte instead. */ *src = (wint_t)(u_char)*mbsrc; clen = 1; cerr = 1; } if (clen == 0) { /* * NUL in input gives 0 return value. process * as single NUL byte and keep going. */ clen = 1; } /* * Let n := MIN(mbslength, MB_LEN_MAX). We have: * * mbslength >= 1 * mbrtowc(..., n, &mbstate) <= n, * by the contract of mbrtowc * * clen is either * (a) mbrtowc(..., n, &mbstate), in which case * clen <= n <= mbslength; or * (b) 1, in which case clen = 1 <= mbslength. */ assert(clen > 0); assert((size_t)clen <= mbslength); /* Advance buffer character pointer. */ src++; /* Advance input pointer by number of bytes read. */ mbsrc += clen; /* Decrement input byte count. */ mbslength -= clen; } len = src - psrc; src = psrc; /* * In the single character input case, we will have actually * processed two characters, c and nextc. Reset len back to * just a single character. */ if (mblength < len) len = mblength; /* Convert extra argument to list of characters for this mode. */ extra = makeextralist(flags, mbextra); if (!extra) { if (dlen && *dlen == 0) { errno = ENOSPC; goto out; } *mbdst = '\0'; /* can't create extra, return "" */ error = 0; goto out; } /* Look up which processing function to call. */ f = getvisfun(flags); /* * Main processing loop. * Call do_Xvis processing function one character at a time * with next character available for look-ahead. */ for (start = dst; len > 0; len--) { c = *src++; dst = (*f)(dst, c, flags, len >= 1 ? *src : L'\0', extra); if (dst == NULL) { errno = ENOSPC; goto out; } } /* Terminate the string in the buffer. */ *dst = L'\0'; /* * Output loop. * Convert wchar_t string back to multibyte output string. * If we have hit a multi-byte conversion error on input, * output byte-by-byte here. Else use wctomb(). */ len = wcslen(start); if (dlen) { maxolen = *dlen; if (maxolen == 0) { errno = ENOSPC; goto out; } } else { if (len > (SIZE_MAX - 1)/MB_LEN_MAX) { errno = ENOSPC; goto out; } maxolen = len*MB_LEN_MAX + 1; } olen = 0; memset(&mbstate, 0, sizeof(mbstate)); for (dst = start; len > 0; len--) { if (!cerr) { /* * If we have at least MB_CUR_MAX bytes in the buffer, * we'll just do the conversion in-place into mbdst. We * need to be a little more conservative when we get to * the end of the buffer, as we may not have MB_CUR_MAX * bytes but we may not need it. */ if (maxolen - olen > MB_CUR_MAX) mbwrite = mbdst; else mbwrite = mbbuf; clen = wcrtomb(mbwrite, *dst, &mbstate); if (clen > 0 && mbwrite != mbdst) { /* * Don't break past our output limit, noting * that maxolen includes the nul terminator so * we can't write past maxolen - 1 here. */ if (olen + clen >= maxolen) { errno = ENOSPC; goto out; } memcpy(mbdst, mbwrite, clen); } } if (cerr || clen < 0) { /* * Conversion error, process as a byte(s) instead. * Examine each byte and higher-order bytes for * data. E.g., * 0x000000000000a264 -> a2 64 * 0x000000001f00a264 -> 1f 00 a2 64 */ clen = 0; wmsk = 0; for (i = sizeof(wmsk) - 1; i >= 0; i--) { shft = i * NBBY; bmsk = (uint64_t)0xffLL << shft; wmsk |= bmsk; if ((*dst & wmsk) || i == 0) { if (olen + clen + 1 >= maxolen) { errno = ENOSPC; goto out; } mbdst[clen++] = (char)( (uint64_t)(*dst & bmsk) >> shft); } } cerr = 1; } /* * We'll be dereferencing mbdst[clen] after this to write the * nul terminator; the above paths should have checked for a * possible overflow already. */ assert(olen + clen < maxolen); /* Advance output pointer by number of bytes written. */ mbdst += clen; /* Advance buffer character pointer. */ dst++; /* Incrment output character count. */ olen += clen; } /* Terminate the output string. */ assert(olen < maxolen); *mbdst = '\0'; if (flags & VIS_NOLOCALE) { /* Pass conversion error flag out. */ if (cerr_ptr) *cerr_ptr = cerr; } free(extra); free(pdst); free(psrc); return (int)olen; out: free(extra); free(pdst); free(psrc); free(mdst); return error; } static int istrsenvisxl(char **mbdstp, size_t *dlen, const char *mbsrc, int flags, const char *mbextra, int *cerr_ptr) { return istrsenvisx(mbdstp, dlen, mbsrc, mbsrc != NULL ? strlen(mbsrc) : 0, flags, mbextra, cerr_ptr); } #endif #if !HAVE_SVIS /* * The "svis" variants all take an "extra" arg that is a pointer * to a NUL-terminated list of characters to be encoded, too. * These functions are useful e. g. to encode strings in such a * way so that they are not interpreted by a shell. */ char * svis(char *mbdst, int c, int flags, int nextc, const char *mbextra) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, mbextra, NULL); if (ret < 0) return NULL; return mbdst + ret; } char * snvis(char *mbdst, size_t dlen, int c, int flags, int nextc, const char *mbextra) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, mbextra, NULL); if (ret < 0) return NULL; return mbdst + ret; } int strsvis(char *mbdst, const char *mbsrc, int flags, const char *mbextra) { return istrsenvisxl(&mbdst, NULL, mbsrc, flags, mbextra, NULL); } int strsnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags, const char *mbextra) { return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, mbextra, NULL); } int strsvisx(char *mbdst, const char *mbsrc, size_t len, int flags, const char *mbextra) { return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, mbextra, NULL); } int strsnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, const char *mbextra) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, NULL); } int strsenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, const char *mbextra, int *cerr_ptr) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, mbextra, cerr_ptr); } #endif #if !HAVE_VIS /* * vis - visually encode characters */ char * vis(char *mbdst, int c, int flags, int nextc) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, NULL, cc, 1, flags, "", NULL); if (ret < 0) return NULL; return mbdst + ret; } char * nvis(char *mbdst, size_t dlen, int c, int flags, int nextc) { char cc[2]; int ret; cc[0] = c; cc[1] = nextc; ret = istrsenvisx(&mbdst, &dlen, cc, 1, flags, "", NULL); if (ret < 0) return NULL; return mbdst + ret; } /* * strvis - visually encode characters from src into dst * * Dst must be 4 times the size of src to account for possible * expansion. The length of dst, not including the trailing NULL, * is returned. */ int strvis(char *mbdst, const char *mbsrc, int flags) { return istrsenvisxl(&mbdst, NULL, mbsrc, flags, "", NULL); } int strnvis(char *mbdst, size_t dlen, const char *mbsrc, int flags) { return istrsenvisxl(&mbdst, &dlen, mbsrc, flags, "", NULL); } int stravis(char **mbdstp, const char *mbsrc, int flags) { *mbdstp = NULL; return istrsenvisxl(mbdstp, NULL, mbsrc, flags, "", NULL); } /* * strvisx - visually encode characters from src into dst * * Dst must be 4 times the size of src to account for possible * expansion. The length of dst, not including the trailing NULL, * is returned. * * Strvisx encodes exactly len characters from src into dst. * This is useful for encoding a block of data. */ int strvisx(char *mbdst, const char *mbsrc, size_t len, int flags) { return istrsenvisx(&mbdst, NULL, mbsrc, len, flags, "", NULL); } int strnvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", NULL); } int strenvisx(char *mbdst, size_t dlen, const char *mbsrc, size_t len, int flags, int *cerr_ptr) { return istrsenvisx(&mbdst, &dlen, mbsrc, len, flags, "", cerr_ptr); } #endif