about summary refs log blame commit diff stats
path: root/WWW/Library/Implementation/HTParse.c
blob: 2e454418a5681dcc3a31e93a043f5b7f91903b6e (plain) (tree)
nos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; } .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 * $LynxId: HTUtils.h,v 1.134 2021/06/29 22:01:12 tom Exp $
 *
 * Utility macros for the W3 code library
 * MACROS FOR GENERAL USE
 * 
 * See also:  the system dependent file "www_tcp.h", which is included here.
 */

#ifndef NO_LYNX_TRACE
#define DEBUG			/* Turns on trace; turn off for smaller binary */
#endif

#ifndef HTUTILS_H
#define HTUTILS_H

#ifdef HAVE_CONFIG_H
#include <lynx_cfg.h>		/* generated by autoconf 'configure' script */

#ifdef HAVE_STDNORETURN_H
#include <stdnoreturn.h>
#undef GCC_NORETURN
#define GCC_NORETURN _Noreturn
#endif

/* see AC_FUNC_ALLOCA macro */
#ifdef __GNUC__
# define alloca(size) __builtin_alloca(size)
#else
# ifdef _MSC_VER
#  include <malloc.h>
#  ifndef alloca
#   define alloca(size) _alloca(size)
#  endif
# else
#  if HAVE_ALLOCA_H
#   include <alloca.h>
#  else
#   ifdef _AIX
#pragma alloca
#   else
#    ifndef alloca		/* predefined by HP cc +Olibcalls */
char *alloca();

#    endif
#   endif
#  endif
# endif
#endif

#include <sys/types.h>
#include <stdio.h>

#else /* HAVE_CONFIG_H */

#ifdef DJGPP
#include <sys/config.h>		/* pseudo-autoconf values for DJGPP libc/headers */
#define HAVE_TRUNCATE 1
#define HAVE_ALLOCA 1
#include <limits.h>
#endif /* DJGPP */

#include <sys/types.h>
#include <stdio.h>

/* Explicit system-configure */
#ifdef VMS
#define NO_SIZECHANGE

#if defined(VAXC) && !defined(__DECC)
#define NO_UNISTD_H		/* DEC C has unistd.h, but not VAX C */
#endif

#define NO_KEYPAD
#define NO_UTMP

#undef NO_FILIO_H
#define NO_FILIO_H

#define NOUSERS
#define DISP_PARTIAL		/* experimental */
#endif

#if defined(VMS) || defined(_WINDOWS)
#define HAVE_STDLIB_H 1
#endif

/* Accommodate non-autoconf'd Makefile's (VMS, DJGPP, etc) */

#ifndef NO_ARPA_INET_H
#define HAVE_ARPA_INET_H 1
#endif

#ifndef NO_CBREAK
#define HAVE_CBREAK 1
#endif

#ifndef NO_CUSERID
#define HAVE_CUSERID 1
#endif

#ifndef NO_FILIO_H
#define HAVE_SYS_FILIO_H 1
#endif

#ifndef NO_GETCWD
#define HAVE_GETCWD 1
#endif

#ifndef USE_SLANG
#ifndef NO_KEYPAD
#define HAVE_KEYPAD 1
#endif
#ifndef NO_TTYTYPE
#define HAVE_TTYTYPE 1
#endif
#endif /* USE_SLANG */

#ifndef NO_PUTENV
#define HAVE_PUTENV 1
#endif

#ifndef NO_SIZECHANGE
#define HAVE_SIZECHANGE 1
#endif

#ifndef NO_UNISTD_H
#undef  HAVE_UNISTD_H
#define HAVE_UNISTD_H 1
#endif

#ifndef NO_UTMP
#define HAVE_UTMP 1
#endif

#endif /* HAVE_CONFIG_H */

#include <assert.h>

/* suppress inadvertent use of gettext in makeuctb when cross-compiling */
#ifdef DONT_USE_GETTEXT
#undef HAVE_GETTEXT
#undef HAVE_LIBGETTEXT_H
#undef HAVE_LIBINTL_H
#endif

#ifndef HAVE_ICONV
#undef USE_JAPANESEUTF8_SUPPORT
#endif

#ifndef lynx_srand
#define lynx_srand srand
#endif

#ifndef lynx_rand
#define lynx_rand rand
#endif

#if '0' != 48
#define NOT_ASCII
#endif

#if '0' == 240
#define EBCDIC
#endif

#ifndef LY_MAXPATH
#define LY_MAXPATH 256
#endif

#ifndef GCC_NORETURN
#define GCC_NORETURN		/* nothing */
#endif

#ifndef GCC_UNUSED
#define GCC_UNUSED		/* nothing */
#endif

#if defined(__GNUC__) && defined(_FORTIFY_SOURCE)
#define USE_IGNORE_RC
extern int ignore_unused;

#define IGNORE_RC(func) ignore_unused = (int) func
#else
#define IGNORE_RC(func) (void) func
#endif /* gcc workarounds */

#if defined(__CYGWIN32__) && ! defined(__CYGWIN__)
#define __CYGWIN__ 1
#endif

#if defined(__CYGWIN__)		/* 1998/12/31 (Thu) 16:13:46 */
#ifdef USE_OPENSSL_INCL
#define NOCRYPT			/* workaround for openssl 1.0.1e bug */
#endif
#include <windows.h>		/* #include "windef.h" */
#define BOOLEAN_DEFINED
#undef HAVE_POPEN		/* FIXME: does this not work, or is it missing */
#undef small			/* see <w32api/rpcndr.h> */
#endif

#if defined(__DARWIN_NO_LONG_LONG)
#undef HAVE_ATOLL
#endif

#if defined(HAVE_ATOLL)
#define LYatoll(n) atoll(n)
#else
extern off_t LYatoll(const char *value);
#endif

/* cygwin, mingw32, etc. */
#ifdef FILE_DOES_NOT_EXIST
#undef FILE_DOES_NOT_EXIST	/* see <w32api/winnt.h> */
#endif

/*
 * VS .NET 2003 includes winsock.h unconditionally from windows.h,
 * so we do not want to include windows.h if we want winsock2.h
 */
#if defined(_WINDOWS) && !defined(__CYGWIN__)

#ifndef __GNUC__
#pragma warning (disable : 4100)	/* unreferenced formal parameter */
#pragma warning (disable : 4127)	/* conditional expression is constant */
#pragma warning (disable : 4201)	/* nameless struct/union */
#pragma warning (disable : 4214)	/* bit field types other than int */
#pragma warning (disable : 4310)	/* cast truncates constant value */
#pragma warning (disable : 4514)	/* unreferenced inline function has been removed */
#pragma warning (disable : 4996)	/* This function or variable may be unsafe. ... */
#endif

#if defined(USE_WINSOCK2_H) && (_MSC_VER >= 1300) && (_MSC_VER < 1400)
#include <winsock2.h>		/* includes windows.h, in turn windef.h */
#else
#include <windows.h>		/* #include "windef.h" */
#endif

#define BOOLEAN_DEFINED

#if !_WIN_CC			/* 1999/09/29 (Wed) 22:00:53 */
#include <dos.h>
#endif

#if defined(DECL_SLEEP) && defined(HAVE_CONFIG_H)
#  undef sleep
#  if defined(__MINGW32__)
#    define sleep(n) Sleep((n)*100)
#  else
extern void sleep(unsigned __seconds);
#  endif
#elif !defined(__MINGW32__)
#  undef sleep
extern void sleep(unsigned __seconds);
#endif

#define popen _popen
#define pclose _pclose

#if defined(_MSC_VER) && (_MSC_VER > 0)
typedef unsigned short mode_t;
#endif

#endif /* _WINDOWS */

#if defined(USE_DEFAULT_COLORS) && !defined(HAVE_USE_DEFAULT_COLORS)
    /* if we don't have use_default_colors() */
#  undef USE_DEFAULT_COLORS
#endif

#ifndef USE_COLOR_STYLE
    /* it's useless for such setup */
#  define NO_EMPTY_HREFLESS_A
#endif

#if  defined(__EMX__) || defined(WIN_EX) || defined(HAVE_POPEN)
#  define CAN_CUT_AND_PASTE
#endif

#if defined(USE_SLANG) || (defined(USE_COLOR_STYLE) && defined(__EMX__))
#  define USE_BLINK
#endif

#if defined(DOSPATH) || defined(__EMX__)
#  define USE_DOS_DRIVES	/* we allow things like "c:" in paths */
#endif

#if defined(UNIX)
#  if (defined(__BEOS__) || defined(__CYGWIN__) || defined(__DJGPP__) || defined(__EMX__) || defined(__MINGW32__))
#    define SINGLE_USER_UNIX	/* well, at least they try */
#  else
#    define MULTI_USER_UNIX
#  endif
#endif

/*

  ERROR TYPE

   This is passed back when streams are aborted. It might be nice to have some structure
   of error messages, numbers, and recursive pointers to reasons.  Currently this is a
   placeholder for something more sophisticated.

 */
typedef void *HTError;		/* Unused at present -- best definition? */

