Path: blob/main/crypto/krb5/src/include/k5-platform.h
34879 views
/* -*- mode: c; indent-tabs-mode: nil -*- */1/* include/k5-platform.h */2/*3* Copyright 2003, 2004, 2005, 2007, 2008, 2009 Massachusetts Institute of Technology.4* All Rights Reserved.5*6* Export of this software from the United States of America may7* require a specific license from the United States Government.8* It is the responsibility of any person or organization contemplating9* export to obtain such a license before exporting.10*11* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and12* distribute this software and its documentation for any purpose and13* without fee is hereby granted, provided that the above copyright14* notice appear in all copies and that both that copyright notice and15* this permission notice appear in supporting documentation, and that16* the name of M.I.T. not be used in advertising or publicity pertaining17* to distribution of the software without specific, written prior18* permission. Furthermore if you modify this software you must label19* your software as modified software and not distribute it in such a20* fashion that it might be confused with the original M.I.T. software.21* M.I.T. makes no representations about the suitability of22* this software for any purpose. It is provided "as is" without express23* or implied warranty.24*/2526/*27* Some platform-dependent definitions to sync up the C support level.28* Some to a C99-ish level, some related utility code.29*30* Currently:31* + [u]int{8,16,32}_t types32* + 64-bit types and load/store code33* + SIZE_MAX34* + shared library init/fini hooks35* + consistent getpwnam/getpwuid interfaces36* + va_copy fudged if not provided37* + strlcpy/strlcat38* + fnmatch39* + [v]asprintf40* + strerror_r41* + mkstemp42* + zap (support function and macro)43* + constant time memory comparison44* + path manipulation45* + _, N_, dgettext, bindtextdomain (for localization)46* + getopt_long47* + secure_getenv48* + fetching filenames from a directory49*/5051#ifndef K5_PLATFORM_H52#define K5_PLATFORM_H5354#include "autoconf.h"55#include <assert.h>56#include <string.h>57#include <stdarg.h>58#include <stdint.h>59#include <limits.h>60#include <stdlib.h>61#include <stdio.h>62#include <fcntl.h>63#include <errno.h>64#ifdef HAVE_FNMATCH_H65#include <fnmatch.h>66#endif6768#ifdef HAVE_UNISTD_H69#include <unistd.h>70#endif7172#ifdef __cplusplus73extern "C" {74#endif7576#ifdef _WIN3277#define CAN_COPY_VA_LIST78#endif7980/* This attribute prevents unused function warnings in gcc and clang. */81#ifdef __GNUC__82#define UNUSED __attribute__((__unused__))83#else84#define UNUSED85#endif8687#if defined(macintosh) || (defined(__MACH__) && defined(__APPLE__))88#include <TargetConditionals.h>89#endif9091/* Initialization and finalization function support for libraries.9293At top level, before the functions are defined or even declared:94MAKE_INIT_FUNCTION(init_fn);95MAKE_FINI_FUNCTION(fini_fn);96Then:97int init_fn(void) { ... }98void fini_fn(void) { if (INITIALIZER_RAN(init_fn)) ... }99In code, in the same file:100err = CALL_INIT_FUNCTION(init_fn);101102To trigger or verify the initializer invocation from another file,103a helper function must be created.104105This model handles both the load-time execution (Windows) and106delayed execution (pthread_once) approaches, and should be able to107guarantee in both cases that the init function is run once, in one108thread, before other stuff in the library is done; furthermore, the109finalization code should only run if the initialization code did.110(Maybe I could've made the "if INITIALIZER_RAN" test implicit, via111another function hidden in macros, but this is hairy enough112already.)113114The init_fn and fini_fn names should be chosen such that any115exported names staring with those names, and optionally followed by116additional characters, fits in with any namespace constraints on117the library in question.118119120There's also PROGRAM_EXITING() currently always defined as zero.121If there's some trivial way to find out if the fini function is122being called because the program that the library is linked into is123exiting, we can just skip all the work because the resources are124about to be freed up anyways. Generally this is likely to be the125same as distinguishing whether the library was loaded dynamically126while the program was running, or loaded as part of program127startup. On most platforms, I don't think we can distinguish these128cases easily, and it's probably not worth expending any significant129effort. (Note in particular that atexit() won't do, because if the130library is explicitly loaded and unloaded, it would have to be able131to deregister the atexit callback function. Also, the system limit132on atexit callbacks may be small.)133134135Implementation outline:136137Windows: MAKE_FINI_FUNCTION creates a symbol with a magic name that138is sought at library build time, and code is added to invoke the139function when the library is unloaded. MAKE_INIT_FUNCTION does140likewise, but the function is invoked when the library is loaded,141and an extra variable is declared to hold an error code and a "yes142the initializer ran" flag. CALL_INIT_FUNCTION blows up if the flag143isn't set, otherwise returns the error code.144145UNIX: MAKE_INIT_FUNCTION creates and initializes a variable with a146name derived from the function name, containing a k5_once_t147(pthread_once_t or int), an error code, and a pointer to the148function. The function itself is declared static, but the149associated variable has external linkage. CALL_INIT_FUNCTION150ensures thath the function is called exactly once (pthread_once or151just check the flag) and returns the stored error code (or the152pthread_once error).153154(That's the basic idea. With some debugging assert() calls and155such, it's a bit more complicated. And we also need to handle156doing the pthread test at run time on systems where that works, so157we use the k5_once_t stuff instead.)158159UNIX, with library unloading prevented or when building static160libraries: we don't need to run finalizers.161162UNIX, with compiler support: MAKE_FINI_FUNCTION declares the163function as a destructor, and the run time linker support or164whatever will cause it to be invoked when the library is unloaded,165the program ends, etc.166167UNIX, with linker support: MAKE_FINI_FUNCTION creates a symbol with168a magic name that is sought at library build time, and linker169options are used to mark it as a finalization function for the170library. The symbol must be exported.171172UNIX, no library finalization support: The finalization function173never runs, and we leak memory. Tough.174175DELAY_INITIALIZER will be defined by the configure script if we176want to use k5_once instead of load-time initialization. That'll177be the preferred method on most systems except Windows, where we178have to initialize some mutexes.179180181182183For maximum flexibility in defining the macros, the function name184parameter should be a simple name, not even a macro defined as185another name. The function should have a unique name, and should186conform to whatever namespace is used by the library in question.187(We do have export lists, but (1) they're not used for all188platforms, and (2) they're not used for static libraries.)189190If the macro expansion needs the function to have been declared, it191must include a declaration. If it is not necessary for the symbol192name to be exported from the object file, the macro should declare193it as "static". Hence the signature must exactly match "void194foo(void)". (ANSI C allows a static declaration followed by a195non-static one; the result is internal linkage.) The macro196expansion has to come before the function, because gcc apparently197won't act on "__attribute__((constructor))" if it comes after the198function definition.199200This is going to be compiler- and environment-specific, and may201require some support at library build time, and/or "asm"202statements. But through macro expansion and auxiliary functions,203we should be able to handle most things except #pragma.204205It's okay for this code to require that the library be built206with the same compiler and compiler options throughout, but207we shouldn't require that the library and application use the208same compiler.209210For static libraries, we don't really care about cleanup too much,211since it's all memory handling and mutex allocation which will all212be cleaned up when the program exits. Thus, it's okay if gcc-built213static libraries don't play nicely with cc-built executables when214it comes to static constructors, just as long as it doesn't cause215linking to fail.216217For dynamic libraries on UNIX, we'll use pthread_once-type support218to do delayed initialization, so if finalization can't be made to219work, we'll only have memory leaks in a load/use/unload cycle. If220anyone (like, say, the OS vendor) complains about this, they can221tell us how to get a shared library finalization function invoked222automatically.223224Currently there's --disable-delayed-initialization for preventing225the initialization from being delayed on UNIX, but that's mainly226just for testing the linker options for initialization, and will227probably be removed at some point. */228229/* Helper macros. */230231# define JOIN__2_2(A,B) A ## _ ## _ ## B232# define JOIN__2(A,B) JOIN__2_2(A,B)233234/* XXX Should test USE_LINKER_INIT_OPTION early, and if it's set,235always provide a function by the expected name, even if we're236delaying initialization. */237238#if defined(DELAY_INITIALIZER)239240/* Run the initialization code during program execution, at the latest241possible moment. This means multiple threads may be active. */242# include "k5-thread.h"243typedef struct { k5_once_t once; int error, did_run; void (*fn)(void); } k5_init_t;244# ifdef USE_LINKER_INIT_OPTION245# define MAYBE_DUMMY_INIT(NAME) \246void JOIN__2(NAME, auxinit) () { }247# else248# define MAYBE_DUMMY_INIT(NAME)249# endif250# ifdef __GNUC__251/* Do it in macro form so we get the file/line of the invocation if252the assertion fails. */253# define k5_call_init_function(I) \254(__extension__ ({ \255k5_init_t *k5int_i = (I); \256int k5int_err = k5_once(&k5int_i->once, k5int_i->fn); \257(k5int_err \258? k5int_err \259: (assert(k5int_i->did_run != 0), k5int_i->error)); \260}))261# define MAYBE_DEFINE_CALLINIT_FUNCTION262# else263# define MAYBE_DEFINE_CALLINIT_FUNCTION \264static inline int k5_call_init_function(k5_init_t *i) \265{ \266int err; \267err = k5_once(&i->once, i->fn); \268if (err) \269return err; \270assert (i->did_run != 0); \271return i->error; \272}273# endif274# define MAKE_INIT_FUNCTION(NAME) \275static int NAME(void); \276MAYBE_DUMMY_INIT(NAME) \277/* forward declaration for use in initializer */ \278static void JOIN__2(NAME, aux) (void); \279static k5_init_t JOIN__2(NAME, once) = \280{ K5_ONCE_INIT, 0, 0, JOIN__2(NAME, aux) }; \281MAYBE_DEFINE_CALLINIT_FUNCTION \282static void JOIN__2(NAME, aux) (void) \283{ \284JOIN__2(NAME, once).did_run = 1; \285JOIN__2(NAME, once).error = NAME(); \286} \287/* so ';' following macro use won't get error */ \288static int NAME(void)289# define CALL_INIT_FUNCTION(NAME) \290k5_call_init_function(& JOIN__2(NAME, once))291/* This should be called in finalization only, so we shouldn't have292multiple active threads mucking around in our library at this293point. So ignore the once_t object and just look at the flag.294295XXX Could we have problems with memory coherence between processors296if we don't invoke mutex/once routines? Probably not, the297application code should already be coordinating things such that298the library code is not in use by this point, and memory299synchronization will be needed there. */300# define INITIALIZER_RAN(NAME) \301(JOIN__2(NAME, once).did_run && JOIN__2(NAME, once).error == 0)302303# define PROGRAM_EXITING() (0)304305#elif defined(__GNUC__) && !defined(_WIN32) && defined(CONSTRUCTOR_ATTR_WORKS)306307/* Run initializer at load time, via GCC/C++ hook magic. */308309# ifdef USE_LINKER_INIT_OPTION310/* Both gcc and linker option?? Favor gcc. */311# define MAYBE_DUMMY_INIT(NAME) \312void JOIN__2(NAME, auxinit) () { }313# else314# define MAYBE_DUMMY_INIT(NAME)315# endif316317typedef struct { int error; unsigned char did_run; } k5_init_t;318# define MAKE_INIT_FUNCTION(NAME) \319MAYBE_DUMMY_INIT(NAME) \320static k5_init_t JOIN__2(NAME, ran) \321= { 0, 2 }; \322static void JOIN__2(NAME, aux)(void) \323__attribute__((constructor)); \324static int NAME(void); \325static void JOIN__2(NAME, aux)(void) \326{ \327JOIN__2(NAME, ran).error = NAME(); \328JOIN__2(NAME, ran).did_run = 3; \329} \330static int NAME(void)331# define CALL_INIT_FUNCTION(NAME) \332(JOIN__2(NAME, ran).did_run == 3 \333? JOIN__2(NAME, ran).error \334: (abort(),0))335# define INITIALIZER_RAN(NAME) (JOIN__2(NAME,ran).did_run == 3 && JOIN__2(NAME, ran).error == 0)336337# define PROGRAM_EXITING() (0)338339#elif defined(USE_LINKER_INIT_OPTION) || defined(_WIN32)340341/* Run initializer at load time, via linker magic, or in the342case of WIN32, win_glue.c hard-coded knowledge. */343typedef struct { int error; unsigned char did_run; } k5_init_t;344# define MAKE_INIT_FUNCTION(NAME) \345static k5_init_t JOIN__2(NAME, ran) \346= { 0, 2 }; \347static int NAME(void); \348void JOIN__2(NAME, auxinit)() \349{ \350JOIN__2(NAME, ran).error = NAME(); \351JOIN__2(NAME, ran).did_run = 3; \352} \353static int NAME(void)354# define CALL_INIT_FUNCTION(NAME) \355(JOIN__2(NAME, ran).did_run == 3 \356? JOIN__2(NAME, ran).error \357: (abort(),0))358# define INITIALIZER_RAN(NAME) \359(JOIN__2(NAME, ran).error == 0)360361# define PROGRAM_EXITING() (0)362363#else364365# error "Don't know how to do load-time initializers for this configuration."366367# define PROGRAM_EXITING() (0)368369#endif370371372373#if defined(USE_LINKER_FINI_OPTION) || defined(_WIN32)374/* If we're told the linker option will be used, it doesn't really375matter what compiler we're using. Do it the same way376regardless. */377378# ifdef __hpux379380/* On HP-UX, we need this auxiliary function. At dynamic load or381unload time (but *not* program startup and termination for382link-time specified libraries), the linker-indicated function383is called with a handle on the library and a flag indicating384whether it's being loaded or unloaded.385386The "real" fini function doesn't need to be exported, so387declare it static.388389As usual, the final declaration is just for syntactic390convenience, so the top-level invocation of this macro can be391followed by a semicolon. */392393# include <dl.h>394# define MAKE_FINI_FUNCTION(NAME) \395static void NAME(void); \396void JOIN__2(NAME, auxfini)(shl_t, int); /* silence gcc warnings */ \397void JOIN__2(NAME, auxfini)(shl_t h, int l) { if (!l) NAME(); } \398static void NAME(void)399400# else /* not hpux */401402# define MAKE_FINI_FUNCTION(NAME) \403void NAME(void)404405# endif406407#elif !defined(SHARED) || defined(LIB_UNLOAD_PREVENTED)408409/*410* In this case, we just don't care about finalization. The code will still411* define the function, but we won't do anything with it.412*/413# define MAKE_FINI_FUNCTION(NAME) \414static void NAME(void) UNUSED415416#elif defined(__GNUC__) && defined(DESTRUCTOR_ATTR_WORKS)417/* If we're using gcc, if the C++ support works, the compiler should418build executables and shared libraries that support the use of419static constructors and destructors. The C compiler supports a420function attribute that makes use of the same facility as C++.421422XXX How do we know if the C++ support actually works? */423# define MAKE_FINI_FUNCTION(NAME) \424static void NAME(void) __attribute__((destructor))425426#else427428# error "Don't know how to do unload-time finalization for this configuration."429430#endif431432#ifndef SIZE_MAX433# define SIZE_MAX ((size_t)((size_t)0 - 1))434#endif435436#ifdef _WIN32437# define SSIZE_MAX ((ssize_t)(SIZE_MAX/2))438#endif439440/* Read and write integer values as (unaligned) octet strings in441specific byte orders. Add per-platform optimizations as442needed. */443444#if HAVE_ENDIAN_H445# include <endian.h>446#elif HAVE_MACHINE_ENDIAN_H447# include <machine/endian.h>448#endif449/* Check for BIG/LITTLE_ENDIAN macros. If exactly one is defined, use450it. If both are defined, then BYTE_ORDER should be defined and451match one of them. Try those symbols, then try again with an452underscore prefix. */453#if defined(BIG_ENDIAN) && defined(LITTLE_ENDIAN)454# if BYTE_ORDER == BIG_ENDIAN455# define K5_BE456# endif457# if BYTE_ORDER == LITTLE_ENDIAN458# define K5_LE459# endif460#elif defined(BIG_ENDIAN)461# define K5_BE462#elif defined(LITTLE_ENDIAN)463# define K5_LE464#elif defined(_BIG_ENDIAN) && defined(_LITTLE_ENDIAN)465# if _BYTE_ORDER == _BIG_ENDIAN466# define K5_BE467# endif468# if _BYTE_ORDER == _LITTLE_ENDIAN469# define K5_LE470# endif471#elif defined(_BIG_ENDIAN)472# define K5_BE473#elif defined(_LITTLE_ENDIAN)474# define K5_LE475#elif defined(__BIG_ENDIAN__) && !defined(__LITTLE_ENDIAN__)476# define K5_BE477#elif defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)478# define K5_LE479#endif480#if !defined(K5_BE) && !defined(K5_LE)481/* Look for some architectures we know about.482483MIPS can use either byte order, but the preprocessor tells us which484mode we're compiling for. The GCC config files indicate that485variants of Alpha and IA64 might be out there with both byte486orders, but until we encounter the "wrong" ones in the real world,487just go with the default (unless there are cpp predefines to help488us there too).489490As far as I know, only PDP11 and ARM (which we don't handle here)491have strange byte orders where an 8-byte value isn't laid out as492either 12345678 or 87654321. */493# if defined(__i386__) || defined(_MIPSEL) || defined(__alpha__) || (defined(__ia64__) && !defined(__hpux))494# define K5_LE495# endif496# if defined(__hppa__) || defined(__rs6000__) || defined(__sparc__) || defined(_MIPSEB) || defined(__m68k__) || defined(__sparc64__) || defined(__ppc__) || defined(__ppc64__) || (defined(__hpux) && defined(__ia64__))497# define K5_BE498# endif499#endif500#if defined(K5_BE) && defined(K5_LE)501# error "oops, check the byte order macros"502#endif503504/* Optimize for GCC on platforms with known byte orders.505506GCC's packed structures can be written to with any alignment; the507compiler will use byte operations, unaligned-word operations, or508normal memory ops as appropriate for the architecture.509510This assumes the availability of uint##_t types, which should work511on most of our platforms except Windows, where we're not using512GCC. */513#ifdef __GNUC__514# define PUT(SIZE,PTR,VAL) (((struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i = (VAL))515# define GET(SIZE,PTR) (((const struct { uint##SIZE##_t i; } __attribute__((packed)) *)(PTR))->i)516# define PUTSWAPPED(SIZE,PTR,VAL) PUT(SIZE,PTR,SWAP##SIZE(VAL))517# define GETSWAPPED(SIZE,PTR) SWAP##SIZE(GET(SIZE,PTR))518#endif519/* To do: Define SWAP16, SWAP32, SWAP64 macros to byte-swap values520with the indicated numbers of bits.521522Linux: byteswap.h, bswap_16 etc.523Solaris 10: none524macOS: machine/endian.h or byte_order.h, NXSwap{Short,Int,LongLong}525NetBSD: sys/bswap.h, bswap16 etc. */526527#if defined(HAVE_BYTESWAP_H) && defined(HAVE_BSWAP_16)528# include <byteswap.h>529# define SWAP16 bswap_16530# define SWAP32 bswap_32531# ifdef HAVE_BSWAP_64532# define SWAP64 bswap_64533# endif534#elif TARGET_OS_MAC535# include <architecture/byte_order.h>536# define SWAP16 k5_swap16537static inline unsigned int k5_swap16 (unsigned int x) {538x &= 0xffff;539return (x >> 8) | ((x & 0xff) << 8);540}541# define SWAP32 OSSwapInt32542# define SWAP64 OSSwapInt64543#elif defined(HAVE_SYS_BSWAP_H)544/* XXX NetBSD/x86 5.0.1 defines bswap16 and bswap32 as inline545functions only, so autoconf doesn't pick up on their existence.546So, no feature macro test for them here. The 64-bit version isn't547inline at all, though, for whatever reason. */548# include <sys/bswap.h>549# define SWAP16 bswap16550# define SWAP32 bswap32551/* However, bswap64 causes lots of warnings about 'long long'552constants; probably only on 32-bit platforms. */553# if LONG_MAX > 0x7fffffffL554# define SWAP64 bswap64555# endif556#endif557558/* Note that on Windows at least this file can be included from C++559source, so casts *from* void* are required. */560static inline void561store_16_be (unsigned int val, void *vp)562{563unsigned char *p = (unsigned char *) vp;564#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)565PUT(16,p,val);566#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)567PUTSWAPPED(16,p,val);568#else569p[0] = (val >> 8) & 0xff;570p[1] = (val ) & 0xff;571#endif572}573static inline void574store_32_be (unsigned int val, void *vp)575{576unsigned char *p = (unsigned char *) vp;577#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)578PUT(32,p,val);579#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)580PUTSWAPPED(32,p,val);581#else582p[0] = (val >> 24) & 0xff;583p[1] = (val >> 16) & 0xff;584p[2] = (val >> 8) & 0xff;585p[3] = (val ) & 0xff;586#endif587}588static inline void589store_64_be (uint64_t val, void *vp)590{591unsigned char *p = (unsigned char *) vp;592#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)593PUT(64,p,val);594#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)595PUTSWAPPED(64,p,val);596#else597p[0] = (unsigned char)((val >> 56) & 0xff);598p[1] = (unsigned char)((val >> 48) & 0xff);599p[2] = (unsigned char)((val >> 40) & 0xff);600p[3] = (unsigned char)((val >> 32) & 0xff);601p[4] = (unsigned char)((val >> 24) & 0xff);602p[5] = (unsigned char)((val >> 16) & 0xff);603p[6] = (unsigned char)((val >> 8) & 0xff);604p[7] = (unsigned char)((val ) & 0xff);605#endif606}607static inline unsigned short608load_16_be (const void *cvp)609{610const unsigned char *p = (const unsigned char *) cvp;611#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)612return GET(16,p);613#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP16) && !defined(__cplusplus)614return GETSWAPPED(16,p);615#else616return (p[1] | (p[0] << 8));617#endif618}619static inline unsigned int620load_32_be (const void *cvp)621{622const unsigned char *p = (const unsigned char *) cvp;623#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)624return GET(32,p);625#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP32) && !defined(__cplusplus)626return GETSWAPPED(32,p);627#else628return (p[3] | (p[2] << 8)629| ((uint32_t) p[1] << 16)630| ((uint32_t) p[0] << 24));631#endif632}633static inline uint64_t634load_64_be (const void *cvp)635{636const unsigned char *p = (const unsigned char *) cvp;637#if defined(__GNUC__) && defined(K5_BE) && !defined(__cplusplus)638return GET(64,p);639#elif defined(__GNUC__) && defined(K5_LE) && defined(SWAP64) && !defined(__cplusplus)640return GETSWAPPED(64,p);641#else642return ((uint64_t)load_32_be(p) << 32) | load_32_be(p+4);643#endif644}645static inline void646store_16_le (unsigned int val, void *vp)647{648unsigned char *p = (unsigned char *) vp;649#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)650PUT(16,p,val);651#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)652PUTSWAPPED(16,p,val);653#else654p[1] = (val >> 8) & 0xff;655p[0] = (val ) & 0xff;656#endif657}658static inline void659store_32_le (unsigned int val, void *vp)660{661unsigned char *p = (unsigned char *) vp;662#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)663PUT(32,p,val);664#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)665PUTSWAPPED(32,p,val);666#else667p[3] = (val >> 24) & 0xff;668p[2] = (val >> 16) & 0xff;669p[1] = (val >> 8) & 0xff;670p[0] = (val ) & 0xff;671#endif672}673static inline void674store_64_le (uint64_t val, void *vp)675{676unsigned char *p = (unsigned char *) vp;677#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)678PUT(64,p,val);679#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)680PUTSWAPPED(64,p,val);681#else682p[7] = (unsigned char)((val >> 56) & 0xff);683p[6] = (unsigned char)((val >> 48) & 0xff);684p[5] = (unsigned char)((val >> 40) & 0xff);685p[4] = (unsigned char)((val >> 32) & 0xff);686p[3] = (unsigned char)((val >> 24) & 0xff);687p[2] = (unsigned char)((val >> 16) & 0xff);688p[1] = (unsigned char)((val >> 8) & 0xff);689p[0] = (unsigned char)((val ) & 0xff);690#endif691}692static inline unsigned short693load_16_le (const void *cvp)694{695const unsigned char *p = (const unsigned char *) cvp;696#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)697return GET(16,p);698#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP16) && !defined(__cplusplus)699return GETSWAPPED(16,p);700#else701return (p[0] | (p[1] << 8));702#endif703}704static inline unsigned int705load_32_le (const void *cvp)706{707const unsigned char *p = (const unsigned char *) cvp;708#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)709return GET(32,p);710#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP32) && !defined(__cplusplus)711return GETSWAPPED(32,p);712#else713return (p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));714#endif715}716static inline uint64_t717load_64_le (const void *cvp)718{719const unsigned char *p = (const unsigned char *) cvp;720#if defined(__GNUC__) && defined(K5_LE) && !defined(__cplusplus)721return GET(64,p);722#elif defined(__GNUC__) && defined(K5_BE) && defined(SWAP64) && !defined(__cplusplus)723return GETSWAPPED(64,p);724#else725return ((uint64_t)load_32_le(p+4) << 32) | load_32_le(p);726#endif727}728729#define UINT16_TYPE uint16_t730#define UINT32_TYPE uint32_t731732static inline void733store_16_n (unsigned int val, void *vp)734{735UINT16_TYPE n = val;736memcpy(vp, &n, 2);737}738static inline void739store_32_n (unsigned int val, void *vp)740{741UINT32_TYPE n = val;742memcpy(vp, &n, 4);743}744static inline void745store_64_n (uint64_t val, void *vp)746{747uint64_t n = val;748memcpy(vp, &n, 8);749}750static inline unsigned short751load_16_n (const void *p)752{753UINT16_TYPE n;754memcpy(&n, p, 2);755return n;756}757static inline unsigned int758load_32_n (const void *p)759{760UINT32_TYPE n;761memcpy(&n, p, 4);762return n;763}764static inline uint64_t765load_64_n (const void *p)766{767uint64_t n;768memcpy(&n, p, 8);769return n;770}771#undef UINT16_TYPE772#undef UINT32_TYPE773774/* Assume for simplicity that these swaps are identical. */775static inline uint64_t776k5_htonll (uint64_t val)777{778#ifdef K5_BE779return val;780#elif defined K5_LE && defined SWAP64781return SWAP64 (val);782#else783return load_64_be ((unsigned char *)&val);784#endif785}786static inline uint64_t787k5_ntohll (uint64_t val)788{789return k5_htonll (val);790}791792/* Make the interfaces to getpwnam and getpwuid consistent.793Model the wrappers on the POSIX thread-safe versions, but794use the unsafe system versions if the safe ones don't exist795or we can't figure out their interfaces. */796797/* int k5_getpwnam_r(const char *, blah blah) */798#ifdef HAVE_GETPWNAM_R799# ifndef GETPWNAM_R_4_ARGS800/* POSIX */801# define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \802(getpwnam_r(NAME,REC,BUF,BUFSIZE,OUT) == 0 \803? (*(OUT) == NULL ? -1 : 0) : -1)804# else805/* POSIX drafts? */806# ifdef GETPWNAM_R_RETURNS_INT807# define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \808(getpwnam_r(NAME,REC,BUF,BUFSIZE) == 0 \809? (*(OUT) = REC, 0) \810: (*(OUT) = NULL, -1))811# else812# define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \813(*(OUT) = getpwnam_r(NAME,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)814# endif815# endif816#else /* no getpwnam_r, or can't figure out #args or return type */817/* Will get warnings about unused variables. */818# define k5_getpwnam_r(NAME, REC, BUF, BUFSIZE, OUT) \819(*(OUT) = getpwnam(NAME), *(OUT) == NULL ? -1 : 0)820#endif821822/* int k5_getpwuid_r(uid_t, blah blah) */823#ifdef HAVE_GETPWUID_R824# ifndef GETPWUID_R_4_ARGS825/* POSIX */826# define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \827(getpwuid_r(UID,REC,BUF,BUFSIZE,OUT) == 0 \828? (*(OUT) == NULL ? -1 : 0) : -1)829# else830/* POSIX drafts? Yes, I mean to test GETPWNAM... here. Less junk to831do at configure time. */832# ifdef GETPWNAM_R_RETURNS_INT833# define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \834(getpwuid_r(UID,REC,BUF,BUFSIZE) == 0 \835? (*(OUT) = REC, 0) \836: (*(OUT) = NULL, -1))837# else838# define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \839(*(OUT) = getpwuid_r(UID,REC,BUF,BUFSIZE), *(OUT) == NULL ? -1 : 0)840# endif841# endif842#else /* no getpwuid_r, or can't figure out #args or return type */843/* Will get warnings about unused variables. */844# define k5_getpwuid_r(UID, REC, BUF, BUFSIZE, OUT) \845(*(OUT) = getpwuid(UID), *(OUT) == NULL ? -1 : 0)846#endif847848/* Ensure, if possible, that the indicated file descriptor won't be849kept open if we exec another process (e.g., launching a ccapi850server). If we don't know how to do it... well, just go about our851business. Probably most callers won't check the return status852anyways. */853854/* Macros make the Sun compiler happier, and all variants of this do a855single evaluation of the argument, and fcntl and fileno should856produce reasonable error messages on type mismatches, on any system857with F_SETFD. */858#ifdef F_SETFD859# ifdef FD_CLOEXEC860# define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, FD_CLOEXEC))861# else862# define set_cloexec_fd(FD) ((void)fcntl((FD), F_SETFD, 1))863# endif864#else865# define set_cloexec_fd(FD) ((void)(FD))866#endif867#define set_cloexec_file(F) set_cloexec_fd(fileno(F))868869/* Since the original ANSI C spec left it undefined whether or870how you could copy around a va_list, C 99 added va_copy.871For old implementations, let's do our best to fake it.872873XXX Doesn't yet handle implementations with __va_copy (early draft)874or GCC's __builtin_va_copy. */875#if defined(HAS_VA_COPY) || defined(va_copy)876/* Do nothing. */877#elif defined(CAN_COPY_VA_LIST)878#define va_copy(dest, src) ((dest) = (src))879#else880/* Assume array type, but still simply copyable.881882There is, theoretically, the possibility that va_start will883allocate some storage pointed to by the va_list, and in that case884we'll just lose. If anyone cares, we could try to devise a test885for that case. */886#define va_copy(dest, src) memcpy(dest, src, sizeof(va_list))887#endif888889/* Provide strlcpy/strlcat interfaces. */890#ifndef HAVE_STRLCPY891#define strlcpy krb5int_strlcpy892#define strlcat krb5int_strlcat893extern size_t krb5int_strlcpy(char *dst, const char *src, size_t siz);894extern size_t krb5int_strlcat(char *dst, const char *src, size_t siz);895#endif896897/* Provide fnmatch interface. */898#ifndef HAVE_FNMATCH899#define fnmatch k5_fnmatch900int k5_fnmatch(const char *pattern, const char *string, int flags);901#define FNM_NOMATCH 1 /* Match failed. */902#define FNM_NOSYS 2 /* Function not implemented. */903#define FNM_NORES 3 /* Out of resources */904#define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */905#define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */906#define FNM_PERIOD 0x04 /* Period must be matched by period. */907#define FNM_CASEFOLD 0x08 /* Pattern is matched case-insensitive */908#define FNM_LEADING_DIR 0x10 /* Ignore /<tail> after Imatch. */909#endif910911/* Provide [v]asprintf interfaces. */912#ifndef HAVE_VSNPRINTF913#ifdef _WIN32914static inline int915vsnprintf(char *str, size_t size, const char *format, va_list args)916{917va_list args_copy;918int length;919920va_copy(args_copy, args);921length = _vscprintf(format, args_copy);922va_end(args_copy);923if (size > 0) {924_vsnprintf(str, size, format, args);925str[size - 1] = '\0';926}927return length;928}929static inline int930snprintf(char *str, size_t size, const char *format, ...)931{932va_list args;933int n;934935va_start(args, format);936n = vsnprintf(str, size, format, args);937va_end(args);938return n;939}940#else /* not win32 */941#error We need an implementation of vsnprintf.942#endif /* win32? */943#endif /* no vsnprintf */944945#ifndef HAVE_VASPRINTF946947extern int krb5int_vasprintf(char **, const char *, va_list)948#if !defined(__cplusplus) && (__GNUC__ > 2)949__attribute__((__format__(__printf__, 2, 0)))950#endif951;952extern int krb5int_asprintf(char **, const char *, ...)953#if !defined(__cplusplus) && (__GNUC__ > 2)954__attribute__((__format__(__printf__, 2, 3)))955#endif956;957958#define vasprintf krb5int_vasprintf959/* Assume HAVE_ASPRINTF iff HAVE_VASPRINTF. */960#define asprintf krb5int_asprintf961962#elif defined(NEED_VASPRINTF_PROTO)963964extern int vasprintf(char **, const char *, va_list)965#if !defined(__cplusplus) && (__GNUC__ > 2)966__attribute__((__format__(__printf__, 2, 0)))967#endif968;969extern int asprintf(char **, const char *, ...)970#if !defined(__cplusplus) && (__GNUC__ > 2)971__attribute__((__format__(__printf__, 2, 3)))972#endif973;974975#endif /* have vasprintf and prototype? */976977/* Return true if the snprintf return value RESULT reflects a buffer978overflow for the buffer size SIZE.979980We cast the result to unsigned int for two reasons. First, old981implementations of snprintf (such as the one in Solaris 9 and982prior) return -1 on a buffer overflow. Casting the result to -1983will convert that value to UINT_MAX, which should compare larger984than any reasonable buffer size. Second, comparing signed and985unsigned integers will generate warnings with some compilers, and986can have unpredictable results, particularly when the relative987widths of the types is not known (size_t may be the same width as988int or larger).989*/990#define SNPRINTF_OVERFLOW(result, size) \991((unsigned int)(result) >= (size_t)(size))992993#if defined(_WIN32) || !defined(HAVE_STRERROR_R) || defined(STRERROR_R_CHAR_P)994#define strerror_r k5_strerror_r995#endif996extern int k5_strerror_r(int errnum, char *buf, size_t buflen);997998#ifndef HAVE_MKSTEMP999extern int krb5int_mkstemp(char *);1000#define mkstemp krb5int_mkstemp1001#endif10021003#ifndef HAVE_GETTIMEOFDAY1004extern int krb5int_gettimeofday(struct timeval *tp, void *ignore);1005#define gettimeofday krb5int_gettimeofday1006#endif10071008/*1009* Attempt to zero memory in a way that compilers won't optimize out.1010*1011* This mechanism should work even for heap storage about to be freed,1012* or automatic storage right before we return from a function.1013*1014* Then, even if we leak uninitialized memory someplace, or UNIX1015* "core" files get created with world-read access, some of the most1016* sensitive data in the process memory will already be safely wiped.1017*1018* We're not going so far -- yet -- as to try to protect key data that1019* may have been written into swap space....1020*/1021#ifdef _WIN321022# define zap(ptr, len) SecureZeroMemory(ptr, len)1023#elif defined(__STDC_LIB_EXT1__)1024/*1025* Use memset_s() which cannot be optimized out. Avoid memset_s(NULL, 0, 0, 0)1026* which would cause a runtime constraint violation.1027*/1028static inline void zap(void *ptr, size_t len)1029{1030if (len > 0)1031memset_s(ptr, len, 0, len);1032}1033#elif defined(HAVE_EXPLICIT_BZERO)1034# define zap(ptr, len) explicit_bzero(ptr, len)1035#elif defined(HAVE_EXPLICIT_MEMSET)1036# define zap(ptr, len) explicit_memset(ptr, 0, len)1037#elif defined(__GNUC__) || defined(__clang__)1038/*1039* Use an asm statement which declares a memory clobber to force the memset to1040* be carried out. Avoid memset(NULL, 0, 0) which has undefined behavior.1041*/1042static inline void zap(void *ptr, size_t len)1043{1044if (len > 0)1045memset(ptr, 0, len);1046__asm__ __volatile__("" : : "g" (ptr) : "memory");1047}1048#else1049/*1050* Use a function from libkrb5support to defeat inlining unless link-time1051* optimization is used. The function uses a volatile pointer, which prevents1052* current compilers from optimizing out the memset.1053*/1054# define zap(ptr, len) krb5int_zap(ptr, len)1055#endif10561057extern void krb5int_zap(void *ptr, size_t len);10581059/*1060* Return 0 if the n-byte memory regions p1 and p2 are equal, and nonzero if1061* they are not. The function is intended to take the same amount of time1062* regardless of how many bytes of p1 and p2 are equal.1063*/1064int k5_bcmp(const void *p1, const void *p2, size_t n);10651066/*1067* Split a path into parent directory and basename. Either output parameter1068* may be NULL if the caller doesn't need it. parent_out will be empty if path1069* has no basename. basename_out will be empty if path ends with a path1070* separator. Returns 0 on success or ENOMEM on allocation failure.1071*/1072long k5_path_split(const char *path, char **parent_out, char **basename_out);10731074/*1075* Compose two path components, inserting the platform-appropriate path1076* separator if needed. If path2 is an absolute path, path1 will be discarded1077* and path_out will be a copy of path2. Returns 0 on success or ENOMEM on1078* allocation failure.1079*/1080long k5_path_join(const char *path1, const char *path2, char **path_out);10811082/* Return 1 if path is absolute, 0 if it is relative. */1083int k5_path_isabs(const char *path);10841085/*1086* Localization macros. If we have gettext, define _ appropriately for1087* translating a string. If we do not have gettext, define _ and1088* bindtextdomain as no-ops. N_ is always a no-op; it marks a string for1089* extraction to pot files but does not translate it.1090*/1091#ifdef ENABLE_NLS1092#include <libintl.h>1093#define KRB5_TEXTDOMAIN "mit-krb5"1094#define _(s) dgettext(KRB5_TEXTDOMAIN, s)1095#else1096#define _(s) s1097#define dgettext(d, m) m1098#define ngettext(m1, m2, n) (((n) == 1) ? m1 : m2)1099#define bindtextdomain(p, d)1100#endif1101#define N_(s) s11021103#if !defined(HAVE_GETOPT) || !defined(HAVE_UNISTD_H)1104/* Data objects imported from DLLs must be declared as such on Windows. */1105#if defined(_WIN32) && !defined(K5_GETOPT_C)1106#define K5_GETOPT_DECL __declspec(dllimport)1107#else1108#define K5_GETOPT_DECL1109#endif1110K5_GETOPT_DECL extern int k5_opterr;1111K5_GETOPT_DECL extern int k5_optind;1112K5_GETOPT_DECL extern int k5_optopt;1113K5_GETOPT_DECL extern char *k5_optarg;1114#define opterr k5_opterr1115#define optind k5_optind1116#define optopt k5_optopt1117#define optarg k5_optarg11181119extern int k5_getopt(int nargc, char * const nargv[], const char *ostr);1120#define getopt k5_getopt1121#endif /* HAVE_GETOPT */11221123#ifdef HAVE_GETOPT_LONG1124#include <getopt.h>1125#else11261127struct option1128{1129const char *name;1130int has_arg;1131int *flag;1132int val;1133};11341135#define no_argument 01136#define required_argument 11137#define optional_argument 211381139extern int k5_getopt_long(int nargc, char **nargv, char *options,1140struct option *long_options, int *index);1141#define getopt_long k5_getopt_long1142#endif /* HAVE_GETOPT_LONG */11431144#if defined(_WIN32)1145/* On Windows there is never a need to ignore the process environment. */1146#define secure_getenv getenv1147#elif !defined(HAVE_SECURE_GETENV)1148#define secure_getenv k5_secure_getenv1149extern char *k5_secure_getenv(const char *name);1150#endif11511152/* Set *fnames_out to a null-terminated list of filenames within dirname,1153* sorted according to strcmp(). Return 0 on success, or ENOENT/ENOMEM. */1154int k5_dir_filenames(const char *dirname, char ***fnames_out);1155void k5_free_filenames(char **fnames);11561157#ifdef __cplusplus1158}1159#endif11601161#endif /* K5_PLATFORM_H */116211631164