]> git.sur5r.net Git - openldap/blob - libraries/libldap/util-int.c
Happy New Year
[openldap] / libraries / libldap / util-int.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2018 The OpenLDAP Foundation.
5  * Portions Copyright 1998 A. Hartgers.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS:
17  * This work was initially developed by Bart Hartgers for inclusion in
18  * OpenLDAP Software.
19  */
20
21 /*
22  * util-int.c   Various functions to replace missing threadsafe ones.
23  *                              Without the real *_r funcs, things will
24  *                              work, but might not be threadsafe. 
25  */
26
27 #include "portable.h"
28
29 #include <ac/stdlib.h>
30
31 #include <ac/errno.h>
32 #include <ac/socket.h>
33 #include <ac/string.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36
37 #include "ldap-int.h"
38
39 #ifndef h_errno
40 /* newer systems declare this in <netdb.h> for you, older ones don't.
41  * harmless to declare it again (unless defined by a macro).
42  */
43 extern int h_errno;
44 #endif
45
46 #ifdef HAVE_HSTRERROR
47 # define HSTRERROR(e)   hstrerror(e)
48 #else
49 # define HSTRERROR(e)   hp_strerror(e)
50 #endif
51
52 #ifndef LDAP_R_COMPILE
53 # undef HAVE_REENTRANT_FUNCTIONS
54 # undef HAVE_CTIME_R
55 # undef HAVE_GETHOSTBYNAME_R
56 # undef HAVE_GETHOSTBYADDR_R
57
58 #else
59 # include <ldap_pvt_thread.h>
60   ldap_pvt_thread_mutex_t ldap_int_resolv_mutex;
61   ldap_pvt_thread_mutex_t ldap_int_hostname_mutex;
62   static ldap_pvt_thread_mutex_t ldap_int_gettime_mutex;
63
64 # if (defined( HAVE_CTIME_R ) || defined( HAVE_REENTRANT_FUNCTIONS)) \
65          && defined( CTIME_R_NARGS )
66 #   define USE_CTIME_R
67 # else
68         static ldap_pvt_thread_mutex_t ldap_int_ctime_mutex;
69 # endif
70
71 /* USE_GMTIME_R and USE_LOCALTIME_R defined in ldap_pvt.h */
72
73 #if !defined( USE_GMTIME_R ) || !defined( USE_LOCALTIME_R )
74         /* we use the same mutex for gmtime(3) and localtime(3)
75          * because implementations may use the same buffer
76          * for both functions */
77         static ldap_pvt_thread_mutex_t ldap_int_gmtime_mutex;
78 #endif
79
80 # if defined(HAVE_GETHOSTBYNAME_R) && \
81         (GETHOSTBYNAME_R_NARGS < 5) || (6 < GETHOSTBYNAME_R_NARGS)
82         /* Don't know how to handle this version, pretend it's not there */
83 #       undef HAVE_GETHOSTBYNAME_R
84 # endif
85 # if defined(HAVE_GETHOSTBYADDR_R) && \
86         (GETHOSTBYADDR_R_NARGS < 7) || (8 < GETHOSTBYADDR_R_NARGS)
87         /* Don't know how to handle this version, pretend it's not there */
88 #       undef HAVE_GETHOSTBYADDR_R
89 # endif
90 #endif /* LDAP_R_COMPILE */
91
92 char *ldap_pvt_ctime( const time_t *tp, char *buf )
93 {
94 #ifdef USE_CTIME_R
95 # if (CTIME_R_NARGS > 3) || (CTIME_R_NARGS < 2)
96 #       error "CTIME_R_NARGS should be 2 or 3"
97 # elif CTIME_R_NARGS > 2 && defined(CTIME_R_RETURNS_INT)
98         return( ctime_r(tp,buf,26) < 0 ? 0 : buf );
99 # elif CTIME_R_NARGS > 2
100         return ctime_r(tp,buf,26);
101 # else
102         return ctime_r(tp,buf);
103 # endif   
104
105 #else
106
107         LDAP_MUTEX_LOCK( &ldap_int_ctime_mutex );
108         AC_MEMCPY( buf, ctime(tp), 26 );
109         LDAP_MUTEX_UNLOCK( &ldap_int_ctime_mutex );
110
111         return buf;
112 #endif  
113 }
114
115 #if !defined( USE_GMTIME_R ) || !defined( USE_LOCALTIME_R )
116 int
117 ldap_pvt_gmtime_lock( void )
118 {
119 # ifndef LDAP_R_COMPILE
120         return 0;
121 # else /* LDAP_R_COMPILE */
122         return ldap_pvt_thread_mutex_lock( &ldap_int_gmtime_mutex );
123 # endif /* LDAP_R_COMPILE */
124 }
125
126 int
127 ldap_pvt_gmtime_unlock( void )
128 {
129 # ifndef LDAP_R_COMPILE
130         return 0;
131 # else /* LDAP_R_COMPILE */
132         return ldap_pvt_thread_mutex_unlock( &ldap_int_gmtime_mutex );
133 # endif /* LDAP_R_COMPILE */
134 }
135 #endif /* !USE_GMTIME_R || !USE_LOCALTIME_R */
136
137 #ifndef USE_GMTIME_R
138 struct tm *
139 ldap_pvt_gmtime( const time_t *timep, struct tm *result )
140 {
141         struct tm *tm_ptr;
142
143         LDAP_MUTEX_LOCK( &ldap_int_gmtime_mutex );
144         tm_ptr = gmtime( timep );
145         if ( tm_ptr == NULL ) {
146                 result = NULL;
147
148         } else {
149                 *result = *tm_ptr;
150         }
151         LDAP_MUTEX_UNLOCK( &ldap_int_gmtime_mutex );
152
153         return result;
154 }
155 #endif /* !USE_GMTIME_R */
156
157 #ifndef USE_LOCALTIME_R
158 struct tm *
159 ldap_pvt_localtime( const time_t *timep, struct tm *result )
160 {
161         struct tm *tm_ptr;
162
163         LDAP_MUTEX_LOCK( &ldap_int_gmtime_mutex );
164         tm_ptr = localtime( timep );
165         if ( tm_ptr == NULL ) {
166                 result = NULL;
167
168         } else {
169                 *result = *tm_ptr;
170         }
171         LDAP_MUTEX_UNLOCK( &ldap_int_gmtime_mutex );
172
173         return result;
174 }
175 #endif /* !USE_LOCALTIME_R */
176
177 static int _ldap_pvt_gt_subs;
178
179 #ifdef _WIN32
180 /* Windows SYSTEMTIME only has 10 millisecond resolution, so we
181  * also need to use a high resolution timer to get microseconds.
182  * This is pretty clunky.
183  */
184 static LARGE_INTEGER _ldap_pvt_gt_freq;
185 static LARGE_INTEGER _ldap_pvt_gt_prev;
186 static int _ldap_pvt_gt_offset;
187
188 #define SEC_TO_UNIX_EPOCH 11644473600LL
189 #define TICKS_PER_SECOND 10000000
190
191 static int
192 ldap_pvt_gettimeusec(int *sec)
193 {
194         LARGE_INTEGER count;
195
196         QueryPerformanceCounter( &count );
197
198         /* It shouldn't ever go backwards, but multiple CPUs might
199          * be able to hit in the same tick.
200          */
201         LDAP_MUTEX_LOCK( &ldap_int_gettime_mutex );
202         /* We assume Windows has at least a vague idea of
203          * when a second begins. So we align our microsecond count
204          * with the Windows millisecond count using this offset.
205          * We retain the submillisecond portion of our own count.
206          *
207          * Note - this also assumes that the relationship between
208          * the PerformanceCounter and SystemTime stays constant;
209          * that assumption breaks if the SystemTime is adjusted by
210          * an external action.
211          */
212         if ( !_ldap_pvt_gt_freq.QuadPart ) {
213                 LARGE_INTEGER c2;
214                 ULARGE_INTEGER ut;
215                 FILETIME ft0, ft1;
216                 long long t;
217                 int usec;
218
219                 /* Initialize our offset */
220                 QueryPerformanceFrequency( &_ldap_pvt_gt_freq );
221
222                 /* Wait for a tick of the system time: 10-15ms */
223                 GetSystemTimeAsFileTime( &ft0 );
224                 do {
225                         GetSystemTimeAsFileTime( &ft1 );
226                 } while ( ft1.dwLowDateTime == ft0.dwLowDateTime );
227
228                 ut.LowPart = ft1.dwLowDateTime;
229                 ut.HighPart = ft1.dwHighDateTime;
230                 QueryPerformanceCounter( &c2 );
231
232                 /* get second and fraction portion of counter */
233                 t = c2.QuadPart % (_ldap_pvt_gt_freq.QuadPart*10);
234
235                 /* convert to microseconds */
236                 t *= 1000000;
237                 usec = t / _ldap_pvt_gt_freq.QuadPart;
238
239                 ut.QuadPart /= 10;
240                 ut.QuadPart %= 10000000;
241                 _ldap_pvt_gt_offset = usec - ut.QuadPart;
242                 count = c2;
243         }
244         if ( count.QuadPart <= _ldap_pvt_gt_prev.QuadPart ) {
245                 _ldap_pvt_gt_subs++;
246         } else {
247                 _ldap_pvt_gt_subs = 0;
248                 _ldap_pvt_gt_prev = count;
249         }
250         LDAP_MUTEX_UNLOCK( &ldap_int_gettime_mutex );
251
252         /* convert to microseconds */
253         count.QuadPart %= _ldap_pvt_gt_freq.QuadPart*10;
254         count.QuadPart *= 1000000;
255         count.QuadPart /= _ldap_pvt_gt_freq.QuadPart;
256         count.QuadPart -= _ldap_pvt_gt_offset;
257
258         /* We've extracted the 1s and microseconds.
259          * The 1sec digit is used to detect wraparound in microsecnds.
260          */
261         if (count.QuadPart < 0)
262                 count.QuadPart += 10000000;
263         else if (count.QuadPart >= 10000000)
264                 count.QuadPart -= 10000000;
265
266         *sec = count.QuadPart / 1000000;
267         return count.QuadPart % 1000000;
268 }
269
270
271 /* emulate POSIX gettimeofday */
272 int
273 ldap_pvt_gettimeofday( struct timeval *tv, void *unused )
274 {
275         FILETIME ft;
276         ULARGE_INTEGER ut;
277         int sec, sec0;
278
279         GetSystemTimeAsFileTime( &ft );
280         ut.LowPart = ft.dwLowDateTime;
281         ut.HighPart = ft.dwHighDateTime;
282
283         /* convert to usec */
284         ut.QuadPart /= (TICKS_PER_SECOND / 1000000);
285
286         tv->tv_usec = ldap_pvt_gettimeusec(&sec);
287         tv->tv_sec = ut.QuadPart / 1000000 - SEC_TO_UNIX_EPOCH;
288
289         /* check for carry from microseconds */
290         sec0 = tv->tv_sec % 10;
291         if (sec0 < sec || (sec0 == 9 && !sec))
292                 tv->tv_sec++;
293
294         return 0;
295 }
296
297 /* return a broken out time, with microseconds
298  */
299 void
300 ldap_pvt_gettime( struct lutil_tm *tm )
301 {
302         SYSTEMTIME st;
303         int sec, sec0;
304         static const char daysPerMonth[] = {
305         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
306
307         GetSystemTime( &st );
308         tm->tm_usec = ldap_pvt_gettimeusec(&sec);
309         tm->tm_usub = _ldap_pvt_gt_subs;
310
311         /* any difference larger than microseconds is
312          * already reflected in st
313          */
314         tm->tm_sec = st.wSecond;
315         tm->tm_min = st.wMinute;
316         tm->tm_hour = st.wHour;
317         tm->tm_mday = st.wDay;
318         tm->tm_mon = st.wMonth - 1;
319         tm->tm_year = st.wYear - 1900;
320
321         /* check for carry from microseconds */
322         sec0 = tm->tm_sec % 10;
323         if (sec0 < sec || (sec0 == 9 && !sec)) {
324                 tm->tm_sec++;
325                 /* FIXME: we don't handle leap seconds */
326                 if (tm->tm_sec > 59) {
327                         tm->tm_sec = 0;
328                         tm->tm_min++;
329                         if (tm->tm_min > 59) {
330                                 tm->tm_min = 0;
331                                 tm->tm_hour++;
332                                 if (tm->tm_hour > 23) {
333                                         int days = daysPerMonth[tm->tm_mon];
334                                         tm->tm_hour = 0;
335                                         tm->tm_mday++;
336
337                                         /* if it's February of a leap year,
338                                          * add 1 day to this month
339                                          */
340                                         if (tm->tm_mon == 1 &&
341                                                 ((!(st.wYear % 4) && (st.wYear % 100)) ||
342                                                 !(st.wYear % 400)))
343                                                 days++;
344
345                                         if (tm->tm_mday > days) {
346                                                 tm->tm_mday = 1;
347                                                 tm->tm_mon++;
348                                                 if (tm->tm_mon > 11) {
349                                                         tm->tm_mon = 0;
350                                                         tm->tm_year++;
351                                                 }
352                                         }
353                                 }
354                         }
355                 }
356         }
357 }
358 #else
359
360 static struct timeval _ldap_pvt_gt_prevTv;
361
362 void
363 ldap_pvt_gettime( struct lutil_tm *ltm )
364 {
365         struct timeval tv;
366
367         struct tm tm;
368         time_t t;
369
370         gettimeofday( &tv, NULL );
371         t = tv.tv_sec;
372
373         LDAP_MUTEX_LOCK( &ldap_int_gettime_mutex );
374         if ( tv.tv_sec < _ldap_pvt_gt_prevTv.tv_sec
375                 || ( tv.tv_sec == _ldap_pvt_gt_prevTv.tv_sec
376                 && tv.tv_usec <= _ldap_pvt_gt_prevTv.tv_usec )) {
377                 _ldap_pvt_gt_subs++;
378         } else {
379                 _ldap_pvt_gt_subs = 0;
380                 _ldap_pvt_gt_prevTv = tv;
381         }
382         LDAP_MUTEX_UNLOCK( &ldap_int_gettime_mutex );
383
384         ltm->tm_usub = _ldap_pvt_gt_subs;
385
386         ldap_pvt_gmtime( &t, &tm );
387
388         ltm->tm_sec = tm.tm_sec;
389         ltm->tm_min = tm.tm_min;
390         ltm->tm_hour = tm.tm_hour;
391         ltm->tm_mday = tm.tm_mday;
392         ltm->tm_mon = tm.tm_mon;
393         ltm->tm_year = tm.tm_year;
394         ltm->tm_usec = tv.tv_usec;
395 }
396 #endif
397
398 size_t
399 ldap_pvt_csnstr(char *buf, size_t len, unsigned int replica, unsigned int mod)
400 {
401         struct lutil_tm tm;
402         int n;
403
404         ldap_pvt_gettime( &tm );
405
406         n = snprintf( buf, len,
407                 "%4d%02d%02d%02d%02d%02d.%06dZ#%06x#%03x#%06x",
408                 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
409                 tm.tm_min, tm.tm_sec, tm.tm_usec, tm.tm_usub, replica, mod );
410
411         if( n < 0 ) return 0;
412         return ( (size_t) n < len ) ? n : 0;
413 }
414
415 #define BUFSTART (1024-32)
416 #define BUFMAX (32*1024-32)
417
418 #if defined(LDAP_R_COMPILE)
419 static char *safe_realloc( char **buf, int len );
420
421 #if !(defined(HAVE_GETHOSTBYNAME_R) && defined(HAVE_GETHOSTBYADDR_R))
422 static int copy_hostent( struct hostent *res,
423         char **buf, struct hostent * src );
424 #endif
425 #endif
426
427 int ldap_pvt_gethostbyname_a(
428         const char *name, 
429         struct hostent *resbuf,
430         char **buf,
431         struct hostent **result,
432         int *herrno_ptr )
433 {
434 #if defined( HAVE_GETHOSTBYNAME_R )
435
436 # define NEED_SAFE_REALLOC 1   
437         int r=-1;
438         int buflen=BUFSTART;
439         *buf = NULL;
440         for(;buflen<BUFMAX;) {
441                 if (safe_realloc( buf, buflen )==NULL)
442                         return r;
443
444 #if (GETHOSTBYNAME_R_NARGS < 6)
445                 *result=gethostbyname_r( name, resbuf, *buf, buflen, herrno_ptr );
446                 r = (*result == NULL) ?  -1 : 0;
447 #else
448                 r = gethostbyname_r( name, resbuf, *buf,
449                         buflen, result, herrno_ptr );
450 #endif
451
452                 Debug( LDAP_DEBUG_TRACE, "ldap_pvt_gethostbyname_a: host=%s, r=%d\n",
453                        name, r, 0 );
454
455 #ifdef NETDB_INTERNAL
456                 if ((r<0) &&
457                         (*herrno_ptr==NETDB_INTERNAL) &&
458                         (errno==ERANGE))
459                 {
460                         buflen*=2;
461                         continue;
462                 }
463 #endif
464                 return r;
465         }
466         return -1;
467 #elif defined( LDAP_R_COMPILE )
468 # define NEED_COPY_HOSTENT   
469         struct hostent *he;
470         int     retval;
471         *buf = NULL;
472         
473         LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
474         
475         he = gethostbyname( name );
476         
477         if (he==NULL) {
478                 *herrno_ptr = h_errno;
479                 retval = -1;
480         } else if (copy_hostent( resbuf, buf, he )<0) {
481                 *herrno_ptr = -1;
482                 retval = -1;
483         } else {
484                 *result = resbuf;
485                 retval = 0;
486         }
487         
488         LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
489         
490         return retval;
491 #else   
492         *buf = NULL;
493         *result = gethostbyname( name );
494
495         if (*result!=NULL) {
496                 return 0;
497         }
498
499         *herrno_ptr = h_errno;
500         
501         return -1;
502 #endif  
503 }
504
505 #if !defined( HAVE_GETNAMEINFO ) && !defined( HAVE_HSTRERROR )
506 static const char *
507 hp_strerror( int err )
508 {
509         switch (err) {
510         case HOST_NOT_FOUND:    return _("Host not found (authoritative)");
511         case TRY_AGAIN:                 return _("Host not found (server fail?)");
512         case NO_RECOVERY:               return _("Non-recoverable failure");
513         case NO_DATA:                   return _("No data of requested type");
514 #ifdef NETDB_INTERNAL
515         case NETDB_INTERNAL:    return STRERROR( errno );
516 #endif
517         }
518         return _("Unknown resolver error");
519 }
520 #endif
521
522 int ldap_pvt_get_hname(
523         const struct sockaddr *sa,
524         int len,
525         char *name,
526         int namelen,
527         char **err )
528 {
529         int rc;
530 #if defined( HAVE_GETNAMEINFO )
531
532         LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
533         rc = getnameinfo( sa, len, name, namelen, NULL, 0, 0 );
534         LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
535         if ( rc ) *err = (char *)AC_GAI_STRERROR( rc );
536         return rc;
537
538 #else /* !HAVE_GETNAMEINFO */
539         char *addr;
540         int alen;
541         struct hostent *hp = NULL;
542 #ifdef HAVE_GETHOSTBYADDR_R
543         struct hostent hb;
544         int buflen=BUFSTART, h_errno;
545         char *buf=NULL;
546 #endif
547
548 #ifdef LDAP_PF_INET6
549         if (sa->sa_family == AF_INET6) {
550                 struct sockaddr_in6 *sin = (struct sockaddr_in6 *)sa;
551                 addr = (char *)&sin->sin6_addr;
552                 alen = sizeof(sin->sin6_addr);
553         } else
554 #endif
555         if (sa->sa_family == AF_INET) {
556                 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
557                 addr = (char *)&sin->sin_addr;
558                 alen = sizeof(sin->sin_addr);
559         } else {
560                 rc = NO_RECOVERY;
561                 *err = (char *)HSTRERROR( rc );
562                 return rc;
563         }
564 #if defined( HAVE_GETHOSTBYADDR_R )
565         for(;buflen<BUFMAX;) {
566                 if (safe_realloc( &buf, buflen )==NULL) {
567                         *err = (char *)STRERROR( ENOMEM );
568                         return ENOMEM;
569                 }
570 #if (GETHOSTBYADDR_R_NARGS < 8)
571                 hp=gethostbyaddr_r( addr, alen, sa->sa_family,
572                         &hb, buf, buflen, &h_errno );
573                 rc = (hp == NULL) ? -1 : 0;
574 #else
575                 rc = gethostbyaddr_r( addr, alen, sa->sa_family,
576                         &hb, buf, buflen, 
577                         &hp, &h_errno );
578 #endif
579 #ifdef NETDB_INTERNAL
580                 if ((rc<0) &&
581                         (h_errno==NETDB_INTERNAL) &&
582                         (errno==ERANGE))
583                 {
584                         buflen*=2;
585                         continue;
586                 }
587 #endif
588                 break;
589         }
590         if (hp) {
591                 strncpy( name, hp->h_name, namelen );
592         } else {
593                 *err = (char *)HSTRERROR( h_errno );
594         }
595         LDAP_FREE(buf);
596 #else /* HAVE_GETHOSTBYADDR_R */
597
598         LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
599         hp = gethostbyaddr( addr, alen, sa->sa_family );
600         if (hp) {
601                 strncpy( name, hp->h_name, namelen );
602                 rc = 0;
603         } else {
604                 rc = h_errno;
605                 *err = (char *)HSTRERROR( h_errno );
606         }
607         LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
608
609 #endif  /* !HAVE_GETHOSTBYADDR_R */
610         return rc;
611 #endif  /* !HAVE_GETNAMEINFO */
612 }
613
614 int ldap_pvt_gethostbyaddr_a(
615         const char *addr,
616         int len,
617         int type,
618         struct hostent *resbuf,
619         char **buf,
620         struct hostent **result,
621         int *herrno_ptr )
622 {
623 #if defined( HAVE_GETHOSTBYADDR_R )
624
625 # undef NEED_SAFE_REALLOC
626 # define NEED_SAFE_REALLOC   
627         int r=-1;
628         int buflen=BUFSTART;
629         *buf = NULL;   
630         for(;buflen<BUFMAX;) {
631                 if (safe_realloc( buf, buflen )==NULL)
632                         return r;
633 #if (GETHOSTBYADDR_R_NARGS < 8)
634                 *result=gethostbyaddr_r( addr, len, type,
635                         resbuf, *buf, buflen, herrno_ptr );
636                 r = (*result == NULL) ? -1 : 0;
637 #else
638                 r = gethostbyaddr_r( addr, len, type,
639                         resbuf, *buf, buflen, 
640                         result, herrno_ptr );
641 #endif
642
643 #ifdef NETDB_INTERNAL
644                 if ((r<0) &&
645                         (*herrno_ptr==NETDB_INTERNAL) &&
646                         (errno==ERANGE))
647                 {
648                         buflen*=2;
649                         continue;
650                 }
651 #endif
652                 return r;
653         }
654         return -1;
655 #elif defined( LDAP_R_COMPILE )
656 # undef NEED_COPY_HOSTENT
657 # define NEED_COPY_HOSTENT   
658         struct hostent *he;
659         int     retval;
660         *buf = NULL;   
661         
662         LDAP_MUTEX_LOCK( &ldap_int_resolv_mutex );
663         he = gethostbyaddr( addr, len, type );
664         
665         if (he==NULL) {
666                 *herrno_ptr = h_errno;
667                 retval = -1;
668         } else if (copy_hostent( resbuf, buf, he )<0) {
669                 *herrno_ptr = -1;
670                 retval = -1;
671         } else {
672                 *result = resbuf;
673                 retval = 0;
674         }
675         LDAP_MUTEX_UNLOCK( &ldap_int_resolv_mutex );
676         
677         return retval;
678
679 #else /* gethostbyaddr() */
680         *buf = NULL;   
681         *result = gethostbyaddr( addr, len, type );
682
683         if (*result!=NULL) {
684                 return 0;
685         }
686         return -1;
687 #endif  
688 }
689 /* 
690  * ldap_int_utils_init() should be called before any other function.
691  */
692
693 void ldap_int_utils_init( void )
694 {
695         static int done=0;
696         if (done)
697           return;
698         done=1;
699
700 #ifdef LDAP_R_COMPILE
701 #if !defined( USE_CTIME_R ) && !defined( HAVE_REENTRANT_FUNCTIONS )
702         ldap_pvt_thread_mutex_init( &ldap_int_ctime_mutex );
703 #endif
704 #if !defined( USE_GMTIME_R ) && !defined( USE_LOCALTIME_R )
705         ldap_pvt_thread_mutex_init( &ldap_int_gmtime_mutex );
706 #endif
707         ldap_pvt_thread_mutex_init( &ldap_int_resolv_mutex );
708
709         ldap_pvt_thread_mutex_init( &ldap_int_hostname_mutex );
710
711         ldap_pvt_thread_mutex_init( &ldap_int_gettime_mutex );
712
713 #ifdef HAVE_GSSAPI
714         ldap_pvt_thread_mutex_init( &ldap_int_gssapi_mutex );
715 #endif
716 #endif
717
718         /* call other module init functions here... */
719 }
720
721 #if defined( NEED_COPY_HOSTENT )
722 # undef NEED_SAFE_REALLOC
723 #define NEED_SAFE_REALLOC
724
725 static char *cpy_aliases(
726         char ***tgtio,
727         char *buf,
728         char **src )
729 {
730         int len;
731         char **tgt=*tgtio;
732         for( ; (*src) ; src++ ) {
733                 len = strlen( *src ) + 1;
734                 AC_MEMCPY( buf, *src, len );
735                 *tgt++=buf;
736                 buf+=len;
737         }
738         *tgtio=tgt;   
739         return buf;
740 }
741
742 static char *cpy_addresses(
743         char ***tgtio,
744         char *buf,
745         char **src,
746         int len )
747 {
748         char **tgt=*tgtio;
749         for( ; (*src) ; src++ ) {
750                 AC_MEMCPY( buf, *src, len );
751                 *tgt++=buf;
752                 buf+=len;
753         }
754         *tgtio=tgt;      
755         return buf;
756 }
757
758 static int copy_hostent(
759         struct hostent *res,
760         char **buf,
761         struct hostent * src )
762 {
763         char    **p;
764         char    **tp;
765         char    *tbuf;
766         int     name_len;
767         int     n_alias=0;
768         int     total_alias_len=0;
769         int     n_addr=0;
770         int     total_addr_len=0;
771         int     total_len;
772           
773         /* calculate the size needed for the buffer */
774         name_len = strlen( src->h_name ) + 1;
775         
776         if( src->h_aliases != NULL ) {
777                 for( p = src->h_aliases; (*p) != NULL; p++ ) {
778                         total_alias_len += strlen( *p ) + 1;
779                         n_alias++; 
780                 }
781         }
782
783         if( src->h_addr_list != NULL ) {
784                 for( p = src->h_addr_list; (*p) != NULL; p++ ) {
785                         n_addr++;
786                 }
787                 total_addr_len = n_addr * src->h_length;
788         }
789         
790         total_len = (n_alias + n_addr + 2) * sizeof( char * ) +
791                 total_addr_len + total_alias_len + name_len;
792         
793         if (safe_realloc( buf, total_len )) {                    
794                 tp = (char **) *buf;
795                 tbuf = *buf + (n_alias + n_addr + 2) * sizeof( char * );
796                 AC_MEMCPY( res, src, sizeof( struct hostent ) );
797                 /* first the name... */
798                 AC_MEMCPY( tbuf, src->h_name, name_len );
799                 res->h_name = tbuf; tbuf+=name_len;
800                 /* now the aliases */
801                 res->h_aliases = tp;
802                 if ( src->h_aliases != NULL ) {
803                         tbuf = cpy_aliases( &tp, tbuf, src->h_aliases );
804                 }
805                 *tp++=NULL;
806                 /* finally the addresses */
807                 res->h_addr_list = tp;
808                 if ( src->h_addr_list != NULL ) {
809                         tbuf = cpy_addresses( &tp, tbuf, src->h_addr_list, src->h_length );
810                 }
811                 *tp++=NULL;
812                 return 0;
813         }
814         return -1;
815 }
816 #endif
817
818 #if defined( NEED_SAFE_REALLOC )
819 static char *safe_realloc( char **buf, int len )
820 {
821         char *tmpbuf;
822         tmpbuf = LDAP_REALLOC( *buf, len );
823         if (tmpbuf) {
824                 *buf=tmpbuf;
825         } 
826         return tmpbuf;
827 }
828 #endif
829
830 char * ldap_pvt_get_fqdn( char *name )
831 {
832         char *fqdn, *ha_buf;
833         char hostbuf[MAXHOSTNAMELEN+1];
834         struct hostent *hp, he_buf;
835         int rc, local_h_errno;
836
837         if( name == NULL ) {
838                 if( gethostname( hostbuf, MAXHOSTNAMELEN ) == 0 ) {
839                         hostbuf[MAXHOSTNAMELEN] = '\0';
840                         name = hostbuf;
841                 } else {
842                         name = "localhost";
843                 }
844         }
845
846         rc = ldap_pvt_gethostbyname_a( name,
847                 &he_buf, &ha_buf, &hp, &local_h_errno );
848
849         if( rc < 0 || hp == NULL || hp->h_name == NULL ) {
850                 fqdn = LDAP_STRDUP( name );
851         } else {
852                 fqdn = LDAP_STRDUP( hp->h_name );
853         }
854
855         LDAP_FREE( ha_buf );
856         return fqdn;
857 }
858
859 #if ( defined( HAVE_GETADDRINFO ) || defined( HAVE_GETNAMEINFO ) ) \
860         && !defined( HAVE_GAI_STRERROR )
861 char *ldap_pvt_gai_strerror (int code) {
862         static struct {
863                 int code;
864                 const char *msg;
865         } values[] = {
866 #ifdef EAI_ADDRFAMILY
867                 { EAI_ADDRFAMILY, N_("Address family for hostname not supported") },
868 #endif
869                 { EAI_AGAIN, N_("Temporary failure in name resolution") },
870                 { EAI_BADFLAGS, N_("Bad value for ai_flags") },
871                 { EAI_FAIL, N_("Non-recoverable failure in name resolution") },
872                 { EAI_FAMILY, N_("ai_family not supported") },
873                 { EAI_MEMORY, N_("Memory allocation failure") },
874 #ifdef EAI_NODATA
875                 { EAI_NODATA, N_("No address associated with hostname") },
876 #endif    
877                 { EAI_NONAME, N_("Name or service not known") },
878                 { EAI_SERVICE, N_("Servname not supported for ai_socktype") },
879                 { EAI_SOCKTYPE, N_("ai_socktype not supported") },
880 #ifdef EAI_SYSTEM
881                 { EAI_SYSTEM, N_("System error") },
882 #endif
883                 { 0, NULL }
884         };
885
886         int i;
887
888         for ( i = 0; values[i].msg != NULL; i++ ) {
889                 if ( values[i].code == code ) {
890                         return (char *) _(values[i].msg);
891                 }
892         }
893         
894         return _("Unknown error");
895 }
896 #endif