/*

Standard C library for malloc() etc

 */
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif

#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif

#ifdef __EMX__
#include <unistd.h>		/* should be re-include protected under EMX */
#define getcwd _getcwd2
#define chdir _chdir2
#endif

#ifdef vax
#ifdef unix
#define ultrix			/* Assume vax+unix=ultrix */
#endif /* unix */
#endif /* vax */

#ifndef VMS
#ifndef ultrix

#ifdef NeXT
#include <libc.h>		/* NeXT */
#endif /* NeXT */

#else /* ultrix: */

#include <malloc.h>
#include <memory.h>

#endif /* !ultrix */
#else /* VMS: */

#include <unixlib.h>
#if defined(VAXC) && !defined(__DECC)
#define malloc	VAXC$MALLOC_OPT
#define calloc	VAXC$CALLOC_OPT
#define free	VAXC$FREE_OPT
#define cfree	VAXC$CFREE_OPT
#define realloc	VAXC$REALLOC_OPT
#endif /* VAXC && !__DECC */

#endif /* !VMS */

#ifndef NULL
#define NULL ((void *)0)
#endif

#define DeConst(p)   (void *)(intptr_t)(p)

#define isEmpty(s)   ((s) == 0 || *(s) == 0)
#define non_empty(s) !isEmpty(s)

#define NonNull(s) (((s) != 0) ? s : "")
#define NONNULL(s) (((s) != 0) ? s : "(null)")

/* array/table size */
#define	TABLESIZE(v)	(sizeof(v)/sizeof(v[0]))

#define	typecalloc(cast)		(cast *)calloc((size_t)1, sizeof(cast))
#define	typecallocn(cast,ntypes)	(cast *)calloc((size_t)(ntypes),sizeof(cast))

#define typeRealloc(cast,ptr,ntypes)    (cast *)realloc(ptr, (size_t)(ntypes)*sizeof(cast))

#define typeMalloc(cast)                (cast *)malloc(sizeof(cast))
#define typeMallocn(cast,ntypes)        (cast *)malloc((size_t)(ntypes)*sizeof(cast))

/*

OFTEN USED INTEGER MACROS

  Min and Max functions

 */
#ifndef HTMIN
#define HTMIN(a,b) ((a) <= (b) ? (a) : (b))
#define HTMAX(a,b) ((a) >= (b) ? (a) : (b))
#endif
/*

Booleans

 */
/* Note: GOOD and BAD are already defined (differently) on RS6000 aix */
/* #define GOOD(status) ((status)38;1)   VMS style status: test bit 0         */
/* #define BAD(status)  (!GOOD(status))  Bit 0 set if OK, otherwise clear   */

#ifndef _WINDOWS
#ifndef BOOLEAN_DEFINED
typedef char BOOLEAN;		/* Logical value */

#ifndef CURSES
#ifndef TRUE
#define TRUE    (BOOLEAN)1
#define FALSE   (BOOLEAN)0
#endif
#endif /*  CURSES  */
#endif /*  BOOLEAN_DEFINED */
#define BOOLEAN_DEFINED
#endif /* _WINDOWS */

#if defined(_MSC_VER) && (_MSC_VER >= 1300)
/* it declares BOOL/BOOLEAN as BYTE/int */
#else
#ifndef BOOL
#define BOOL BOOLEAN
#endif
#endif

#ifndef YES
#define YES (BOOLEAN)1
#define NO (BOOLEAN)0
#endif

#define STRING1PTR const char *
#define STRING2PTR const char * const *

extern BOOL LYOutOfMemory;	/* Declared in LYexit.c - FM */

#define TCP_PORT 80		/* Allocated to http by Jon Postel/ISI 24-Jan-92 */
#define OLD_TCP_PORT 2784	/* Try the old one if no answer on 80 */
#define DNP_OBJ 80		/* This one doesn't look busy, but we must check */
			/* That one was for decnet */

/*      Inline Function WHITE: Is character c white space? */
/*      For speed, include all control characters */

#define WHITE(c) ((UCH(TOASCII(c))) <= 32)

/*     Inline Function LYIsASCII: Is character c a traditional ASCII
 *     character (i.e. <128) after converting from host character set.  */

#define LYIsASCII(c) (TOASCII(UCH(c)) < 128)

/*

Success (>=0) and failure (<0) codes

Some of the values are chosen to be HTTP-like, but status return values
are generally not the response status from any specific protocol.

 */

#define HT_PARSER_OTHER_CONTENT  701	/* tells SGML to change content model */
#define HT_PARSER_REOPEN_ELT     700	/* tells SGML parser to keep tag open */
#define HT_REDIRECTING           399
#define HT_PARTIAL_CONTENT       206	/* Partial Content */
#define HT_LOADED                200	/* Instead of a socket */

#define HT_OK                      0	/* Generic success */

#define HT_ERROR                  -1	/* Generic failure */
#define HT_CANNOT_TRANSLATE       -4
#define HT_BAD_EOF               -12	/* Premature EOF */
#define HT_NO_CONNECTION         -99	/* ERR no connection available - */
#define HT_NO_DATA              -204	/* OK but no data was loaded - */
					/* possibly other app started or forked */
#define HT_NO_ACCESS            -401	/* Access not available */
#define HT_FORBIDDEN            -403	/* Access forbidden */
#define HT_NOT_ACCEPTABLE       -406	/* Not Acceptable */
#define HT_H_ERRNO_VALID        -800	/* see h_errno for resolver error */
#define HT_INTERNAL             -900	/* Weird -- should never happen. */
#define HT_INTERRUPTED        -29998
#define HT_NOT_LOADED         -29999

#ifndef va_arg
#  include <stdarg.h>
#endif

#define LYva_start(ap,format) va_start(ap,format)

/*
 * GCC can be told that some functions are like printf (and do type-checking on
 * their parameters).
 */
#ifndef GCC_PRINTFLIKE
#if defined(GCC_PRINTF) && !defined(printf) && !defined(HAVE_LIBUTF8_H)
#define GCC_PRINTFLIKE(fmt,var) __attribute__((format(printf,fmt,var)))
#else
#define GCC_PRINTFLIKE(fmt,var)	/*nothing */
#endif
#endif

#include <HTString.h>		/* String utilities */

/*

Out Of Memory checking for malloc() return:

 */
#ifndef __FILE__
#define __FILE__ ""
#define __LINE__ ""
#endif

#include <LYexit.h>

/*
 * Upper- and Lowercase macros
 *
 * The problem here is that toupper(x) is not defined officially unless
 * isupper(x) is.  These macros are CERTAINLY needed on #if defined(pyr) ||
 * define(mips) or BDSI platforms.  For safefy, we make them mandatory.
 *
 * Note: Pyramid and Mips can't uppercase non-alpha.
 */
#include <ctype.h>
#include <string.h>

#ifndef TOLOWER

#ifdef USE_ASCII_CTYPES

#define TOLOWER(c) ascii_tolower(UCH(c))
#define TOUPPER(c) ascii_toupper(UCH(c))
#define ISUPPER(c) ascii_isupper(UCH(c))

#else

#define TOLOWER(c) (isupper(UCH(c)) ? tolower(UCH(c)) : UCH(c))
#define TOUPPER(c) (islower(UCH(c)) ? toupper(UCH(c)) : UCH(c))
#define ISUPPER(c) (isupper(UCH(c)))

#endif

#endif /* TOLOWER */

#define FREE(x)    {if (x != 0) {free((char *)x); x = NULL;}}

/*

The local equivalents of CR and LF

   We can check for these after net ascii text has been converted to the local
   representation.  Similarly, we include them in strings to be sent as net ascii after
   translation.

 */
#define LF   FROMASCII('\012')	/* ASCII line feed LOCAL EQUIVALENT */
#define CR   FROMASCII('\015')	/* Will be converted to ^M for transmission */

/*
 * Debug message control.
 */
#ifdef NO_LYNX_TRACE
#define WWW_TraceFlag   0
#define WWW_TraceMask   0
#define LYTraceLogFP    0
#else
extern BOOLEAN WWW_TraceFlag;
extern int WWW_TraceMask;
#endif

#define TRACE           (WWW_TraceFlag)
#define TRACE_bit(n)    (TRACE && (WWW_TraceMask & (1 << n)) != 0)
#define TRACE_SGML      (TRACE_bit(0))
#define TRACE_STYLE     (TRACE_bit(1))
#define TRACE_TRST      (TRACE_bit(2))
#define TRACE_CFG       (TRACE_bit(3))
#define TRACE_BSTRING   (TRACE_bit(4))
#define TRACE_COOKIES   (TRACE_bit(5))
#define TRACE_CHARSETS  (TRACE_bit(6))
#define TRACE_GRIDTEXT  (TRACE_bit(7))
#define TRACE_TIMING    (TRACE_bit(8))
#define TRACE_HTPARSE   (TRACE_bit(9))

/*
 * Get printing/scanning formats.
 */
#if defined(HAVE_INTTYPES_H)
#include <inttypes.h>
#endif

