5 * Copyright (c) 1995 Regents of the University of Michigan.
8 * ldap_getdxbyname - retrieve DX records from the DNS (from TXT records for now)
15 #include <ac/socket.h>
16 #include <ac/string.h>
23 static char ** decode_answer LDAP_P(( unsigned char *answer, int len ));
26 extern char *h_errlist[];
29 #define MAX_TO_SORT 32
33 * ldap_getdxbyname - lookup DNS DX records for domain and return an ordered
37 ldap_getdxbyname( char *domain )
39 unsigned char buf[ PACKETSZ ];
43 Debug( LDAP_DEBUG_TRACE, "ldap_getdxbyname( %s )\n", domain, 0, 0 );
45 memset( buf, 0, sizeof( buf ));
47 if (( rc = res_search( domain, C_IN, T_TXT, buf, sizeof( buf ))) < 0
48 || ( dxs = decode_answer( buf, rc )) == NULL ) {
50 * punt: return list conisting of the original domain name only
52 if (( dxs = (char **)malloc( 2 * sizeof( char * ))) == NULL ||
53 ( dxs[ 0 ] = strdup( domain )) == NULL ) {
68 decode_answer( unsigned char *answer, int len )
71 char buf[ 256 ], **dxs;
72 unsigned char *eom, *p;
73 int ancount, err, rc, type, class, dx_count, rr_len;
74 int dx_pref[ MAX_TO_SORT ];
78 if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
82 #endif /* LDAP_DEBUG */
85 hp = (HEADER *)answer;
88 if ( ntohs( hp->qdcount ) != 1 ) {
89 h_errno = NO_RECOVERY;
93 ancount = ntohs( hp->ancount );
100 * skip over the query
102 p = answer + HFIXEDSZ;
103 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
104 h_errno = NO_RECOVERY;
107 p += ( rc + QFIXEDSZ );
110 * pull out the answers we are interested in
113 while ( ancount > 0 && err == 0 && p < eom ) {
114 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
118 p += rc; /* skip over name */
119 type = _getshort( p );
121 class = _getshort( p );
123 p += INT32SZ; /* skip over TTL */
124 rr_len = _getshort( p );
126 if ( class == C_IN && type == T_TXT ) {
127 int i, n, pref, txt_len;
131 while ( q < (char *)p + rr_len && err == 0 ) {
132 if ( *q >= 3 && strncasecmp( q + 1, "dx:", 3 ) == 0 ) {
135 while ( isspace( *r )) {
140 while ( isdigit( *r )) {
142 pref += ( *r - '0' );
146 if ( dx_count < MAX_TO_SORT - 1 ) {
147 dx_pref[ dx_count ] = pref;
149 while ( isspace( *r )) {
153 if ( dx_count == 0 ) {
154 dxs = (char **)malloc( 2 * sizeof( char * ));
156 dxs = (char **)realloc( dxs,
157 ( dx_count + 2 ) * sizeof( char * ));
159 if ( dxs == NULL || ( dxs[ dx_count ] =
160 (char *)calloc( 1, txt_len + 1 )) == NULL ) {
164 memcpy( dxs[ dx_count ], r, txt_len );
165 dxs[ ++dx_count ] = NULL;
167 q += ( *q + 1 ); /* move past last TXT record */
174 if ( dx_count == 0 ) {
178 * sort records based on associated preference value
180 int i, j, sort_count, tmp_pref;
183 sort_count = ( dx_count < MAX_TO_SORT ) ? dx_count : MAX_TO_SORT;
184 for ( i = 0; i < sort_count; ++i ) {
185 for ( j = i + 1; j < sort_count; ++j ) {
186 if ( dx_pref[ i ] > dx_pref[ j ] ) {
187 tmp_pref = dx_pref[ i ];
188 dx_pref[ i ] = dx_pref[ j ];
189 dx_pref[ j ] = tmp_pref;
203 #endif /* LDAP_DNS */