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