#define DigitsOf(type)  (int)((sizeof(type)*8)/3)

/*
 * Printing/scanning-formats for "off_t", as well as cast needed to fit.
 */
#if defined(HAVE_LONG_LONG) && defined(HAVE_INTTYPES_H) && defined(SIZEOF_OFF_T)
#if (SIZEOF_OFF_T == 8) && defined(PRId64) && defined(SCNd64)

#define PRI_off_t	PRId64
#define SCN_off_t	SCNd64
#define CAST_off_t(n)	(int64_t)(n)

#elif (SIZEOF_OFF_T == 4) && defined(PRId32)

#define PRI_off_t	PRId32
#define SCN_off_t	SCNd32

#if (SIZEOF_INT == 4)
#define CAST_off_t(n)	(int)(n)
#elif (SIZEOF_LONG == 4)
#define CAST_off_t(n)	(long)(n)
#else
#define CAST_off_t(n)	(int32_t)(n)
#endif

#endif
#endif

#ifndef PRI_off_t
#define GUESS_PRI_off_t
#if (SIZEOF_OFF_T == SIZEOF_LONG)
#define PRI_off_t	"ld"
#define SCN_off_t	"ld"
#define CAST_off_t(n)	(long)(n)
#elif defined(HAVE_LONG_LONG)
#define PRI_off_t	"lld"
#define SCN_off_t	"lld"
#define CAST_off_t(n)	(long long)(n)
#else
#define PRI_off_t	"ld"
/* SCN_off_t requires workaround */
#define CAST_off_t(n)	(long)(n)
#endif
#endif

/*
 * MinGW-32 uses only 32-bit DLL, which limits printing.
 */
#if defined(__MINGW32__)
#undef  PRI_off_t
#undef  CAST_off_t
#define PRI_off_t	"ld"
#define CAST_off_t(n)	(long)(n)
#endif

/*
 * Printing-format for "time_t", as well as cast needed to fit.
 */
#if defined(HAVE_LONG_LONG) && defined(HAVE_INTTYPES_H) && defined(SIZEOF_TIME_T)
#if (SIZEOF_TIME_T == 8) && defined(PRId64)

#define PRI_time_t	PRId64
#define SCN_time_t	SCNd64
#define CAST_time_t(n)	(int64_t)(n)

#elif (SIZEOF_TIME_T == 4) && defined(PRId32)

#define PRI_time_t	PRId32
#define SCN_time_t	SCNd32

#if (SIZEOF_INT == 4)
#define CAST_time_t(n)	(int)(n)
#elif (SIZEOF_LONG == 4)
#define CAST_time_t(n)	(long)(n)
#else
#define CAST_time_t(n)	(int32_t)(n)
#endif

#endif
#endif

#ifndef PRI_time_t
#if defined(HAVE_LONG_LONG) && (SIZEOF_TIME_T > SIZEOF_LONG)
#define PRI_time_t	"lld"
#define SCN_time_t	"lld"
#define CAST_time_t(n)	(long long)(n)
#else
#define PRI_time_t	"ld"
#define SCN_time_t	"ld"
#define CAST_time_t(n)	(long)(n)
#endif
#endif

/*
 * Printing-format for "UCode_t".
 */
#define PRI_UCode_t	"lX"
#define CAST_UCode_t(n)	(unsigned long)(n)

/*
 * Verbose-tracing.
 */
#if defined(USE_VERTRACE) && !defined(LY_TRACELINE)
#define LY_TRACELINE __LINE__
#endif

#if defined(LY_TRACELINE)
#define LY_SHOWWHERE fprintf( tfp, "%s: %d: ", __FILE__, LY_TRACELINE ),
#else
#define LY_SHOWWHERE		/* nothing */
#endif

#define CTRACE(p)         ((void)((TRACE) && ( LY_SHOWWHERE fprintf p )))
#define CTRACE2(m,p)      ((void)((m)     && ( LY_SHOWWHERE fprintf p )))
#define tfp TraceFP()
#define CTRACE_SLEEP(secs) if (TRACE && LYTraceLogFP == 0) sleep((unsigned)secs)
#define CTRACE_FLUSH(fp)   if (TRACE) fflush(fp)

#include <www_tcp.h>

/*
 * We force this include-ordering since socks.h contains redefinitions of
 * functions that probably are prototyped via other includes.  The socks.h
 * definitions have to be included everywhere, since they're making wrappers
 * for the stdio functions as well as the network functions.
 */
#if defined(USE_SOCKS5)
#define SOCKS4TO5		/* turn on the Rxxxx definitions used in Lynx */
#include <socks.h>

/*
 * The AIX- and SOCKS4-specific definitions in socks.h are inconsistent.
 * Repair them so they're consistent (and usable).
 */
#if defined(_AIX) && !defined(USE_SOCKS4_PREFIX)
#undef  Raccept
#define Raccept       accept
#undef  Rgetsockname
#define Rgetsockname  getsockname
#undef  Rgetpeername
#define Rgetpeername  getpeername
#endif

/*
 * Workaround for order-of-evaluation problem with gcc and socks5 headers
 * which breaks the Rxxxx names by attaching the prefix twice:
 */
#ifdef INCLUDE_PROTOTYPES
#undef  Raccept
#undef  Rbind
#undef  Rconnect
#undef  Rlisten
#undef  Rselect
#undef  Rgetpeername
#undef  Rgetsockname
#define Raccept       accept
#define Rbind         bind
#define Rconnect      connect
#define Rgetpeername  getpeername
#define Rgetsockname  getsockname
#define Rlisten       listen
#define Rselect       select
#endif

#elif defined(SOCKS)
#include <socks.h>
#endif /* USE_SOCKS5 */

#ifdef USE_SSL

#define free_func free__func

#ifdef USE_OPENSSL_INCL
#include <openssl/ssl.h>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/err.h>

#else

#if defined(USE_GNUTLS_FUNCS)
#include <tidy_tls.h>
#define USE_GNUTLS_INCL 1	/* do this for the ".c" ifdef's */
#elif defined(USE_GNUTLS_INCL)
#include <gnutls/openssl.h>
/*
 * GNUTLS's implementation of OpenSSL is very incomplete and rudimentary.
 * For a start, let's make it compile (TD - 2003/4/13).
 */
#ifndef SSL_VERIFY_PEER
#define SSL_VERIFY_PEER			0x01
#endif
#else

#ifdef USE_NSS_COMPAT_INCL
#include <nss_compat_ossl/nss_compat_ossl.h>

#else /* assume SSLeay */
#include <ssl.h>
#include <crypto.h>
#include <rand.h>
#include <err.h>
#endif
#endif
#endif /* USE_OPENSSL_INCL */

#undef free_func
#endif /* USE_SSL */

#ifdef HAVE_BSD_STDLIB_H
#include <bsd/stdlib.h>		/* prototype for arc4random.h */
#elif defined(HAVE_BSD_RANDOM_H)
#include <bsd/random.h>		/* prototype for arc4random.h */
#endif

#ifdef HAVE_LIBDMALLOC
#include <dmalloc.h>		/* Gray Watson's library */
#define show_alloc() dmalloc_log_unfreed()
#endif

#ifdef HAVE_LIBDBMALLOC
#include <dbmalloc.h>		/* Conor Cahill's library */
#define show_alloc() malloc_dump(fileno(stderr))
#endif

#ifndef show_alloc
#define show_alloc()		/* nothing */
#endif

#include <userdefs.h>

#ifdef __cplusplus
extern "C" {
#endif
#ifndef TOLOWER
#ifdef USE_ASCII_CTYPES
    extern int ascii_toupper(int);
    extern int ascii_tolower(int);
    extern int ascii_isupper(int);
#endif
#endif

    extern FILE *TraceFP(void);

    extern char *HTSkipToAt(char *host, int *gen_delims);
    extern void strip_userid(char *host, int warn);

#ifdef USE_SSL
    extern SSL *HTGetSSLHandle(void);
    extern void HTSSLInitPRNG(void);
    extern int HTGetSSLCharacter(void *handle);
#endif				/* USE_SSL */

#ifdef __cplusplus
}
#endif
#endif				/* HTUTILS_H */
d='n253' href='#n253'>253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
  
                                                          





















                                                                         



                                                

                     
                                               
                                              

















































































































                                                                              
                                                                                      



                                                                         
                                             
















                                                                    
                                                                





















                                                                               
                                              

                             

                                              



                                                
                                      














































                                                                            
                                          





















                                                                            
                                      




                        
                                           
                    
                       


                                                              




                                          
















                                                                                































                                                                                    
                                                                                


                                                                                     
                                     
                                     




                                                           
                       
                                 
         
     

                 











                                                                          

                                                                        



























































                                                                                     




























































































                                                                              







                                                                               
                                   
 

                                                                  
                                    
                 













































                                                                           
                                          





                                                                         


































































                                                                             

                              


                                           
                                   

















                                                                      
                                                                  





                                                                   
                                        

                                      

                                       
             




                                                                


                                                                    
                                    


                                              
                                    






                                                      

                                        





                                                         
                                                          
































                                                                              
                                         

































                                                                 
                                                     
















































                                                                                





















                                                                            
                                                                                
   
                                              
 

                                         
                                             
                           





                                 
            













                                            
                                            











































                                                                        
                                                                       








                                                                  

                 
                                    

                                                     
                                 




                                                                           
         




                                               
                 


                               

                 










                                                                              

         

                                                          





























































                                                                              



























































                                                                              








































                                                                                








































                                                                            
































































































                                                                                 
                                                                                  





































































                                                                              


























                                                                         
/*
 * $LynxId: HTParse.c,v 1.98 2021/07/27 21:29:49 tom Exp $
 *
 *		Parse HyperText Document Address		HTParse.c
 *		================================
 */

