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>
22 static char ** decode_answer LDAP_P(( unsigned char *answer, int len ));
24 #define MAX_TO_SORT 32
28 * ldap_getdxbyname - lookup DNS DX records for domain and return an ordered
32 ldap_getdxbyname( char *domain )
34 unsigned char buf[ PACKETSZ ];
38 Debug( LDAP_DEBUG_TRACE, "ldap_getdxbyname( %s )\n", domain, 0, 0 );
40 memset( buf, 0, sizeof( buf ));
42 if (( rc = res_search( domain, C_IN, T_TXT, buf, sizeof( buf ))) < 0
43 || ( dxs = decode_answer( buf, rc )) == NULL ) {
45 * punt: return list conisting of the original domain name only
47 if (( dxs = (char **)malloc( 2 * sizeof( char * ))) == NULL ||
48 ( dxs[ 0 ] = strdup( domain )) == NULL ) {
63 decode_answer( unsigned char *answer, int len )
66 char buf[ 256 ], **dxs;
67 unsigned char *eom, *p;
68 int ancount, err, rc, type, class, dx_count, rr_len;
69 int dx_pref[ MAX_TO_SORT ];
73 if ( ldap_debug & LDAP_DEBUG_PACKETS ) {
77 #endif /* LDAP_DEBUG */
80 hp = (HEADER *)answer;
83 if ( ntohs( hp->qdcount ) != 1 ) {
84 h_errno = NO_RECOVERY;
88 ancount = ntohs( hp->ancount );
97 p = answer + HFIXEDSZ;
98 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
99 h_errno = NO_RECOVERY;
102 p += ( rc + QFIXEDSZ );
105 * pull out the answers we are interested in
108 while ( ancount > 0 && err == 0 && p < eom ) {
109 if (( rc = dn_expand( answer, eom, p, buf, sizeof( buf ))) < 0 ) {
113 p += rc; /* skip over name */
114 type = _getshort( p );
116 class = _getshort( p );
118 p += INT32SZ; /* skip over TTL */
119 rr_len = _getshort( p );
121 if ( class == C_IN && type == T_TXT ) {
122 int i, n, pref, txt_len;
126 while ( q < (char *)p + rr_len && err == 0 ) {
127 if ( *q >= 3 && strncasecmp( q + 1, "dx:", 3 ) == 0 ) {
130 while ( isspace( *r )) {
135 while ( isdigit( *r )) {
137 pref += ( *r - '0' );
141 if ( dx_count < MAX_TO_SORT - 1 ) {
142 dx_pref[ dx_count ] = pref;
144 while ( isspace( *r )) {
148 if ( dx_count == 0 ) {
149 dxs = (char **)malloc( 2 * sizeof( char * ));
151 dxs = (char **)realloc( dxs,
152 ( dx_count + 2 ) * sizeof( char * ));
154 if ( dxs == NULL || ( dxs[ dx_count ] =
155 (char *)calloc( 1, txt_len + 1 )) == NULL ) {
159 memcpy( dxs[ dx_count ], r, txt_len );
160 dxs[ ++dx_count ] = NULL;
162 q += ( *q + 1 ); /* move past last TXT record */
169 if ( dx_count == 0 ) {
173 * sort records based on associated preference value
175 int i, j, sort_count, tmp_pref;
178 sort_count = ( dx_count < MAX_TO_SORT ) ? dx_count : MAX_TO_SORT;
179 for ( i = 0; i < sort_count; ++i ) {
180 for ( j = i + 1; j < sort_count; ++j ) {
181 if ( dx_pref[ i ] > dx_pref[ j ] ) {
182 tmp_pref = dx_pref[ i ];
183 dx_pref[ i ] = dx_pref[ j ];
184 dx_pref[ j ] = tmp_pref;
198 #endif /* LDAP_DNS */