gloox  1.1-svn
dns.cpp
1 /*
2  Copyright (c) 2005-2009 by Jakob Schroeter <js@camaya.net>
3  This file is part of the gloox library. http://camaya.net/gloox
4 
5  This software is distributed under a license. The full license
6  agreement can be found in the file LICENSE in this distribution.
7  This software may not be copied, modified, sold or distributed
8  other than expressed in the named license agreement.
9 
10  This software is distributed without any warranty.
11 */
12 
13 
14 #include "config.h"
15 
16 #include "gloox.h"
17 #include "dns.h"
18 #include "util.h"
19 
20 #ifndef _WIN32_WCE
21 # include <sys/types.h>
22 #endif
23 
24 #include <stdio.h>
25 
26 #if ( !defined( _WIN32 ) && !defined( _WIN32_WCE ) ) || defined( __SYMBIAN32__ )
27 # include <netinet/in.h>
28 # include <arpa/nameser.h>
29 # include <resolv.h>
30 # include <netdb.h>
31 # include <arpa/inet.h>
32 # include <sys/socket.h>
33 # include <sys/un.h>
34 # include <unistd.h>
35 # include <errno.h>
36 #endif
37 
38 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
39 # include <winsock.h>
40 #elif defined( _WIN32_WCE )
41 # include <winsock2.h>
42 #endif
43 
44 #ifdef HAVE_WINDNS_H
45 # include <windns.h>
46 #endif
47 
48 #define SRV_COST (RRFIXEDSZ+0)
49 #define SRV_WEIGHT (RRFIXEDSZ+2)
50 #define SRV_PORT (RRFIXEDSZ+4)
51 #define SRV_SERVER (RRFIXEDSZ+6)
52 #define SRV_FIXEDSZ (RRFIXEDSZ+6)
53 
54 #ifndef T_SRV
55 # define T_SRV 33
56 #endif
57 
58 // mingw
59 #ifndef DNS_TYPE_SRV
60 # define DNS_TYPE_SRV 33
61 #endif
62 
63 #ifndef NS_CMPRSFLGS
64 # define NS_CMPRSFLGS 0xc0
65 #endif
66 
67 #ifndef C_IN
68 # define C_IN 1
69 #endif
70 
71 #ifndef INVALID_SOCKET
72 # define INVALID_SOCKET -1
73 #endif
74 
75 #define XMPP_PORT 5222
76 
77 namespace gloox
78 {
79 
80 #if defined( HAVE_RES_QUERYDOMAIN ) && defined( HAVE_DN_SKIPNAME ) && defined( HAVE_RES_QUERY )
81  DNS::HostMap DNS::resolve( const std::string& service, const std::string& proto,
82  const std::string& domain, const LogSink& logInstance )
83  {
84  buffer srvbuf;
85  bool error = false;
86 
87  const std::string dname = "_" + service + "._" + proto;
88 
89  if( !domain.empty() )
90  srvbuf.len = res_querydomain( dname.c_str(), const_cast<char*>( domain.c_str() ),
91  C_IN, T_SRV, srvbuf.buf, NS_PACKETSZ );
92  else
93  srvbuf.len = res_query( dname.c_str(), C_IN, T_SRV, srvbuf.buf, NS_PACKETSZ );
94 
95  if( srvbuf.len < 0 )
96  return defaultHostMap( domain, logInstance );
97 
98  HEADER* hdr = (HEADER*)srvbuf.buf;
99  unsigned char* here = srvbuf.buf + NS_HFIXEDSZ;
100 
101  if( srvbuf.len < NS_HFIXEDSZ )
102  error = true;
103 
104  if( hdr->rcode >= 1 && hdr->rcode <= 5 )
105  error = true;
106 
107  if( ntohs( hdr->ancount ) == 0 )
108  error = true;
109 
110  if( ntohs( hdr->ancount ) > NS_PACKETSZ )
111  error = true;
112 
113  int cnt;
114  for( cnt = ntohs( hdr->qdcount ); cnt > 0; --cnt )
115  {
116  int strlen = dn_skipname( here, srvbuf.buf + srvbuf.len );
117  here += strlen + NS_QFIXEDSZ;
118  }
119 
120  unsigned char* srv[NS_PACKETSZ];
121  int srvnum = 0;
122  for( cnt = ntohs( hdr->ancount ); cnt > 0; --cnt )
123  {
124  int strlen = dn_skipname( here, srvbuf.buf + srvbuf.len );
125  here += strlen;
126  srv[srvnum++] = here;
127  here += SRV_FIXEDSZ;
128  here += dn_skipname( here, srvbuf.buf + srvbuf.len );
129  }
130 
131  if( error )
132  {
133  return defaultHostMap( domain, logInstance );
134  }
135 
136  // (q)sort here
137 
138  HostMap servers;
139  for( cnt = 0; cnt < srvnum; ++cnt )
140  {
141  char srvname[NS_MAXDNAME];
142  srvname[0] = '\0';
143 
144  if( dn_expand( srvbuf.buf, srvbuf.buf + NS_PACKETSZ,
145  srv[cnt] + SRV_SERVER, srvname, NS_MAXDNAME ) < 0
146  || !(*srvname) )
147  continue;
148 
149  unsigned char* c = srv[cnt] + SRV_PORT;
150  servers.insert( std::make_pair( (char*)srvname, ntohs( c[1] << 8 | c[0] ) ) );
151  }
152 
153  if( !servers.size() )
154  return defaultHostMap( domain, logInstance );
155 
156  return servers;
157  }
158 
159 #elif defined( _WIN32 ) && defined( HAVE_WINDNS_H )
160  DNS::HostMap DNS::resolve( const std::string& service, const std::string& proto,
161  const std::string& domain, const LogSink& logInstance )
162  {
163  const std::string dname = "_" + service + "._" + proto + "." + domain;
164  bool error = false;
165 
166  DNS::HostMap servers;
167  DNS_RECORD* pRecord = NULL;
168  DNS_STATUS status = DnsQuery_UTF8( dname.c_str(), DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &pRecord, NULL );
169  if( status == ERROR_SUCCESS )
170  {
171  DNS_RECORD* pRec = pRecord;
172  do
173  {
174  if( pRec->wType == DNS_TYPE_SRV )
175  {
176  servers[pRec->Data.SRV.pNameTarget] = pRec->Data.SRV.wPort;
177  }
178  pRec = pRec->pNext;
179  }
180  while( pRec != NULL );
181  DnsRecordListFree( pRecord, DnsFreeRecordList );
182  }
183  else
184  {
185  logInstance.warn( LogAreaClassDns, "DnsQuery_UTF8() failed: " + util::int2string( status ) );
186  error = true;
187  }
188 
189  if( error || !servers.size() )
190  {
191  servers = defaultHostMap( domain, logInstance );
192  }
193 
194  return servers;
195  }
196 
197 #else
198  DNS::HostMap DNS::resolve( const std::string& /*service*/, const std::string& /*proto*/,
199  const std::string& domain, const LogSink& logInstance )
200  {
201  logInstance.warn( LogAreaClassDns, "Notice: gloox does not support SRV "
202  "records on this platform. Using A records instead." );
203  return defaultHostMap( domain, logInstance );
204  }
205 #endif
206 
207  DNS::HostMap DNS::defaultHostMap( const std::string& domain, const LogSink& logInstance )
208  {
209  HostMap server;
210 
211  logInstance.warn( LogAreaClassDns, "Notice: no SRV record found for "
212  + domain + ", using default port." );
213 
214  if( !domain.empty() )
215  server[domain] = XMPP_PORT;
216 
217  return server;
218  }
219 
220 #ifdef HAVE_GETADDRINFO
221  void DNS::resolve( struct addrinfo** res, const std::string& service, const std::string& proto,
222  const std::string& domain, const LogSink& logInstance )
223  {
224  logInstance.dbg( LogAreaClassDns, "Resolving: _" + service + "._" + proto + "." + domain );
225  struct addrinfo hints;
226  if( proto == "tcp" )
227  hints.ai_socktype = SOCK_STREAM;
228  else if( proto == "udp" )
229  hints.ai_socktype = SOCK_DGRAM;
230  else
231  {
232  logInstance.err( LogAreaClassDns, "Unknown/Invalid protocol: " + proto );
233  }
234  memset( &hints, '\0', sizeof( hints ) );
235  hints.ai_flags = AI_ADDRCONFIG | AI_CANONNAME;
236  hints.ai_socktype = SOCK_STREAM;
237  int e = getaddrinfo( domain.c_str(), service.c_str(), &hints, res );
238  if( e )
239  logInstance.err( LogAreaClassDns, "getaddrinfo() failed" );
240  }
241 
242  int DNS::connect( const std::string& host, const LogSink& logInstance )
243  {
244  struct addrinfo* results = 0;
245 
246  resolve( &results, host, logInstance );
247  if( !results )
248  {
249  logInstance.err( LogAreaClassDns, "host not found: " + host );
250  return -ConnDnsError;
251  }
252 
253  struct addrinfo* runp = results;
254  while( runp )
255  {
256  int fd = DNS::connect( runp, logInstance );
257  if( fd >= 0 )
258  return fd;
259 
260  runp = runp->ai_next;
261  }
262 
263  freeaddrinfo( results );
264 
265  return -ConnConnectionRefused;
266  }
267 
268  int DNS::connect( struct addrinfo* res, const LogSink& logInstance )
269  {
270  if( !res )
271  return -1;
272 
273  int fd = getSocket( res->ai_family, res->ai_socktype, res->ai_protocol, logInstance );
274  if( fd < 0 )
275  return fd;
276 
277  if( ::connect( fd, res->ai_addr, res->ai_addrlen ) == 0 )
278  {
279  char ip[NI_MAXHOST];
280  char port[NI_MAXSERV];
281 
282  if( getnameinfo( res->ai_addr, sizeof( sockaddr ),
283  ip, sizeof( ip ),
284  port, sizeof( port ),
285  NI_NUMERICHOST | NI_NUMERICSERV ) )
286  {
287  //FIXME do we need to handle this? How? Can it actually happen at all?
288 // printf( "could not get numeric hostname");
289  }
290 
291  if( res->ai_canonname )
292  logInstance.dbg( LogAreaClassDns, "Connecting to " + std::string( res->ai_canonname )
293  + " (" + ip + "), port " + port );
294  else
295  logInstance.dbg( LogAreaClassDns, "Connecting to " + ip + ":" + port );
296 
297  return fd;
298  }
299 
300  std::string message = "connect() failed. "
301 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
302  "WSAGetLastError: " + util::int2string( ::WSAGetLastError() );
303 #else
304  "errno: " + util::int2string( errno );
305 #endif
306  logInstance.dbg( LogAreaClassDns, message );
307 
308  closeSocket( fd, logInstance );
309  return -ConnConnectionRefused;
310  }
311 
312 #else
313 
314  int DNS::connect( const std::string& host, const LogSink& logInstance )
315  {
316  HostMap hosts = resolve( host, logInstance );
317  if( hosts.size() == 0 )
318  return -ConnDnsError;
319 
320  HostMap::const_iterator it = hosts.begin();
321  for( ; it != hosts.end(); ++it )
322  {
323  int fd = DNS::connect( (*it).first, (*it).second, logInstance );
324  if( fd >= 0 )
325  return fd;
326  }
327 
328  return -ConnConnectionRefused;
329  }
330 #endif
331 
332  int DNS::getSocket( const LogSink& logInstance )
333  {
334 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
335  WSADATA wsaData;
336  if( WSAStartup( MAKEWORD( 1, 1 ), &wsaData ) != 0 )
337  {
338  logInstance.dbg( LogAreaClassDns, "WSAStartup() failed. WSAGetLastError: "
339  + util::int2string( ::WSAGetLastError() ) );
340  return -ConnDnsError;
341  }
342 #endif
343 
344  int protocol = IPPROTO_TCP;
345  struct protoent* prot;
346  if( ( prot = getprotobyname( "tcp" ) ) != 0 )
347  {
348  protocol = prot->p_proto;
349  }
350  else
351  {
352  std::string message = "getprotobyname( \"tcp\" ) failed. "
353 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
354  "WSAGetLastError: " + util::int2string( ::WSAGetLastError() )
355 #else
356  "errno: " + util::int2string( errno );
357 #endif
358  + ". Falling back to IPPROTO_TCP: " + util::int2string( IPPROTO_TCP );
359  logInstance.dbg( LogAreaClassDns, message );
360 
361  // Do not return an error. We'll fall back to IPPROTO_TCP.
362  }
363 
364  return getSocket( PF_INET, SOCK_STREAM, protocol, logInstance );
365  }
366 
367  int DNS::getSocket( int af, int socktype, int proto, const LogSink& logInstance )
368  {
369 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
370  SOCKET fd;
371 #else
372  int fd;
373 #endif
374  if( ( fd = socket( af, socktype, proto ) ) == INVALID_SOCKET )
375  {
376  std::string message = "getSocket( "
377  + util::int2string( af ) + ", "
378  + util::int2string( socktype ) + ", "
379  + util::int2string( proto )
380  + " ) failed. "
381 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
382  "WSAGetLastError: " + util::int2string( ::WSAGetLastError() );
383 #else
384  "errno: " + util::int2string( errno );
385 #endif
386  logInstance.dbg( LogAreaClassDns, message );
387 
388  cleanup( logInstance );
389  return -ConnSocketError;
390  }
391 
392 #ifdef HAVE_SETSOCKOPT
393  int timeout = 5000;
394  setsockopt( fd, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof( timeout ) );
395  setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (char*)&timeout, sizeof( timeout ) );
396 #endif
397 
398  return (int)fd;
399  }
400 
401  int DNS::connect( const std::string& host, int port, const LogSink& logInstance )
402  {
403  int fd = getSocket( logInstance );
404  if( fd < 0 )
405  return fd;
406 
407  struct hostent* h;
408  if( ( h = gethostbyname( host.c_str() ) ) == 0 )
409  {
410  logInstance.dbg( LogAreaClassDns, "gethostbyname() failed for " + host + "." );
411  cleanup( logInstance );
412  return -ConnDnsError;
413  }
414 
415  struct sockaddr_in target;
416  target.sin_family = AF_INET;
417  target.sin_port = htons( static_cast<unsigned short int>( port ) );
418 
419  if( h->h_length != sizeof( struct in_addr ) )
420  {
421  logInstance.dbg( LogAreaClassDns, "gethostbyname() returned unexpected structure." );
422  cleanup( logInstance );
423  return -ConnDnsError;
424  }
425  else
426  {
427  memcpy( &target.sin_addr, h->h_addr, sizeof( struct in_addr ) );
428  }
429 
430  logInstance.dbg( LogAreaClassDns, "Connecting to " + host
431  + " (" + inet_ntoa( target.sin_addr ) + ":" + util::int2string( port ) + ")" );
432 
433  memset( target.sin_zero, '\0', 8 );
434  if( ::connect( fd, (struct sockaddr *)&target, sizeof( struct sockaddr ) ) == 0 )
435  {
436  logInstance.dbg( LogAreaClassDns, "Connected to " + host + " ("
437  + inet_ntoa( target.sin_addr ) + ":" + util::int2string( port ) + ")" );
438  return fd;
439  }
440 
441  std::string message = "Connection to " + host + " ("
442  + inet_ntoa( target.sin_addr ) + ":" + util::int2string( port ) + ") failed. "
443 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
444  "WSAGetLastError: " + util::int2string( ::WSAGetLastError() );
445 #else
446  "errno: " + util::int2string( errno );
447 #endif
448  logInstance.dbg( LogAreaClassDns, message );
449 
450  closeSocket( fd, logInstance );
451  return -ConnConnectionRefused;
452  }
453 
454  void DNS::closeSocket( int fd, const LogSink& logInstance )
455  {
456 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
457  int result = closesocket( fd );
458 #else
459  int result = close( fd );
460 #endif
461 
462  if( result != 0 )
463  {
464  std::string message = "closeSocket() failed. "
465 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
466  "WSAGetLastError: " + util::int2string( ::WSAGetLastError() );
467 #else
468  "errno: " + util::int2string( errno );
469 #endif
470  logInstance.dbg( LogAreaClassDns, message );
471  }
472  }
473 
474  void DNS::cleanup( const LogSink& logInstance )
475  {
476 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
477  if( WSACleanup() != 0 )
478  {
479  logInstance.dbg( LogAreaClassDns, "WSACleanup() failed. WSAGetLastError: "
480  + util::int2string( ::WSAGetLastError() ) );
481  }
482 #else
483  (void)logInstance;
484 #endif
485  }
486 
487 }