#include <HTUtils.h>
#include <HTParse.h>

#include <LYUtils.h>
#include <LYLeaks.h>
#include <LYStrings.h>
#include <LYCharUtils.h>
#include <LYGlobalDefs.h>

#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#else
#ifdef __MINGW32__
#include <malloc.h>
#endif /* __MINGW32__ */
#endif

#ifdef USE_IDN2
#include <idn2.h>
#define FreeIdna(out)             idn2_free(out)
#elif defined(USE_IDNA)
#include <idna.h>
#include <idn-free.h>
#define FreeIdna(out)             idn_free(out)
#define IDN2_OK                   IDNA_SUCCESS
#endif

#define HEX_ESCAPE '%'

struct struct_parts {
    char *access;
    char *host;
    char *absolute;
    char *relative;
    char *search;		/* treated normally as part of path */
    char *anchor;
};

#if 0				/* for debugging */
static void show_parts(const char *name, struct struct_parts *parts, int line)
{
    if (TRACE) {
	CTRACE((tfp, "struct_parts(%s) %s@%d\n", name, __FILE__, line));
	CTRACE((tfp, "   access   '%s'\n", NONNULL(parts->access)));
	CTRACE((tfp, "   host     '%s'\n", NONNULL(parts->host)));
	CTRACE((tfp, "   absolute '%s'\n", NONNULL(parts->absolute)));
	CTRACE((tfp, "   relative '%s'\n", NONNULL(parts->relative)));
	CTRACE((tfp, "   search   '%s'\n", NONNULL(parts->search)));
	CTRACE((tfp, "   anchor   '%s'\n", NONNULL(parts->anchor)));
    }
}
#define SHOW_PARTS(name) show_parts(#name, &name, __LINE__)
#else
#define SHOW_PARTS(name)	/* nothing */
#endif

/*	Strip white space off a string.				HTStrip()
 *	-------------------------------
 *
 * On exit,
 *	Return value points to first non-white character, or to 0 if none.
 *	All trailing white space is OVERWRITTEN with zero.
 */
char *HTStrip(char *s)
{
#define SPACE(c) ((c == ' ') || (c == '\t') || (c == '\n'))
    char *p;

    for (p = s; *p; p++) {	/* Find end of string */
	;
    }
    for (p--; p >= s; p--) {
	if (SPACE(*p))
	    *p = '\0';		/* Zap trailing blanks */
	else
	    break;
    }
    while (SPACE(*s))
	s++;			/* Strip leading blanks */
    return s;
}

/*	Scan a filename for its constituents.			scan()
 *	-------------------------------------
 *
 * On entry,
 *	name	points to a document name which may be incomplete.
 * On exit,
 *	absolute or relative may be nonzero (but not both).
 *	host, anchor and access may be nonzero if they were specified.
 *	Any which are nonzero point to zero terminated strings.
 */
static void scan(char *name,
		 struct struct_parts *parts)
{
    char *after_access;
    char *p;

    parts->access = NULL;
    parts->host = NULL;
    parts->absolute = NULL;
    parts->relative = NULL;
    parts->search = NULL;	/* normally not used - kw */
    parts->anchor = NULL;

    /*
     * Scan left-to-right for a scheme (access).
     */
    after_access = name;
    for (p = name; *p; p++) {
	if (*p == ':') {
	    *p = '\0';
	    parts->access = name;	/* Access name has been specified */
	    after_access = (p + 1);
	    break;
	}
	if (*p == '/' || *p == '#' || *p == ';' || *p == '?')
	    break;
    }

    /*
     * Scan left-to-right for a fragment (anchor).
     */
    for (p = after_access; *p; p++) {
	if (*p == '#') {
	    parts->anchor = (p + 1);
	    *p = '\0';		/* terminate the rest */
	    break;		/* leave things after first # alone - kw */
	}
    }

    /*
     * Scan left-to-right for a host or absolute path.
     */
    p = after_access;
    if (*p == '/') {
	if (p[1] == '/') {
	    parts->host = (p + 2);	/* host has been specified    */
	    *p = '\0';		/* Terminate access           */
	    p = StrChr(parts->host, '/');	/* look for end of host name if any */
	    if (p != NULL) {
		*p = '\0';	/* Terminate host */
		parts->absolute = (p + 1);	/* Root has been found */
	    } else {
		p = StrChr(parts->host, '?');
		if (p != NULL) {
		    *p = '\0';	/* Terminate host */
		    parts->search = (p + 1);
		}
	    }
	} else {
	    parts->absolute = (p + 1);	/* Root found but no host */
	}
    } else {
	parts->relative = (*after_access) ?
	    after_access : NULL;	/* NULL for "" */
    }

    /*
     * Check schemes that commonly have unescaped hashes.
     */
    if (parts->access && parts->anchor &&
    /* optimize */ StrChr("lnsdLNSD", *parts->access) != NULL) {
	if ((!parts->host && strcasecomp(parts->access, "lynxcgi")) ||
	    !strcasecomp(parts->access, "nntp") ||
	    !strcasecomp(parts->access, "snews") ||
	    !strcasecomp(parts->access, "news") ||
	    !strcasecomp(parts->access, "data")) {
	    /*
	     * Access specified but no host and not a lynxcgi URL, so the
	     * anchor may not really be one, e.g., news:j462#36487@foo.bar, or
	     * it's an nntp or snews URL, or news URL with a host.  Restore the
	     * '#' in the address.
	     */
	    /* but only if we have found a path component of which this will
	     * become part. - kw  */
	    if (parts->relative || parts->absolute) {
		*(parts->anchor - 1) = '#';
		parts->anchor = NULL;
	    }
	}
    }
}				/*scan */

#if defined(HAVE_ALLOCA) && !defined(LY_FIND_LEAKS)
#define LYalloca(x)        alloca((size_t)(x))
#define LYalloca_free(x)   {}
#else
#define LYalloca(x)        malloc((size_t)(x))
#define LYalloca_free(x)   free((void *)(x))
#endif

static char *strchr_or_end(char *string, int ch)
{
    char *result = StrChr(string, ch);

    if (result == 0) {
	result = string + strlen(string);
    }
    return result;
}

/*
 * Given a host specification that may end with a port number, e.g.,
 *	foobar:123
 * point to the ':' which begins the ":port" to make it simple to handle the
 * substring.
 *
 * If no port is found (or a syntax error), return null.
 */
char *HTParsePort(char *host, int *portp)
{
    int brackets = 0;
    char *result = NULL;

    *portp = 0;
    if (host != NULL) {
	while (*host != '\0' && result == 0) {
	    switch (*host++) {
	    case ':':
		if (brackets == 0 && isdigit(UCH(*host))) {
		    char *next = NULL;

		    *portp = (int) strtol(host, &next, 10);
		    if (next != 0 && next != host && *next == '\0') {
			result = (host - 1);
			CTRACE((tfp, "HTParsePort %d\n", *portp));
		    }
		}
		break;
	    case '[':		/* for ipv6 */
		++brackets;
		break;
	    case ']':		/* for ipv6 */
		--brackets;
		break;
	    }
	}
    }
    return result;
}

#if defined(USE_IDNA) || defined(USE_IDN2)
static int hex_decode(int ch)
{
    int result = -1;

    if (ch >= '0' && ch <= '9')
	result = (ch - '0');
    else if (ch >= 'a' && ch <= 'f')
	result = (ch - 'a') + 10;
    else if (ch >= 'A' && ch <= 'F')
	result = (ch - 'A') + 10;
    return result;
}

/*
 * Convert in-place the given hostname to IDNA form.  That requires up to 64
 * characters, and we've allowed for that, with MIN_PARSE.
 */
