2 * Copyright (c) 1995 Regents of the University of Michigan.
5 * ldap_getdxbyname - retrieve DX records from the DNS (from TXT records for now)
16 #include <ac/socket.h>
17 #include <ac/string.h>
24 static char ** decode_answer LDAP_P(( unsigned char *answer, int len ));
26 #define MAX_TO_SORT 32
30 * ldap_getdxbyname - lookup DNS DX records for domain and return an ordered
34 ldap_getdxbyname( char *domain )
36 unsigned char buf[ PACKETSZ ];
40 Debug( LDAP_DEBUG_TRACE, "ldap_getdxbyname( %s )\n", domain, 0, 0 );
42 memset( buf, 0, sizeof( buf ));
44 if (( rc = res_search( domain, C_IN, T_TXT, buf, sizeof( buf ))) < 0
45 || ( dxs = decode_answer( buf, rc )) == NULL ) {
47 * punt: return list conisting of the original domain name only
49 if (( dxs = (char **)malloc( 2 * sizeof( char * ))) == NULL ||
50 ( dxs[ 0 ] = strdup( domain )) == NULL ) {
65 decode_answer( unsigned char *answer, int len )
68 char buf[ 256 ], **dxs;
69 unsigned char *eom, *p;
70 int ancount, err, rc, type, class, dx_count, rr_len;
71 int dx_pref[ MAX_TO_SORT ];
75 if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
79 #endif /* LDAP_DEBUG */
82 hp = (HEADER *)answer;
85 if ( ntohs( hp->qdcount ) != 1 ) {
86 h_errno = NO_RECOVERY;
90 ancount = ntohs( hp->ancount );
99 p = answer + HFIXEDSZ;
100 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
101 h_errno = NO_RECOVERY;
104 p += ( rc + QFIXEDSZ );
107 * pull out the answers we are interested in
110 while ( ancount > 0 && err == 0 && p < eom ) {
111 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
115 p += rc; /* skip over name */
116 type = _getshort( p );
118 class = _getshort( p );
120 p += INT32SZ; /* skip over TTL */
121 rr_len = _getshort( p );
123 if ( class == C_IN && type == T_TXT ) {
124 int i, n, pref, txt_len;
128 while ( q < (char *)p + rr_len && err == 0 ) {
129 if ( *q >= 3 && strncasecmp( q + 1, "dx:", 3 ) == 0 ) {
132 while ( isspace( *r )) {
137 while ( isdigit( *r )) {
139 pref += ( *r - '0' );
143 if ( dx_count < MAX_TO_SORT - 1 ) {
144 dx_pref[ dx_count ] = pref;
146 while ( isspace( *r )) {
150 if ( dx_count == 0 ) {
151 dxs = (char **)malloc( 2 * sizeof( char * ));
153 dxs = (char **)realloc( dxs,
154 ( dx_count + 2 ) * sizeof( char * ));
156 if ( dxs == NULL || ( dxs[ dx_count ] =
157 (char *)calloc( 1, txt_len + 1 )) == NULL ) {
161 memcpy( dxs[ dx_count ], r, txt_len );
162 dxs[ ++dx_count ] = NULL;
164 q += ( *q + 1 ); /* move past last TXT record */
171 if ( dx_count == 0 ) {
175 * sort records based on associated preference value
177 int i, j, sort_count, tmp_pref;
180 sort_count = ( dx_count < MAX_TO_SORT ) ? dx_count : MAX_TO_SORT;
181 for ( i = 0; i < sort_count; ++i ) {
182 for ( j = i + 1; j < sort_count; ++j ) {
183 if ( dx_pref[ i ] > dx_pref[ j ] ) {
184 tmp_pref = dx_pref[ i ];
185 dx_pref[ i ] = dx_pref[ j ];
186 dx_pref[ j ] = tmp_pref;
200 #endif /* LDAP_DNS */