iphone_net.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /*
  2. Copyright (C) 2009-2011 id Software LLC, a ZeniMax Media company.
  3. Copyright (C) 2009 Id Software, Inc.
  4. This program is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License
  6. as published by the Free Software Foundation; either version 2
  7. of the License, or (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  15. */
  16. /*
  17. Deal with all the DNS / bonjour service discovery and resolution
  18. */
  19. #include "../doomiphone.h"
  20. #include <dns_sd.h>
  21. #include <netdb.h> // for gethostbyname
  22. #include <net/if.h> // for if_nameindex()
  23. DNSServiceRef browseRef;
  24. DNSServiceRef clientServiceRef;
  25. DNSServiceRef serviceRef;
  26. boolean serviceRefValid;
  27. typedef struct {
  28. int interfaceIndex;
  29. char browseName[1024];
  30. char browseRegtype[1024];
  31. char browseDomain[1024];
  32. } service_t;
  33. boolean localServer;
  34. // we can find services on both WiFi and Bluetooth interfaces
  35. #define MAX_SERVICE_INTEFACES 4
  36. service_t serviceInterfaces[MAX_SERVICE_INTEFACES];
  37. boolean gotServerAddress;
  38. struct sockaddr resolvedServerAddress;
  39. static const char *serviceName = "_DoomServer._udp.";
  40. int InterfaceIndexForName( const char *ifname );
  41. void DNSServiceRegisterReplyCallback (
  42. DNSServiceRef sdRef,
  43. DNSServiceFlags flags,
  44. DNSServiceErrorType errorCode,
  45. const char *name,
  46. const char *regtype,
  47. const char *domain,
  48. void *context ) {
  49. if ( errorCode == kDNSServiceErr_NoError ) {
  50. localServer = true;
  51. } else {
  52. localServer = false;
  53. }
  54. }
  55. boolean RegisterGameService() {
  56. DNSServiceErrorType err = DNSServiceRegister(
  57. &serviceRef,
  58. kDNSServiceFlagsNoAutoRename, // we want a conflict error
  59. InterfaceIndexForName( "en0" ), // pass 0 for all interfaces
  60. "iPhone Doom Classic",
  61. serviceName,
  62. NULL, // domain
  63. NULL, // host
  64. htons( DOOM_PORT ),
  65. 0, // txtLen
  66. NULL, // txtRecord
  67. DNSServiceRegisterReplyCallback,
  68. NULL // context
  69. );
  70. if ( err != kDNSServiceErr_NoError ) {
  71. printf( "DNSServiceRegister error\n" );
  72. } else {
  73. // block until we get a response, process it, and run the callback
  74. err = DNSServiceProcessResult( serviceRef );
  75. if ( err != kDNSServiceErr_NoError ) {
  76. printf( "DNSServiceProcessResult error\n" );
  77. }
  78. }
  79. return localServer;
  80. }
  81. void TerminateGameService() {
  82. if ( localServer ) {
  83. localServer = false;
  84. }
  85. DNSServiceRefDeallocate( serviceRef );
  86. memset( serviceInterfaces, 0, sizeof( serviceInterfaces ) );
  87. }
  88. void DNSServiceQueryRecordReplyCallback (
  89. DNSServiceRef DNSServiceRef,
  90. DNSServiceFlags flags,
  91. uint32_t interfaceIndex,
  92. DNSServiceErrorType errorCode,
  93. const char *fullname,
  94. uint16_t rrtype,
  95. uint16_t rrclass,
  96. uint16_t rdlen,
  97. const void *rdata,
  98. uint32_t ttl,
  99. void *context ) {
  100. assert( rdlen == 4 );
  101. const byte *ip = (const byte *)rdata;
  102. char interfaceName[IF_NAMESIZE];
  103. if_indextoname( interfaceIndex, interfaceName );
  104. printf( "DNSServiceQueryRecordReplyCallback: %s, interface[%i] = %s, [%i] = %i.%i.%i.%i\n",
  105. fullname, interfaceIndex, interfaceName, rdlen, ip[0], ip[1], ip[2], ip[3] );
  106. ReportNetworkInterfaces();
  107. memset( &resolvedServerAddress, 0, sizeof( resolvedServerAddress ) );
  108. struct sockaddr_in *sin = (struct sockaddr_in *)&resolvedServerAddress;
  109. sin->sin_len = sizeof( resolvedServerAddress );
  110. sin->sin_family = AF_INET;
  111. sin->sin_port = htons( DOOM_PORT );
  112. memcpy( &sin->sin_addr, ip, 4 );
  113. gotServerAddress = true;
  114. }
  115. DNSServiceFlags callbackFlags;
  116. void DNSServiceResolveReplyCallback (
  117. DNSServiceRef sdRef,
  118. DNSServiceFlags flags,
  119. uint32_t interfaceIndex,
  120. DNSServiceErrorType errorCode,
  121. const char *fullname,
  122. const char *hosttarget,
  123. uint16_t port,
  124. uint16_t txtLen,
  125. const unsigned char *txtRecord,
  126. void *context ) {
  127. char interfaceName[IF_NAMESIZE];
  128. if_indextoname( interfaceIndex, interfaceName );
  129. printf( "Resolve: interfaceIndex [%i]=%s : %s @ %s\n", interfaceIndex, interfaceName, fullname, hosttarget );
  130. callbackFlags = flags;
  131. #if 0
  132. struct hostent * host = gethostbyname( hosttarget );
  133. if ( host ) {
  134. printf( "h_name: %s\n", host->h_name );
  135. if ( host->h_aliases ) { // this can be NULL
  136. for ( char **list = host->h_aliases ; *list ; list++ ) {
  137. printf( "h_alias: %s\n", *list );
  138. }
  139. }
  140. printf( "h_addrtype: %i\n", host->h_addrtype );
  141. printf( "h_length: %i\n", host->h_length );
  142. if ( !host->h_addr_list ) { // I doubt this would ever be NULL...
  143. return;
  144. }
  145. for ( char **list = host->h_addr_list ; *list ; list++ ) {
  146. printf( "addr: %i.%i.%i.%i\n", ((byte *)*list)[0], ((byte *)*list)[1], ((byte *)*list)[2], ((byte *)*list)[3] );
  147. }
  148. memset( &resolvedServerAddress, 0, sizeof( resolvedServerAddress ) );
  149. resolvedServerAddress.sin_len = sizeof( resolvedServerAddress );
  150. resolvedServerAddress.sin_family = host->h_addrtype;
  151. resolvedServerAddress.sin_port = htons( DOOM_PORT );
  152. assert( host->h_length == 4 );
  153. memcpy( &resolvedServerAddress.sin_addr, *host->h_addr_list, host->h_length );
  154. gotServerAddress = true;
  155. }
  156. #else
  157. DNSServiceRef queryRef;
  158. // look up the name for this host
  159. DNSServiceErrorType err = DNSServiceQueryRecord (
  160. &queryRef,
  161. kDNSServiceFlagsForceMulticast,
  162. interfaceIndex,
  163. hosttarget,
  164. kDNSServiceType_A, // we want the host address
  165. kDNSServiceClass_IN,
  166. DNSServiceQueryRecordReplyCallback,
  167. NULL /* may be NULL */
  168. );
  169. if ( err != kDNSServiceErr_NoError ) {
  170. printf( "DNSServiceQueryRecord error\n" );
  171. } else {
  172. // block until we get a response, process it, and run the callback
  173. err = DNSServiceProcessResult( queryRef );
  174. if ( err != kDNSServiceErr_NoError ) {
  175. printf( "DNSServiceProcessResult error\n" );
  176. }
  177. DNSServiceRefDeallocate( queryRef );
  178. }
  179. #endif
  180. }
  181. boolean NetworkServerAvailable() {
  182. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  183. if ( serviceInterfaces[i].interfaceIndex != 0 ) {
  184. return true;
  185. }
  186. }
  187. return false;
  188. }
  189. // returns "WiFi", "BlueTooth", or "" for display on the
  190. // main menu multiplayer icon
  191. const char *NetworkServerTransport() {
  192. int count = 0;
  193. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  194. if ( serviceInterfaces[i].interfaceIndex != 0 ) {
  195. count++;
  196. }
  197. }
  198. static char str[1024];
  199. str[0] = 0;
  200. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  201. int index = serviceInterfaces[i].interfaceIndex;
  202. if ( index == 0 ) {
  203. continue;
  204. }
  205. if ( str[0] ) {
  206. strcat( str, "+" );
  207. }
  208. if ( index == -1 ) {
  209. strcat( str, "BT-NEW" );
  210. } else if ( index == 1 ) {
  211. strcat( str, "LOOP" ); // we should never see this!
  212. } else if ( index == 2 ) {
  213. strcat( str, "WiFi" );
  214. } else {
  215. strcat( str, "BT-EST" );
  216. }
  217. }
  218. return str;
  219. }
  220. boolean ResolveNetworkServer( struct sockaddr *addr ) {
  221. if ( !NetworkServerAvailable() ) {
  222. return false;
  223. }
  224. gotServerAddress = false;
  225. DNSServiceRef resolveRef;
  226. // An unconnected bluetooth service will report an interfaceIndex of -1, so if
  227. // we have a wifi link with an interfaceIndex > 0, use that
  228. // explicitly.
  229. service_t *service = NULL;
  230. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  231. if ( serviceInterfaces[i].interfaceIndex > 0 ) {
  232. service = &serviceInterfaces[i];
  233. char interfaceName[IF_NAMESIZE];
  234. if_indextoname( service->interfaceIndex, interfaceName );
  235. printf( "explicitly resolving server on interface %i = %s\n", service->interfaceIndex, interfaceName );
  236. break;
  237. }
  238. }
  239. if ( !service ) {
  240. #if 0 // don't support bluetooth now
  241. // settle for the unconnected bluetooth service
  242. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  243. if ( serviceInterfaces[i].interfaceIndex != 0 ) {
  244. service = &serviceInterfaces[i];
  245. break;
  246. }
  247. }
  248. #endif
  249. if ( !service ) {
  250. printf( "No serviceInterface current.\n" );
  251. return false;
  252. }
  253. }
  254. // look up the name for this service
  255. DNSServiceErrorType err = DNSServiceResolve (
  256. &resolveRef,
  257. kDNSServiceFlagsForceMulticast, // always on local link
  258. service->interfaceIndex > 0 ? service->interfaceIndex : 0, // don't use -1 for bluetooth
  259. service->browseName,
  260. service->browseRegtype,
  261. service->browseDomain,
  262. DNSServiceResolveReplyCallback,
  263. NULL /* context */
  264. );
  265. if ( err != kDNSServiceErr_NoError ) {
  266. printf( "DNSServiceResolve error\n" );
  267. } else {
  268. // We can get two callbacks when both wifi and bluetooth are enabled
  269. callbackFlags = 0;
  270. do {
  271. err = DNSServiceProcessResult( resolveRef );
  272. if ( err != kDNSServiceErr_NoError ) {
  273. printf( "DNSServiceProcessResult error\n" );
  274. }
  275. } while ( callbackFlags & kDNSServiceFlagsMoreComing );
  276. DNSServiceRefDeallocate( resolveRef );
  277. }
  278. if ( gotServerAddress ) {
  279. *addr = resolvedServerAddress;
  280. return true;
  281. }
  282. return false;
  283. }
  284. void DNSServiceBrowseReplyCallback(
  285. DNSServiceRef sdRef,
  286. DNSServiceFlags flags,
  287. uint32_t interfaceIndex,
  288. DNSServiceErrorType errorCode,
  289. const char *serviceName,
  290. const char *regtype,
  291. const char *replyDomain,
  292. void *context ) {
  293. printf( "DNSServiceBrowseReplyCallback %s: interface:%i name:%s regtype:%s domain:%s\n",
  294. (flags & kDNSServiceFlagsAdd) ? "ADD" : "REMOVE",
  295. interfaceIndex, serviceName, regtype, replyDomain );
  296. if ( flags & kDNSServiceFlagsAdd ) {
  297. // add it to the list
  298. if ( interfaceIndex == 1 ) {
  299. printf( "Not adding service on loopback interface.\n" );
  300. } else {
  301. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  302. service_t *service = &serviceInterfaces[i];
  303. if ( service->interfaceIndex == 0 ) {
  304. strncpy( service->browseName, serviceName, sizeof( service->browseName ) -1 );
  305. strncpy( service->browseRegtype, regtype, sizeof( service->browseRegtype ) -1 );
  306. strncpy( service->browseDomain, replyDomain, sizeof( service->browseDomain ) -1 );
  307. service->interfaceIndex = interfaceIndex;
  308. break;
  309. }
  310. }
  311. }
  312. } else {
  313. // remove it from the list
  314. for ( int i = 0 ; i < MAX_SERVICE_INTEFACES ; i++ ) {
  315. if ( serviceInterfaces[i].interfaceIndex == interfaceIndex ) {
  316. serviceInterfaces[i].interfaceIndex = 0;
  317. }
  318. }
  319. }
  320. }
  321. void ProcessDNSMessages() {
  322. static boolean initialized;
  323. if ( !initialized ) {
  324. initialized = true;
  325. DNSServiceErrorType err = DNSServiceBrowse (
  326. &browseRef,
  327. 0, /* flags */
  328. 0, /* interface */
  329. serviceName,
  330. NULL, /* domain */
  331. DNSServiceBrowseReplyCallback,
  332. NULL /* context */
  333. );
  334. if ( err != kDNSServiceErr_NoError ) {
  335. printf( "DNSServiceBrowse error\n" );
  336. return;
  337. }
  338. }
  339. // poll the socket for updates
  340. int socket = DNSServiceRefSockFD( browseRef );
  341. if ( socket <= 0 ) {
  342. return;
  343. }
  344. fd_set set;
  345. FD_ZERO( &set );
  346. FD_SET( socket, &set );
  347. struct timeval tv;
  348. memset( &tv, 0, sizeof( tv ) );
  349. if ( select( socket+1, &set, NULL, NULL, &tv ) > 0 ) {
  350. DNSServiceProcessResult( browseRef );
  351. }
  352. }
  353. void ReportNetworkInterfaces() {
  354. struct ifaddrs *ifap;
  355. printf( "getifaddrs():\n" );
  356. if ( getifaddrs( &ifap ) == -1 ) {
  357. perror( "getifaddrs(): " );
  358. } else {
  359. for ( struct ifaddrs *ifa = ifap ; ifa ; ifa = ifa->ifa_next ) {
  360. struct sockaddr_in *ina = (struct sockaddr_in *)ifa->ifa_addr;
  361. if ( ina->sin_family == AF_INET ) {
  362. byte *ip = (byte *)&ina->sin_addr;
  363. printf( "ifa_name: %s ifa_flags: %i sa_family: %i=AF_INET ip: %i.%i.%i.%i\n", ifa->ifa_name, ifa->ifa_flags,
  364. ina->sin_family, ip[0], ip[1], ip[2], ip[3] );
  365. } else if ( ina->sin_family == AF_LINK ) {
  366. struct if_data *data = (struct if_data *)ifa->ifa_data;
  367. printf( "ifa_name: %s ifa_flags: %i sa_family: %i=AF_LINK ifi_ipackets: %i\n", ifa->ifa_name, ifa->ifa_flags,
  368. ina->sin_family, data->ifi_ipackets );
  369. } else {
  370. printf( "ifa_name: %s ifa_flags: %i sa_family: %i=???\n", ifa->ifa_name, ifa->ifa_flags,
  371. ina->sin_family );
  372. }
  373. }
  374. freeifaddrs( ifap );
  375. }
  376. printf( "if_nameindex():\n" );
  377. struct if_nameindex *ifnames = if_nameindex();
  378. if ( !ifnames ) {
  379. perror( "if_ameindex():" );
  380. } else {
  381. for ( int i = 0 ; ifnames[i].if_index != 0 ; i++ ) {
  382. printf( "%i : %s\n", ifnames[i].if_index, ifnames[i].if_name );
  383. }
  384. if_freenameindex( ifnames );
  385. }
  386. }
  387. boolean NetworkAvailable() {
  388. struct ifaddrs *ifap;
  389. if ( getifaddrs( &ifap ) == -1 ) {
  390. return false;
  391. }
  392. // We can't tell if bluetooth is available from here, because
  393. // the interface doesn't appear until after the service is found,
  394. // but I decided not to support bluetooth for now due to the poor performance.
  395. boolean goodInterface = false;
  396. for ( struct ifaddrs *ifa = ifap ; ifa ; ifa = ifa->ifa_next ) {
  397. struct sockaddr_in *ina = (struct sockaddr_in *)ifa->ifa_addr;
  398. if ( ina->sin_family == AF_INET ) {
  399. if ( !strcmp( ifa->ifa_name, "en0" ) ) {
  400. goodInterface = true;
  401. }
  402. }
  403. }
  404. freeifaddrs( ifap );
  405. return goodInterface;
  406. }
  407. int InterfaceIndexForAddress( struct sockaddr_in *adr ) {
  408. // FIXME: compare against getifaddrs
  409. return 0;
  410. }
  411. struct sockaddr_in AddressForInterfaceName( const char *ifname ) {
  412. struct sockaddr_in s;
  413. memset( &s, 0, sizeof( s ) );
  414. struct ifaddrs *ifap;
  415. if ( getifaddrs( &ifap ) == -1 ) {
  416. perror( "getifaddrs()" );
  417. return s;
  418. }
  419. struct ifaddrs *ifa;
  420. for ( ifa = ifap ; ifa ; ifa = ifa->ifa_next ) {
  421. struct sockaddr_in *ina = (struct sockaddr_in *)ifa->ifa_addr;
  422. if ( ina->sin_family == AF_INET && !strcmp( ifa->ifa_name, ifname ) ) {
  423. byte *ip = (byte *)&ina->sin_addr;
  424. printf( "AddressForInterfaceName( %s ) = ifa_name: %s ifa_flags: %i sa_family: %i=AF_INET ip: %i.%i.%i.%i\n",
  425. ifname, ifa->ifa_name, ifa->ifa_flags,
  426. ina->sin_family, ip[0], ip[1], ip[2], ip[3] );
  427. freeifaddrs( ifap );
  428. return *ina;
  429. }
  430. }
  431. freeifaddrs( ifap );
  432. printf( "AddressForInterfaceName( %s ): Couldn't find IP address\n", ifname );
  433. return s;
  434. }
  435. int InterfaceIndexForName( const char *ifname ) {
  436. struct if_nameindex *ifnames = if_nameindex();
  437. if ( !ifnames ) {
  438. perror( "if_nameindex()" );
  439. return 0;
  440. }
  441. for ( int i = 0 ; ifnames[i].if_index != 0 ; i++ ) {
  442. if ( !strcmp( ifname, ifnames[i].if_name ) ) {
  443. int index = ifnames[i].if_index;
  444. if_freenameindex( ifnames );
  445. return index;
  446. }
  447. }
  448. printf( "InterfaceIndexForName( %s ): Couldn't find interface\n", ifname );
  449. if_freenameindex( ifnames );
  450. return 0;
  451. }
  452. struct sockaddr_in AddressForInterfaceIndex( int interfaceIndex ) {
  453. struct sockaddr_in addr;
  454. memset( &addr, 0, sizeof( addr ) );
  455. addr.sin_len = sizeof( addr );
  456. addr.sin_family = AF_INET;
  457. addr.sin_addr.s_addr = INADDR_ANY;
  458. if ( interfaceIndex == 0 ) {
  459. return addr;
  460. }
  461. struct if_nameindex *ifnames = if_nameindex();
  462. if ( !ifnames ) {
  463. perror( "if_ameindex()" );
  464. return addr;
  465. }
  466. for ( int i = 0 ; ifnames[i].if_index != 0 ; i++ ) {
  467. if ( ifnames[i].if_index == interfaceIndex ) {
  468. addr = AddressForInterfaceName( ifnames[i].if_name );
  469. if_freenameindex( ifnames );
  470. return addr;
  471. }
  472. }
  473. printf( "AddressForInterfaceIndex( %i ): Couldn't find interface\n", interfaceIndex );
  474. if_freenameindex( ifnames );
  475. return addr;
  476. }
  477. struct sockaddr_in gameSocketAddress;
  478. int UDPSocket( const char *interfaceName, int portnum ) {
  479. int udpSocket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
  480. if ( udpSocket == -1 ) {
  481. Com_Printf( "UDP socket failed: %s\n", strerror( errno ) );
  482. return -1;
  483. }
  484. struct sockaddr_in addr = AddressForInterfaceName( interfaceName );
  485. addr.sin_port = htons( portnum );
  486. byte *ip = (byte *)&addr.sin_addr;
  487. gameSocketAddress = addr;
  488. Com_Printf( "UDPSocket( %s, %i ) = %i.%i.%i.%i\n", interfaceName, portnum,
  489. ip[0], ip[1], ip[2], ip[3] );
  490. if ( bind( udpSocket, (struct sockaddr *)&addr, sizeof( addr ) ) == -1 ) {
  491. Com_Printf( "UDP bind failed: %s\n", strerror( errno ) );
  492. close( udpSocket );
  493. return -1;
  494. }
  495. #if 0
  496. // enable broadcast
  497. int on = 1;
  498. if ( setsockopt( udpSocket, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) ) == -1 ) {
  499. Com_Printf( "UDP setsockopt failed: %s\n", strerror( errno ) );
  500. close( udpSocket );
  501. return -1;
  502. }
  503. #endif
  504. #if 0
  505. // set the type-of-service, in hopes that the link level drivers use it
  506. // to stop buffering huge amounts of data when there are line errors
  507. int tos = 0x10; /* IPTOS_LOWDELAY; */ /* see <netinet/in.h> */
  508. if ( setsockopt( udpSocket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos) ) == -1 ) {
  509. Com_Printf( "setsockopt IP_TOS failed: %s\n", strerror( errno ) );
  510. }
  511. #endif
  512. // enable non-blocking IO
  513. if ( fcntl( udpSocket, F_SETFL, O_NONBLOCK ) == -1 ) {
  514. Com_Printf( "UDP fcntl failed: %s\n", strerror( errno ) );
  515. close( udpSocket );
  516. return -1;
  517. }
  518. return udpSocket;
  519. }