static void convert_to_idna(char *host)
{
    size_t length = strlen(host);
    char *endhost = host + length;
    char *buffer = malloc(length + 1);
    char *params = malloc(length + 1);
    char *output = NULL;
    char *src, *dst;
    int code;
    int hi, lo;

    if (buffer != NULL && params != NULL) {
	code = TRUE;
	*params = '\0';
	for (dst = buffer, src = host; src < endhost; ++dst) {
	    int ch = *src++;

	    if (RFC_3986_GEN_DELIMS(ch)) {
		strcpy(params, src - 1);
		*dst = '\0';
		break;
	    } else if (ch == HEX_ESCAPE) {
		if ((src + 1) < endhost
		    && (hi = hex_decode(src[0])) >= 0
		    && (lo = hex_decode(src[1])) >= 0) {

		    *dst = (char) ((hi << 4) | lo);
		    src += 2;
		} else {
		    CTRACE((tfp, "convert_to_idna: `%s' is malformed\n", host));
		    code = FALSE;
		    break;
		}
	    } else {
		*dst = (char) ch;
	    }
	}
	if (code) {
	    *dst = '\0';
#ifdef USE_IDN2
#if (!defined(IDN2_VERSION_NUMBER) || IDN2_VERSION_NUMBER < 0x02000003)
	    /*
	     * Older libidn2 mishandles STD3, stripping underscores.
	     */
	    if (strchr(buffer, '_') != NULL) {
		code = -1;
	    } else
#endif
		switch (LYidnaMode) {
		case LYidna2003:
		    code = idn2_to_ascii_8z(buffer, &output, IDN2_TRANSITIONAL);
		    break;
		case LYidna2008:
		    /* IDNA2008 rules without the TR46 amendments */
		    code = idn2_to_ascii_8z(buffer, &output, 0);
		    break;
		case LYidnaTR46:
		    code = idn2_to_ascii_8z(buffer, &output, IDN2_NONTRANSITIONAL
					    | IDN2_NFC_INPUT);
		    break;
		case LYidnaCompat:
		    /* IDNA2008 */
		    code = idn2_to_ascii_8z(buffer, &output, IDN2_NONTRANSITIONAL
					    | IDN2_NFC_INPUT);
		    if (code == IDN2_DISALLOWED) {
			/* IDNA2003 - compatible */
			code = idn2_to_ascii_8z(buffer, &output, IDN2_TRANSITIONAL);
		    }
		    break;
		}
#else
	    code = idna_to_ascii_8z(buffer, &output, IDNA_USE_STD3_ASCII_RULES);
#endif
	    if (code == IDN2_OK) {
		CTRACE((tfp, "convert_to_idna: `%s' -> `%s': OK\n", buffer, output));
		strcpy(host, output);
		strcat(host, params);
	    } else {
		CTRACE((tfp, "convert_to_idna: `%s': %s\n",
			buffer,
			idna_strerror((Idna_rc) code)));
	    }
	    if (output)
		FreeIdna(output);
	}
    }
    free(buffer);
    free(params);
}
#define MIN_PARSE 80
#else
#define MIN_PARSE 8
#endif

/*	Parse a Name relative to another name.			HTParse()
 *	--------------------------------------
 *
 *	This returns those parts of a name which are given (and requested)
 *	substituting bits from the related name where necessary.
 *
 *	Originally based on RFC 1808, some details in RFC 3986 are used.
 *
 * On entry,
 *	aName		A filename given
 *	relatedName	A name relative to which aName is to be parsed
 *	wanted		A mask for the bits which are wanted.
 *
 * On exit,
 *     returns         A pointer to a malloc'd string which MUST BE FREED
 */
char *HTParse(const char *aName,
	      const char *relatedName,
	      int wanted)
{
    char *result = NULL;
    char *tail = NULL;		/* a pointer to the end of the 'result' string */
    char *return_value = NULL;
    size_t len, len1, len2;
    size_t need;
    char *name = NULL;
    char *rel = NULL;
    char *p, *q;
    char *acc_method;
    struct struct_parts given, related;

    CTRACE((tfp, "HTParse: aName:`%s'\n", aName));
    CTRACE((tfp, "   relatedName:`%s'\n", relatedName));

    if (wanted & (PARSE_STRICTPATH | PARSE_QUERY)) {	/* if detail wanted... */
	if ((wanted & (PARSE_STRICTPATH | PARSE_QUERY))
	    == (PARSE_STRICTPATH | PARSE_QUERY))	/* if strictpath AND query */
	    wanted |= PARSE_PATH;	/* then treat as if PARSE_PATH wanted */
	if (wanted & PARSE_PATH)	/* if PARSE_PATH wanted */
	    wanted &= ~(PARSE_STRICTPATH | PARSE_QUERY);	/* ignore details */
    }
/* *INDENT-OFF* */
    CTRACE((tfp, "   want:%s%s%s%s%s%s%s\n",
	    wanted & PARSE_PUNCTUATION ? " punc"   : "",
	    wanted & PARSE_ANCHOR      ? " anchor" : "",
	    wanted & PARSE_PATH        ? " path"   : "",
	    wanted & PARSE_HOST        ? " host"   : "",
	    wanted & PARSE_ACCESS      ? " access" : "",
	    wanted & PARSE_STRICTPATH  ? " PATH"   : "",
	    wanted & PARSE_QUERY       ? " QUERY"  : ""));
/* *INDENT-ON* */

    /*
     * Allocate the temporary string. Optimized.
     */
    len1 = strlen(aName) + 1;
    len2 = strlen(relatedName) + 1;
    len = len1 + len2 + MIN_PARSE;	/* Lots of space: more than enough */

    need = (len * 2 + len1 + len2);
    if (need > (size_t) max_uri_size ||
	(int) need < (int) len1 ||
	(int) need < (int) len2)
	return StrAllocCopy(return_value, "");

    result = tail = (char *) LYalloca(need);
    if (result == NULL) {
	outofmem(__FILE__, "HTParse");
    }
    *result = '\0';
    name = result + len;
    rel = name + len1;

    /*
     * Make working copy of the input string to cut up.
     */
    MemCpy(name, aName, len1);

    /*
     * Cut up the string into URL fields.
     */
    scan(name, &given);
    SHOW_PARTS(given);

    /*
     * Now related string.
     */
    if ((given.access && given.host && given.absolute) || !*relatedName) {
	/*
	 * Inherit nothing!
	 */
	related.access = NULL;
	related.host = NULL;
	related.absolute = NULL;
	related.relative = NULL;
	related.search = NULL;
	related.anchor = NULL;
    } else {
	MemCpy(rel, relatedName, len2);
	scan(rel, &related);
    }
    SHOW_PARTS(related);

    /*
     * Handle the scheme (access) field.
     */
    if (given.access && given.host && !given.relative && !given.absolute) {
	if (!strcmp(given.access, "http") ||
	    !strcmp(given.access, "https") ||
	    !strcmp(given.access, "ftp")) {

	    /*
	     * Assume root.
	     */
	    given.absolute = empty_string;
	}
    }
    acc_method = given.access ? given.access : related.access;
    if (wanted & PARSE_ACCESS) {
	if (acc_method) {
	    strcpy(tail, acc_method);
	    tail += strlen(tail);
	    if (wanted & PARSE_PUNCTUATION) {
		*tail++ = ':';
		*tail = '\0';
	    }
	}
    }

    /*
     * If different schemes, inherit nothing.
     *
     * We'll try complying with RFC 1808 and the Fielding draft, and inherit
     * nothing if both schemes are given, rather than only when they differ,
     * except for file URLs - FM
     *
     * After trying it for a while, it's still premature, IHMO, to go along
     * with it, so this is back to inheriting for identical schemes whether or
     * not they are "file".  If you want to try it again yourself, uncomment
     * the strcasecomp() below.  - FM
     */
    if ((given.access && related.access) &&
	(			/* strcasecomp(given.access, "file") || */
	    strcmp(given.access, related.access))) {
	related.host = NULL;
	related.absolute = NULL;
	related.relative = NULL;
	related.search = NULL;
	related.anchor = NULL;
    }

    /*
     * Handle the host field.
     */
    if (wanted & PARSE_HOST) {
	if (given.host || related.host) {
	    if (wanted & PARSE_PUNCTUATION) {
		*tail++ = '/';
		*tail++ = '/';
	    }
	    strcpy(tail, given.host ? given.host : related.host);
	    /*
	     * Ignore default port numbers, and trailing dots on FQDNs, which
	     * will only cause identical addresses to look different.  (related
	     * is already a clean url).
	     */
	    {
		char *p2, *h;
		int portnumber;
		int gen_delims = 0;

		if ((p2 = HTSkipToAt(result, &gen_delims)) != NULL
		    && gen_delims == 0) {
		    tail = (p2 + 1);
		}
		p2 = HTParsePort(result, &portnumber);
		if (p2 != NULL && acc_method != NULL) {
		    /*
		     * Port specified.
		     */
#define ACC_METHOD(a,b) (!strcmp(acc_method, a) && (portnumber == b))
		    if (ACC_METHOD("http", 80) ||
			ACC_METHOD("https", 443) ||
			ACC_METHOD("gopher", 70) ||
			ACC_METHOD("ftp", 21) ||
			ACC_METHOD("wais", 210) ||
			ACC_METHOD("nntp", 119) ||
			ACC_METHOD("news", 119) ||
			ACC_METHOD("newspost", 119) ||
			ACC_METHOD("newsreply", 119) ||
			ACC_METHOD("snews", 563) ||
			ACC_METHOD("snewspost", 563) ||
			ACC_METHOD("snewsreply", 563) ||
			ACC_METHOD("finger", 79) ||
			ACC_METHOD("telnet", 23) ||
			ACC_METHOD("tn3270", 23) ||
			ACC_METHOD("rlogin", 513) ||
			ACC_METHOD("cso", 105))
			*p2 = '\0';	/* It is the default: ignore it */
		}
		if (p2 == NULL) {
		    int len3 = (int) strlen(tail);

		    if (len3 > 0) {
			h = tail + len3 - 1;	/* last char of hostname */
			if (*h == '.')
			    *h = '\0';	/* chop final . */
		    }
		} else if (p2 != result) {
		    h = p2;
		    h--;	/* End of hostname */
		    if (*h == '.') {
			/*
			 * Slide p2 over h.
			 */
			while (*p2 != '\0')
			    *h++ = *p2++;
			*h = '\0';	/* terminate */
		    }
		}
	    }
#if defined(USE_IDNA) || defined(USE_IDN2)
	    /*
	     * Depending on locale-support, we could have a literal UTF-8
	     * string as a host name, or a URL-encoded form of that.
	     */
	    convert_to_idna(tail);
#endif
	}
    }

    /*
     * Trim any blanks from the result so far - there's no excuse for blanks
     * in a hostname.  Also update the tail here.
     */
    tail = LYRemoveBlanks(result);

    /*
     * If host in given or related was ended directly with a '?' (no slash),
     * fake the search part into absolute.  This is the only case search is
     * returned from scan.  A host must have been present.  this restores the
     * '?' at which the host part had been truncated in scan, we have to do
     * this after host part handling is done.  - kw
     */
    if (given.search && *(given.search - 1) == '\0') {
	given.absolute = given.search - 1;
	given.absolute[0] = '?';
    } else if (related.search && !related.absolute &&
	       *(related.search - 1) == '\0') {
	related.absolute = related.search - 1;
	related.absolute[0] = '?';
    }

    /*
     * If different hosts, inherit no path.
     */
    if (given.host && related.host)
	if (strcmp(given.host, related.host) != 0) {
	    related.absolute = NULL;
	    related.relative = NULL;
	    related.anchor = NULL;
	}

    /*
     * Handle the path.
     */
    if (wanted & (PARSE_PATH | PARSE_STRICTPATH | PARSE_QUERY)) {
	int want_detail = (wanted & (PARSE_STRICTPATH | PARSE_QUERY));

	if (acc_method && !given.absolute && given.relative) {
	    /*
	     * Treat all given nntp or snews paths, or given paths for news
	     * URLs with a host, as absolute.
	     */
	    switch (*acc_method) {
	    case 'N':
	    case 'n':
		if (!strcasecomp(acc_method, "nntp") ||
		    (!strcasecomp(acc_method, "news") &&
		     !strncasecomp(result, "news://", 7))) {
		    given.absolute = given.relative;
		    given.relative = NULL;
		}
		break;
	    case 'S':
	    case 's':
		if (!strcasecomp(acc_method, "snews")) {
		    given.absolute = given.relative;
		    given.relative = NULL;
		}
		break;
	    }
	}

	if (given.absolute) {	/* All is given */
	    char *base = tail;

	    if (wanted & PARSE_PUNCTUATION)
		*tail++ = '/';
	    strcpy(tail, given.absolute);
	    HTSimplify(base, TRUE);
	    CTRACE((tfp, "HTParse: (ABS)\n"));
	} else if (related.absolute) {	/* Adopt path not name */
	    char *base = tail;

	    *tail++ = '/';
	    strcpy(tail, related.absolute);
	    if (given.relative) {
		/* RFC 1808 part 4 step 5 (if URL path is empty) */
		/* a) if given has params, add/replace that */
		if (given.relative[0] == ';') {
		    strcpy(strchr_or_end(tail, ';'), given.relative);
		}
		/* b) if given has query, add/replace that */
		else if (given.relative[0] == '?') {
		    strcpy(strchr_or_end(tail, '?'), given.relative);
		}
		/* otherwise fall through to RFC 1808 part 4 step 6 */
		else {
		    p = StrChr(tail, '?');	/* Search part? */
		    if (p == NULL)
			p = (tail + strlen(tail) - 1);
		    for (; *p != '/'; p--) ;	/* last / */
		    p[1] = '\0';	/* Remove filename */
		    strcat(p, given.relative);	/* Add given one */
		}
		HTSimplify(base, FALSE);
		if (*base == '\0')
		    strcpy(base, "/");
	    } else {
		HTSimplify(base, TRUE);
	    }
	    if (base[0] == '/' && base[1] == '/') {
		char *pz;

		for (pz = base; (pz[0] = pz[1]) != '\0'; ++pz) ;
	    }
	    CTRACE((tfp, "HTParse: (Related-ABS)\n"));
	} else if (given.relative) {
	    strcpy(tail, given.relative);	/* what we've got */
	    HTSimplify(tail, FALSE);
	    CTRACE((tfp, "HTParse: (REL)\n"));
	} else if (related.relative) {
	    strcpy(tail, related.relative);
	    HTSimplify(tail, FALSE);
	    CTRACE((tfp, "HTParse: (Related-REL)\n"));
	} else {		/* No inheritance */
	    if (!isLYNXCGI(aName) &&
		!isLYNXEXEC(aName) &&
		!isLYNXPROG(aName)) {
		*tail++ = '/';
		*tail = '\0';
	    } else {
		HTSimplify(tail, FALSE);
	    }
	    if (!strcmp(result, "news:/"))
		result[5] = '*';
	    CTRACE((tfp, "HTParse: (No inheritance)\n"));
	}
	if (want_detail) {
	    p = StrChr(tail, '?');	/* Search part? */
	    if (p) {
		if (PARSE_STRICTPATH) {
		    *p = '\0';
		} else {
		    if (!(wanted & PARSE_PUNCTUATION))
			p++;
		    do {
			*tail++ = *p;
		    } while (*p++);
		}
	    } else {
		if (wanted & PARSE_QUERY)
		    *tail = '\0';
	    }
	}
    }

    /*
     * Handle the fragment (anchor).  Never inherit.
     */
    if (wanted & PARSE_ANCHOR) {
	if (given.anchor && *given.anchor) {
	    tail += strlen(tail);
	    if (wanted & PARSE_PUNCTUATION)
		*tail++ = '#';
	    strcpy(tail, given.anchor);
	}
    }

    /*
     * If there are any blanks remaining in the string, escape them as needed.
     * See the discussion in LYLegitimizeHREF() for example.
     */
    if ((p = StrChr(result, ' ')) != 0) {
	switch (is_url(result)) {
	case UNKNOWN_URL_TYPE:
	    CTRACE((tfp, "HTParse:      ignore:`%s'\n", result));
	    break;
	case LYNXEXEC_URL_TYPE:
	case LYNXPROG_URL_TYPE:
	case LYNXCGI_URL_TYPE:
	case LYNXPRINT_URL_TYPE:
	case LYNXHIST_URL_TYPE:
	case LYNXDOWNLOAD_URL_TYPE:
	case LYNXKEYMAP_URL_TYPE:
	case LYNXIMGMAP_URL_TYPE:
	case LYNXCOOKIE_URL_TYPE:
	case LYNXCACHE_URL_TYPE:
	case LYNXDIRED_URL_TYPE:
	case LYNXOPTIONS_URL_TYPE:
	case LYNXCFG_URL_TYPE:
	case LYNXCOMPILE_OPTS_URL_TYPE:
	case LYNXMESSAGES_URL_TYPE:
	    CTRACE((tfp, "HTParse:      spaces:`%s'\n", result));
	    break;
	case NOT_A_URL_TYPE:
	default:
	    CTRACE((tfp, "HTParse:      encode:`%s'\n", result));
	    do {
		q = p + strlen(p) + 2;

		while (q != p + 1) {
		    q[0] = q[-2];
		    --q;
		}
		p[0] = HEX_ESCAPE;
		p[1] = '2';
		p[2] = '0';
	    } while ((p = StrChr(result, ' ')) != 0);
	    break;
	}
    }
    CTRACE((tfp, "HTParse:      result:`%s'\n", result));

    StrAllocCopy(return_value, result);
    LYalloca_free(result);

    /* FIXME: could be optimized using HTParse() internals */
    if (*relatedName &&
	((wanted & PARSE_ALL_WITHOUT_ANCHOR) == PARSE_ALL_WITHOUT_ANCHOR)) {
	/*
	 * Check whether to fill in localhost.  - FM
	 */
	LYFillLocalFileURL(&return_value, relatedName);
	CTRACE((tfp, "pass LYFillLocalFile:`%s'\n", return_value));
    }

    return return_value;	/* exactly the right length */
}

/*	HTParseAnchor(), fast HTParse() specialization
 *	----------------------------------------------
 *
 * On exit,
 *	returns		A pointer within input string (probably to its end '\0')
 */
const char *HTParseAnchor(const char *aName)
{
    const char *p = aName;

    for (; *p && *p != '#'; p++) {
	;
    }
    if (*p == '#') {
	/* the safe way based on HTParse() -
	 * keeping in mind scan() peculiarities on schemes:
	 */
	struct struct_parts given;
	size_t need = ((unsigned) ((p - aName) + (int) strlen(p) + 1));
	char *name;

	if (need > (size_t) max_uri_size) {
	    p += strlen(p);
	} else {
	    name = (char *) LYalloca(need);

	    if (name == NULL) {
		outofmem(__FILE__, "HTParseAnchor");
	    }
	    strcpy(name, aName);
	    scan(name, &given);
	    LYalloca_free(name);

	    p++;		/*next to '#' */
	    if (given.anchor == NULL) {
		for (; *p; p++)	/*scroll to end '\0' */
		    ;
	    }
	}
    }
    return p;
}

/*	Simplify a filename.				HTSimplify()
 *	--------------------
 *
 *  A unix-style file is allowed to contain the sequence xxx/../ which may
 *  be replaced by "" , and the sequence "/./" which may be replaced by "/".
 *  Simplification helps us recognize duplicate filenames.
 *
 *  RFC 3986 section 5.2.4 says to do this whether or not the path was relative.
 */
void HTSimplify(char *filename, BOOL absolute)
{
#define MY_FMT "HTParse HTSimplify\t(%s)"
#ifdef NO_LYNX_TRACE
#define debug_at(at)		/* nothing */
#define atln		"?"
#else
    const char *atln;

#define debug_at(at)	atln = at
#endif
    char *mark;
    char *p;
    size_t limit;

    CTRACE2(TRACE_HTPARSE,
	    (tfp, MY_FMT " %s\n",
	     filename,
	     absolute ? "ABS" : "REL"));

    if (LYIsPathSep(*filename) && !absolute)
	++filename;
    mark = filename;
    limit = strlen(filename);

    for (p = filename; *p; ++p) {
	if (*p == '?' || *p == '#') {
	    limit = (size_t) (p - filename);
	    break;
	}
    }
    while ((limit != 0) && (*filename != '\0')) {
	size_t trim = 0;
	size_t skip = 0;
	size_t last = 0;

	debug_at("?");
	p = filename;
	if (limit >= 2 && !memcmp(p, "./", 2)) {	/* 2A */
	    debug_at("2A");
	    trim = 2;
	} else if (limit >= 3 && !memcmp(p, "../", 3)) {
	    debug_at("2A2");
	    trim = 3;
	} else if (limit >= 3 && !memcmp(p, "/./", 3)) {	/* 2B */
	    debug_at("2B");
	    trim = 2;
	    skip = 1;
	} else if (limit == 2 && !memcmp(p, "/.", 2)) {
	    debug_at("2B2");
	    trim = 1;
	    skip = 1;
	} else if (limit >= 4 && !memcmp(p, "/../", 4)) {	/* 2C */
	    debug_at("2C");
	    trim = 3;
	    skip = 1;
	    last = 1;
	} else if (limit == 3 && !memcmp(p, "/..", 3)) {
	    debug_at("2C2");
	    trim = 2;
	    skip = 1;
	    last = 1;
	} else if (limit == 2 && !memcmp(p, "..", 2)) {		/* 2D */
	    debug_at("2D");
	    trim = 2;
	} else if (limit == 1 && !memcmp(p, ".", 1)) {
	    debug_at("2D2");
	    trim = 1;
	}
	if (trim) {
	    CTRACE2(TRACE_HTPARSE,
		    (tfp, MY_FMT " trim %lu/%lu (%.*s) '%.*s' @%s\n",
		     mark, (unsigned long) trim, (unsigned long) limit,
		     (int) trim, p + skip, (int) limit, p, atln));
	}
	if (last) {
	    char *prior = filename;

	    if (prior != mark) {
		--prior;
		while (prior != mark && *prior != '/') {
		    --prior;
		}
	    }
	    if (prior != filename) {
		trim += (size_t) (filename - prior);
		limit += (size_t) (filename - prior);
		filename = prior;
		CTRACE2(TRACE_HTPARSE,
			(tfp, MY_FMT " TRIM %lu/%lu (%.*s)\n",
			 mark, (unsigned long) trim, (unsigned long) limit,
			 (int) trim, filename + skip));
	    }
	}
	if (trim) {
	    limit -= trim;
	    for (p = filename;; ++p) {
		if ((p[0] = p[trim]) == '\0') {
		    break;
		}
		if (skip) {
		    p[0] = '/';
		    skip = 0;
		}
	    }
	    CTRACE2(TRACE_HTPARSE,
		    (tfp, MY_FMT " loop %lu\n", mark, (unsigned long) limit));
	} else {
	    if (*filename == '/') {
		++filename;
		--limit;
	    }
	    while ((limit != 0) && (*filename != '/')) {
		++filename;
		--limit;
	    }
	}
    }
    CTRACE2(TRACE_HTPARSE, (tfp, MY_FMT " done\n", mark));
#undef MY_FMT
}

/*	Make Relative Name.					HTRelative()
 *	-------------------
 *
 * This function creates and returns a string which gives an expression of
 * one address as related to another.  Where there is no relation, an absolute
 * address is returned.
 *
 *  On entry,
 *	Both names must be absolute, fully qualified names of nodes
 *	(no anchor bits)
 *
 *  On exit,
 *	The return result points to a newly allocated name which, if
 *	parsed by HTParse relative to relatedName, will yield aName.
 *	The caller is responsible for freeing the resulting name later.
 *
 */
char *HTRelative(const char *aName,
		 const char *relatedName)
{
    char *result = NULL;
    const char *p = aName;
    const char *q = relatedName;
    const char *after_access = NULL;
    const char *path = NULL;
    const char *last_slash = NULL;
    int slashes = 0;

    for (; *p; p++, q++) {	/* Find extent of match */
	if (*p != *q)
	    break;
	if (*p == ':')
	    after_access = p + 1;
	if (*p == '/') {
	    last_slash = p;
	    slashes++;
	    if (slashes == 3)
		path = p;
	}
    }

    /* q, p point to the first non-matching character or zero */

    if (!after_access) {	/* Different access */
	StrAllocCopy(result, aName);
    } else if (slashes < 3) {	/* Different nodes */
	StrAllocCopy(result, after_access);
    } else if (slashes == 3) {	/* Same node, different path */
	StrAllocCopy(result, path);
    } else {			/* Some path in common */
	unsigned levels = 0;

	for (; *q && (*q != '#'); q++)
	    if (*q == '/')
		levels++;
	result = typecallocn(char, 3 * levels + strlen(last_slash) + 1);

	if (result == NULL)
	    outofmem(__FILE__, "HTRelative");

	result[0] = '\0';
	for (; levels; levels--)
	    strcat(result, "../");
	strcat(result, last_slash + 1);
    }
    CTRACE((tfp,
	    "HTparse: `%s' expressed relative to\n   `%s' is\n   `%s'.\n",
	    aName, relatedName, result));
    return result;
}

#define AlloCopy(next,base,extra) \
	typecallocn(char, ((next - base) + ((int) extra)))

/*	Escape undesirable characters using %			HTEscape()
 *	-------------------------------------
 *
 *	This function takes a pointer to a string in which
 *	some characters may be unacceptable unescaped.
 *	It returns a string which has these characters
 *	represented by a '%' character followed by two hex digits.
 *
 *	Unlike HTUnEscape(), this routine returns a calloc'd string.
 */
/* *INDENT-OFF* */
static const unsigned char isAcceptable[96] =

/*	Bit 0		xalpha		-- see HTFile.h
 *	Bit 1		xpalpha		-- as xalpha but with plus.
 *	Bit 2 ...	path		-- as xpalphas but with /
 */
    /*	 0 1 2 3 4 5 6 7 8 9 A B C D E F */
    {	 0,0,0,0,0,0,0,0,0,0,7,6,0,7,7,4,	/* 2x	!"#$%&'()*+,-./  */
	 7,7,7,7,7,7,7,7,7,7,0,0,0,0,0,0,	/* 3x  0123456789:;<=>?  */
	 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,	/* 4x  @ABCDEFGHIJKLMNO  */
	 7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,7,	/* 5X  PQRSTUVWXYZ[\]^_  */
	 0,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,	/* 6x  `abcdefghijklmno  */
	 7,7,7,7,7,7,7,7,7,7,7,0,0,0,0,0 };	/* 7X  pqrstuvwxyz{|}~	DEL */
/* *INDENT-ON* */

static const char *hex = "0123456789ABCDEF";

#define ACCEPTABLE(a)	( a>=32 && a<128 && ((isAcceptable[a-32]) & mask))

char *HTEscape(const char *str,
	       unsigned mask)
{
    const char *p;
    char *q;
    char *result;
    size_t unacceptable = 0;

    for (p = str; *p; p++)
	if (!ACCEPTABLE(UCH(TOASCII(*p))))
	    unacceptable++;
    result = AlloCopy(p, str, (unacceptable * 2) + 1);

    if (result == NULL)
	outofmem(__FILE__, "HTEscape");

    for (q = result, p = str; *p; p++) {
	unsigned char a = UCH(TOASCII(*p));

	if (!ACCEPTABLE(a)) {
	    *q++ = HEX_ESCAPE;	/* Means hex coming */
	    *q++ = hex[a >> 4];
	    *q++ = hex[a & 15];
	} else
	    *q++ = *p;
    }
    *q = '\0';			/* Terminate */
    return result;
}

/*	Escape unsafe characters using %			HTEscapeUnsafe()
 *	--------------------------------
 *
 *	This function takes a pointer to a string in which
 *	some characters may be that may be unsafe are unescaped.
 *	It returns a string which has these characters
 *	represented by a '%' character followed by two hex digits.
 *
 *	Unlike HTUnEscape(), this routine returns a malloc'd string.
 */
#define UNSAFE(ch) (((ch) <= 32) || ((ch) >= 127))

char *HTEscapeUnsafe(const char *str)
{
    const char *p;
    char *q;
    char *result;
    size_t unacceptable = 0;

    for (p = str; *p; p++)
	if (UNSAFE(UCH(TOASCII(*p))))
	    unacceptable++;
    result = AlloCopy(p, str, (unacceptable * 2) + 1);

    if (result == NULL)
	outofmem(__FILE__, "HTEscapeUnsafe");

    for (q = result, p = str; *p; p++) {
	unsigned char a = UCH(TOASCII(*p));

	if (UNSAFE(a)) {
	    *q++ = HEX_ESCAPE;	/* Means hex coming */
	    *q++ = hex[a >> 4];
	    *q++ = hex[a & 15];
	} else
	    *q++ = *p;
    }
    *q = '\0';			/* Terminate */
    return result;
}

/*	Escape undesirable characters using % but space to +.	HTEscapeSP()
 *	-----------------------------------------------------
 *
 *	This function takes a pointer to a string in which
 *	some characters may be unacceptable unescaped.
 *	It returns a string which has these characters
 *	represented by a '%' character followed by two hex digits,
 *	except that spaces are converted to '+' instead of %2B.
 *
 *	Unlike HTUnEscape(), this routine returns a calloced string.
 */
char *HTEscapeSP(const char *str,
		 unsigned mask)
{
    const char *p;
    char *q;
    char *result;
    size_t unacceptable = 0;

    for (p = str; *p; p++)
	if (!(*p == ' ' || ACCEPTABLE(UCH(TOASCII(*p)))))
	    unacceptable++;
    result = AlloCopy(p, str, (unacceptable * 2) + 1);

    if (result == NULL)
	outofmem(__FILE__, "HTEscape");

    for (q = result, p = str; *p; p++) {
	unsigned char a = UCH(TOASCII(*p));

	if (a == 32) {
	    *q++ = '+';
	} else if (!ACCEPTABLE(a)) {
	    *q++ = HEX_ESCAPE;	/* Means hex coming */
	    *q++ = hex[a >> 4];
	    *q++ = hex[a & 15];
	} else {
	    *q++ = *p;
	}
    }
    *q = '\0';			/* Terminate */
    return result;
}

/*	Decode %xx escaped characters.				HTUnEscape()
 *	------------------------------
 *
 *	This function takes a pointer to a string in which some
 *	characters may have been encoded in %xy form, where xy is
 *	the ASCII hex code for character 16x+y.
 *	The string is converted in place, as it will never grow.
 */
static char from_hex(int c)
{
    return (char) (c >= '0' && c <= '9' ? c - '0'
		   : c >= 'A' && c <= 'F' ? c - 'A' + 10
		   : c - 'a' + 10);	/* accept small letters just in case */
}

char *HTUnEscape(char *str)
{
    char *p = str;
    char *q = str;

    if (!(p && *p))
	return str;

    while (*p != '\0') {
	if (*p == HEX_ESCAPE &&
	/*
	 * Tests shouldn't be needed, but better safe than sorry.
	 */
	    p[1] && p[2] &&
	    isxdigit(UCH(p[1])) &&
	    isxdigit(UCH(p[2]))) {
	    p++;
	    if (*p)
		*q = (char) (from_hex(*p++) * 16);
	    if (*p) {
		/*
		 * Careful! FROMASCII() may evaluate its arg more than once!
		 */
		/* S/390 -- gil -- 0221 */
		*q = (char) (*q + from_hex(*p++));
	    }
	    *q = FROMASCII(*q);
	    q++;
	} else {
	    *q++ = *p++;
	}
    }

    *q = '\0';
    return str;

}				/* HTUnEscape */

/*	Decode some %xx escaped characters.		      HTUnEscapeSome()
 *	-----------------------------------			Klaus Weide
 *							    (kweide@tezcat.com)
 *	This function takes a pointer to a string in which some
 *	characters may have been encoded in %xy form, where xy is
 *	the ASCII hex code for character 16x+y, and a pointer to
 *	a second string containing one or more characters which
 *	should be unescaped if escaped in the first string.
 *	The first string is converted in place, as it will never grow.
 */
char *HTUnEscapeSome(char *str,
		     const char *do_trans)
{
    char *p = str;
    char *q = str;
    char testcode;

    if (p == NULL || *p == '\0' || do_trans == NULL || *do_trans == '\0')
	return str;

    while (*p != '\0') {
	if (*p == HEX_ESCAPE &&
	    p[1] && p[2] &&	/* tests shouldn't be needed, but.. */
	    isxdigit(UCH(p[1])) &&
	    isxdigit(UCH(p[2])) &&
	    (testcode = (char) FROMASCII(from_hex(p[1]) * 16 +
					 from_hex(p[2]))) &&	/* %00 no good */
	    StrChr(do_trans, testcode)) {	/* it's one of the ones we want */
	    *q++ = testcode;
	    p += 3;
	} else {
	    *q++ = *p++;
	}
    }

    *q = '\0';
    return str;

}				/* HTUnEscapeSome */
/* *INDENT-OFF* */
static const unsigned char crfc[96] =

/*	Bit 0		xalpha		-- need "quoting"
 *	Bit 1		xpalpha		-- need \escape if quoted
 */
    /*	 0 1 2 3 4 5 6 7 8 9 A B C D E F */
    {	 1,0,3,0,0,0,0,0,1,1,0,0,1,0,1,0,	/* 2x	!"#$%&'()*+,-./  */
	 0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,	/* 3x  0123456789:;<=>?  */
	 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,	/* 4x  @ABCDEFGHIJKLMNO  */
	 0,0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,	/* 5X  PQRSTUVWXYZ[\]^_  */
	 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,	/* 6x  `abcdefghijklmno  */
	 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3 };	/* 7X  pqrstuvwxyz{|}~	DEL */
/* *INDENT-ON* */

#define ASCII_TAB '\011'
#define ASCII_LF  '\012'
#define ASCII_CR  '\015'
#define ASCII_SPC '\040'
#define ASCII_BAK '\134'

/*
 *  Turn a string which is not a RFC 822 token into a quoted-string. - KW
 *  The "quoted" parameter tells whether we need the beginning/ending quote
 *  marks.  If not, the caller will provide them -TD
 */
void HTMake822Word(char **str,
		   int quoted)
{
    const char *p;
    char *q;
    char *result;
    unsigned char a;
    unsigned added = 0;

    if (isEmpty(*str)) {
	StrAllocCopy(*str, quoted ? "\"\"" : "");
	return;
    }
    for (p = *str; *p; p++) {
	a = UCH(TOASCII(*p));	/* S/390 -- gil -- 0240 */
	if (a < 32 || a >= 128 ||
	    ((crfc[a - 32]) & 1)) {
	    if (!added)
		added = 2;
	    if (a >= 160 || a == '\t')
		continue;
	    if (a == '\r' || a == '\n')
		added += 2;
	    else if ((a & 127) < 32 || ((crfc[a - 32]) & 2))
		added++;
	}
    }
    if (!added)
	return;
    result = AlloCopy(p, *str, added + 1);
    if (result == NULL)
	outofmem(__FILE__, "HTMake822Word");

    q = result;
    if (quoted)
	*q++ = '"';
    /*
     * Having converted the character to ASCII, we can't use symbolic
     * escape codes, since they're in the host character set, which
     * is not necessarily ASCII.  Thus we use octal escape codes instead.
     * -- gil (Paul Gilmartin) <pg@sweng.stortek.com>
     */
    /* S/390 -- gil -- 0268 */
    for (p = *str; *p; p++) {
	a = UCH(TOASCII(*p));
	if ((a != ASCII_TAB) &&
	    ((a & 127) < ASCII_SPC ||
	     (a < 128 && ((crfc[a - 32]) & 2))))
	    *q++ = ASCII_BAK;
	*q++ = *p;
	if (a == ASCII_LF ||
	    (a == ASCII_CR && (TOASCII(*(p + 1)) != ASCII_LF)))
	    *q++ = ' ';
    }
    if (quoted)
	*q++ = '"';
    *q = '\0';			/* Terminate */
    FREE(*str);
    *str = result;
}