*** empty log message ***
[platform/upstream/c-ares.git] / acountry.c
1 /*
2  * $Id$
3  *
4  * IP-address/hostname to country converter.
5  *
6  * Problem; you want to know where IP a.b.c.d is located.
7  *
8  * Use ares_gethostbyname ("d.c.b.a.zz.countries.nerd.dk")
9  * and get the CNAME (host->h_name). Result will be:
10  *   CNAME = zz<CC>.countries.nerd.dk with address 127.0.x.y (ver 1) or
11  *   CNAME = <a.b.c.d>.zz.countries.nerd.dk with address 127.0.x.y (ver 2)
12  *
13  * The 2 letter country code in <CC> and the ISO-3166 country
14  * number in x.y (number = x*256 + y). Version 2 of the protocol is missing
15  * the <CC> number.
16  *
17  * Ref: http://countries.nerd.dk/more.html
18  *
19  * Written by G. Vanem <gvanem@broadpark.no> 2006, 2007
20  *
21  * NB! This program may not be big-endian aware.
22  *
23  * Permission to use, copy, modify, and distribute this
24  * software and its documentation for any purpose and without
25  * fee is hereby granted, provided that the above copyright
26  * notice appear in all copies and that both that copyright
27  * notice and this permission notice appear in supporting
28  * documentation, and that the name of M.I.T. not be used in
29  * advertising or publicity pertaining to distribution of the
30  * software without specific, written prior permission.
31  * M.I.T. makes no representations about the suitability of
32  * this software for any purpose.  It is provided "as is"
33  * without express or implied warranty.
34  */
35
36 #include "setup.h"
37
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <stdarg.h>
41 #include <string.h>
42 #include <ctype.h>
43 #ifdef HAVE_UNISTD_H
44 #include <unistd.h>
45 #endif
46 #ifdef HAVE_STRINGS_H
47 #include <strings.h>
48 #endif
49
50 #if defined(WIN32) && !defined(WATT32)
51   #include <winsock.h>
52 #else
53   #include <arpa/inet.h>
54   #include <netinet/in.h>
55   #include <netdb.h>
56 #endif
57
58 #include "ares.h"
59 #include "ares_getopt.h"
60 #include "inet_net_pton.h"
61 #include "inet_ntop.h"
62
63 #ifndef INADDR_NONE
64 #define INADDR_NONE 0xffffffff
65 #endif
66
67 static const char *usage      = "acountry [-vh?] {host|addr} ...\n";
68 static const char  nerd_fmt[] = "%u.%u.%u.%u.zz.countries.nerd.dk";
69 static const char *nerd_ver1  = nerd_fmt + 14;
70 static const char *nerd_ver2  = nerd_fmt + 11;
71 static int         verbose    = 0;
72
73 #define TRACE(fmt) do {               \
74                      if (verbose > 0) \
75                        printf fmt ;   \
76                    } while (0)
77
78 static void wait_ares(ares_channel channel);
79 static void callback(void *arg, int status, int timeouts, struct hostent *host);
80 static void callback2(void *arg, int status, int timeouts, struct hostent *host);
81 static void find_country_from_cname(const char *cname, struct in_addr addr);
82
83 static void Abort(const char *fmt, ...)
84 {
85   va_list args;
86   va_start(args, fmt);
87   vfprintf(stderr, fmt, args);
88   va_end(args);
89   exit(1);
90 }
91
92 int main(int argc, char **argv)
93 {
94   ares_channel channel;
95   int    ch, status;
96
97 #if defined(WIN32) && !defined(WATT32)
98   WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
99   WSADATA wsaData;
100   WSAStartup(wVersionRequested, &wsaData);
101 #endif
102
103   while ((ch = ares_getopt(argc, argv, "dvh?")) != -1)
104     switch (ch)
105       {
106       case 'd':
107 #ifdef WATT32
108         dbug_init();
109 #endif
110         break;
111       case 'v':
112         verbose++;
113         break;
114       case 'h':
115       case '?':
116       default:
117         Abort(usage);
118       }
119
120   argc -= optind;
121   argv += optind;
122   if (argc < 1)
123      Abort(usage);
124
125   status = ares_init(&channel);
126   if (status != ARES_SUCCESS)
127     {
128       fprintf(stderr, "ares_init: %s\n", ares_strerror(status));
129       return 1;
130     }
131
132   /* Initiate the queries, one per command-line argument. */
133   for ( ; *argv; argv++)
134     {
135       struct in_addr addr;
136       char buf[100];
137
138       /* If this fails, assume '*argv' is a host-name that
139        * must be resolved first
140        */
141       if (ares_inet_pton(AF_INET, *argv, &addr) != 1)
142         {
143           ares_gethostbyname(channel, *argv, AF_INET, callback2, &addr);
144           wait_ares(channel);
145           if (addr.s_addr == INADDR_NONE)
146             {
147               printf("Failed to lookup %s\n", *argv);
148               continue;
149             }
150         }
151
152       sprintf(buf, nerd_fmt,
153               (unsigned int)(addr.s_addr >> 24),
154               (unsigned int)((addr.s_addr >> 16) & 255),
155               (unsigned int)((addr.s_addr >> 8) & 255),
156               (unsigned int)(addr.s_addr & 255));
157       TRACE(("Looking up %s...", buf));
158       fflush(stdout);
159       ares_gethostbyname(channel, buf, AF_INET, callback, buf);
160     }
161
162   wait_ares(channel);
163   ares_destroy(channel);
164
165 #if defined(WIN32) && !defined(WATT32)
166   WSACleanup();
167 #endif
168
169   return 0;
170 }
171
172 /*
173  * Wait for the queries to complete.
174  */
175 static void wait_ares(ares_channel channel)
176 {
177   while (1)
178     {
179       struct timeval *tvp, tv;
180       fd_set read_fds, write_fds;
181       int nfds;
182
183       FD_ZERO(&read_fds);
184       FD_ZERO(&write_fds);
185       nfds = ares_fds(channel, &read_fds, &write_fds);
186       if (nfds == 0)
187         break;
188       tvp = ares_timeout(channel, NULL, &tv);
189       select(nfds, &read_fds, &write_fds, NULL, tvp);
190       ares_process(channel, &read_fds, &write_fds);
191     }
192 }
193
194 /*
195  * This is the callback used when we have the IP-address of interest.
196  * Extract the CNAME and figure out the country-code from it.
197  */
198 static void callback(void *arg, int status, int timeouts, struct hostent *host)
199 {
200   const char *name = (const char*)arg;
201   const char *cname;
202   char buf[20];
203
204   (void)timeouts;
205
206   if (!host || status != ARES_SUCCESS)
207     {
208       printf("Failed to lookup %s: %s\n", name, ares_strerror(status));
209       return;
210     }
211
212   TRACE(("\nFound address %s, name %s\n",
213          ares_inet_ntop(AF_INET,(const char*)host->h_addr,buf,sizeof(buf)),
214          host->h_name));
215
216   cname = host->h_name;  /* CNAME gets put here */
217   if (!cname)
218     printf("Failed to get CNAME for %s\n", name);
219   else
220     find_country_from_cname(cname, *(struct in_addr*)host->h_addr);
221 }
222
223 /*
224  * This is the callback used to obtain the IP-address of the host of interest.
225  */
226 static void callback2(void *arg, int status, int timeouts, struct hostent *host)
227 {
228   struct in_addr *addr = (struct in_addr*) arg;
229
230   (void)timeouts;
231   if (!host || status != ARES_SUCCESS)
232     memset(addr, INADDR_NONE, sizeof(*addr));
233   else
234     memcpy(addr, host->h_addr, sizeof(*addr));
235 }
236
237 struct search_list {
238        int         country_number; /* ISO-3166 country number */
239        char        short_name[3];  /* A2 short country code */
240        const char *long_name;      /* normal country name */
241      };
242
243 static const struct search_list *list_lookup(int number, const struct search_list *list, int num)
244 {
245   while (num > 0 && list->long_name)
246     {
247       if (list->country_number == number)
248         return (list);
249       num--;
250       list++;
251     }
252   return (NULL);
253 }
254
255 /*
256  * Ref: ftp://ftp.ripe.net/iso3166-countrycodes.txt
257  */
258 static const struct search_list country_list[] = {
259        {   4, "af", "Afghanistan"                          },
260        { 248, "ax", "Ă…land Island"                         },
261        {   8, "al", "Albania"                              },
262        {  12, "dz", "Algeria"                              },
263        {  16, "as", "American Samoa"                       },
264        {  20, "ad", "Andorra"                              },
265        {  24, "ao", "Angola"                               },
266        { 660, "ai", "Anguilla"                             },
267        {  10, "aq", "Antarctica"                           },
268        {  28, "ag", "Antigua & Barbuda"                    },
269        {  32, "ar", "Argentina"                            },
270        {  51, "am", "Armenia"                              },
271        { 533, "aw", "Aruba"                                },
272        {  36, "au", "Australia"                            },
273        {  40, "at", "Austria"                              },
274        {  31, "az", "Azerbaijan"                           },
275        {  44, "bs", "Bahamas"                              },
276        {  48, "bh", "Bahrain"                              },
277        {  50, "bd", "Bangladesh"                           },
278        {  52, "bb", "Barbados"                             },
279        { 112, "by", "Belarus"                              },
280        {  56, "be", "Belgium"                              },
281        {  84, "bz", "Belize"                               },
282        { 204, "bj", "Benin"                                },
283        {  60, "bm", "Bermuda"                              },
284        {  64, "bt", "Bhutan"                               },
285        {  68, "bo", "Bolivia"                              },
286        {  70, "ba", "Bosnia & Herzegowina"                 },
287        {  72, "bw", "Botswana"                             },
288        {  74, "bv", "Bouvet Island"                        },
289        {  76, "br", "Brazil"                               },
290        {  86, "io", "British Indian Ocean Territory"       },
291        {  96, "bn", "Brunei Darussalam"                    },
292        { 100, "bg", "Bulgaria"                             },
293        { 854, "bf", "Burkina Faso"                         },
294        { 108, "bi", "Burundi"                              },
295        { 116, "kh", "Cambodia"                             },
296        { 120, "cm", "Cameroon"                             },
297        { 124, "ca", "Canada"                               },
298        { 132, "cv", "Cape Verde"                           },
299        { 136, "ky", "Cayman Islands"                       },
300        { 140, "cf", "Central African Republic"             },
301        { 148, "td", "Chad"                                 },
302        { 152, "cl", "Chile"                                },
303        { 156, "cn", "China"                                },
304        { 162, "cx", "Christmas Island"                     },
305        { 166, "cc", "Cocos Islands"                        },
306        { 170, "co", "Colombia"                             },
307        { 174, "km", "Comoros"                              },
308        { 178, "cg", "Congo"                                },
309        { 180, "cd", "Congo"                                },
310        { 184, "ck", "Cook Islands"                         },
311        { 188, "cr", "Costa Rica"                           },
312        { 384, "ci", "Cote d'Ivoire"                        },
313        { 191, "hr", "Croatia"                              },
314        { 192, "cu", "Cuba"                                 },
315        { 196, "cy", "Cyprus"                               },
316        { 203, "cz", "Czech Republic"                       },
317        { 208, "dk", "Denmark"                              },
318        { 262, "dj", "Djibouti"                             },
319        { 212, "dm", "Dominica"                             },
320        { 214, "do", "Dominican Republic"                   },
321        { 218, "ec", "Ecuador"                              },
322        { 818, "eg", "Egypt"                                },
323        { 222, "sv", "El Salvador"                          },
324        { 226, "gq", "Equatorial Guinea"                    },
325        { 232, "er", "Eritrea"                              },
326        { 233, "ee", "Estonia"                              },
327        { 231, "et", "Ethiopia"                             },
328        { 238, "fk", "Falkland Islands"                     },
329        { 234, "fo", "Faroe Islands"                        },
330        { 242, "fj", "Fiji"                                 },
331        { 246, "fi", "Finland"                              },
332        { 250, "fr", "France"                               },
333        { 249, "fx", "France, Metropolitan"                 },
334        { 254, "gf", "French Guiana"                        },
335        { 258, "pf", "French Polynesia"                     },
336        { 260, "tf", "French Southern Territories"          },
337        { 266, "ga", "Gabon"                                },
338        { 270, "gm", "Gambia"                               },
339        { 268, "ge", "Georgia"                              },
340        { 276, "de", "Germany"                              },
341        { 288, "gh", "Ghana"                                },
342        { 292, "gi", "Gibraltar"                            },
343        { 300, "gr", "Greece"                               },
344        { 304, "gl", "Greenland"                            },
345        { 308, "gd", "Grenada"                              },
346        { 312, "gp", "Guadeloupe"                           },
347        { 316, "gu", "Guam"                                 },
348        { 320, "gt", "Guatemala"                            },
349        { 324, "gn", "Guinea"                               },
350        { 624, "gw", "Guinea-Bissau"                        },
351        { 328, "gy", "Guyana"                               },
352        { 332, "ht", "Haiti"                                },
353        { 334, "hm", "Heard & Mc Donald Islands"            },
354        { 336, "va", "Vatican City"                         },
355        { 340, "hn", "Honduras"                             },
356        { 344, "hk", "Hong kong"                            },
357        { 348, "hu", "Hungary"                              },
358        { 352, "is", "Iceland"                              },
359        { 356, "in", "India"                                },
360        { 360, "id", "Indonesia"                            },
361        { 364, "ir", "Iran"                                 },
362        { 368, "iq", "Iraq"                                 },
363        { 372, "ie", "Ireland"                              },
364        { 376, "il", "Israel"                               },
365        { 380, "it", "Italy"                                },
366        { 388, "jm", "Jamaica"                              },
367        { 392, "jp", "Japan"                                },
368        { 400, "jo", "Jordan"                               },
369        { 398, "kz", "Kazakhstan"                           },
370        { 404, "ke", "Kenya"                                },
371        { 296, "ki", "Kiribati"                             },
372        { 408, "kp", "Korea (north)"                        },
373        { 410, "kr", "Korea (south)"                        },
374        { 414, "kw", "Kuwait"                               },
375        { 417, "kg", "Kyrgyzstan"                           },
376        { 418, "la", "Laos"                                 },
377        { 428, "lv", "Latvia"                               },
378        { 422, "lb", "Lebanon"                              },
379        { 426, "ls", "Lesotho"                              },
380        { 430, "lr", "Liberia"                              },
381        { 434, "ly", "Libya"                                },
382        { 438, "li", "Liechtenstein"                        },
383        { 440, "lt", "Lithuania"                            },
384        { 442, "lu", "Luxembourg"                           },
385        { 446, "mo", "Macao"                                },
386        { 807, "mk", "Macedonia"                            },
387        { 450, "mg", "Madagascar"                           },
388        { 454, "mw", "Malawi"                               },
389        { 458, "my", "Malaysia"                             },
390        { 462, "mv", "Maldives"                             },
391        { 466, "ml", "Mali"                                 },
392        { 470, "mt", "Malta"                                },
393        { 584, "mh", "Marshall Islands"                     },
394        { 474, "mq", "Martinique"                           },
395        { 478, "mr", "Mauritania"                           },
396        { 480, "mu", "Mauritius"                            },
397        { 175, "yt", "Mayotte"                              },
398        { 484, "mx", "Mexico"                               },
399        { 583, "fm", "Micronesia"                           },
400        { 498, "md", "Moldova"                              },
401        { 492, "mc", "Monaco"                               },
402        { 496, "mn", "Mongolia"                             },
403        { 500, "ms", "Montserrat"                           },
404        { 504, "ma", "Morocco"                              },
405        { 508, "mz", "Mozambique"                           },
406        { 104, "mm", "Myanmar"                              },
407        { 516, "na", "Namibia"                              },
408        { 520, "nr", "Nauru"                                },
409        { 524, "np", "Nepal"                                },
410        { 528, "nl", "Netherlands"                          },
411        { 530, "an", "Netherlands Antilles"                 },
412        { 540, "nc", "New Caledonia"                        },
413        { 554, "nz", "New Zealand"                          },
414        { 558, "ni", "Nicaragua"                            },
415        { 562, "ne", "Niger"                                },
416        { 566, "ng", "Nigeria"                              },
417        { 570, "nu", "Niue"                                 },
418        { 574, "nf", "Norfolk Island"                       },
419        { 580, "mp", "Northern Mariana Islands"             },
420        { 578, "no", "Norway"                               },
421        { 512, "om", "Oman"                                 },
422        { 586, "pk", "Pakistan"                             },
423        { 585, "pw", "Palau"                                },
424        { 275, "ps", "Palestinian Territory"                },
425        { 591, "pa", "Panama"                               },
426        { 598, "pg", "Papua New Guinea"                     },
427        { 600, "py", "Paraguay"                             },
428        { 604, "pe", "Peru"                                 },
429        { 608, "ph", "Philippines"                          },
430        { 612, "pn", "Pitcairn"                             },
431        { 616, "pl", "Poland"                               },
432        { 620, "pt", "Portugal"                             },
433        { 630, "pr", "Puerto Rico"                          },
434        { 634, "qa", "Qatar"                                },
435        { 638, "re", "Reunion"                              },
436        { 642, "ro", "Romania"                              },
437        { 643, "ru", "Russia"                               },
438        { 646, "rw", "Rwanda"                               },
439        { 659, "kn", "Saint Kitts & Nevis"                  },
440        { 662, "lc", "Saint Lucia"                          },
441        { 670, "vc", "Saint Vincent"                        },
442        { 882, "ws", "Samoa"                                },
443        { 674, "sm", "San Marino"                           },
444        { 678, "st", "Sao Tome & Principe"                  },
445        { 682, "sa", "Saudi Arabia"                         },
446        { 686, "sn", "Senegal"                              },
447        { 891, "cs", "Serbia and Montenegro"                },
448        { 690, "sc", "Seychelles"                           },
449        { 694, "sl", "Sierra Leone"                         },
450        { 702, "sg", "Singapore"                            },
451        { 703, "sk", "Slovakia"                             },
452        { 705, "si", "Slovenia"                             },
453        {  90, "sb", "Solomon Islands"                      },
454        { 706, "so", "Somalia"                              },
455        { 710, "za", "South Africa"                         },
456        { 239, "gs", "South Georgia"                        },
457        { 724, "es", "Spain"                                },
458        { 144, "lk", "Sri Lanka"                            },
459        { 654, "sh", "St. Helena"                           },
460        { 666, "pm", "St. Pierre & Miquelon"                },
461        { 736, "sd", "Sudan"                                },
462        { 740, "sr", "Suriname"                             },
463        { 744, "sj", "Svalbard & Jan Mayen Islands"         },
464        { 748, "sz", "Swaziland"                            },
465        { 752, "se", "Sweden"                               },
466        { 756, "ch", "Switzerland"                          },
467        { 760, "sy", "Syrian Arab Republic"                 },
468        { 626, "tl", "Timor-Leste"                          },
469        { 158, "tw", "Taiwan"                               },
470        { 762, "tj", "Tajikistan"                           },
471        { 834, "tz", "Tanzania"                             },
472        { 764, "th", "Thailand"                             },
473        { 768, "tg", "Togo"                                 },
474        { 772, "tk", "Tokelau"                              },
475        { 776, "to", "Tonga"                                },
476        { 780, "tt", "Trinidad & Tobago"                    },
477        { 788, "tn", "Tunisia"                              },
478        { 792, "tr", "Turkey"                               },
479        { 795, "tm", "Turkmenistan"                         },
480        { 796, "tc", "Turks & Caicos Islands"               },
481        { 798, "tv", "Tuvalu"                               },
482        { 800, "ug", "Uganda"                               },
483        { 804, "ua", "Ukraine"                              },
484        { 784, "ae", "United Arab Emirates"                 },
485        { 826, "gb", "United Kingdom"                       },
486        { 840, "us", "United States"                        },
487        { 581, "um", "United States Minor Outlying Islands" },
488        { 858, "uy", "Uruguay"                              },
489        { 860, "uz", "Uzbekistan"                           },
490        { 548, "vu", "Vanuatu"                              },
491        { 862, "ve", "Venezuela"                            },
492        { 704, "vn", "Vietnam"                              },
493        {  92, "vg", "Virgin Islands (British)"             },
494        { 850, "vi", "Virgin Islands (US)"                  },
495        { 876, "wf", "Wallis & Futuna Islands"              },
496        { 732, "eh", "Western Sahara"                       },
497        { 887, "ye", "Yemen"                                },
498        { 894, "zm", "Zambia"                               },
499        { 716, "zw", "Zimbabwe"                             }
500      };
501
502 /*
503  * Check if start of 'str' is simply an IPv4 address.
504  */
505 #define BYTE_OK(x) ((x) >= 0 && (x) <= 255)
506
507 static int is_addr(char *str, char **end)
508 {
509   int a0, a1, a2, a3, num, rc = 0, length = 0;
510
511   if ((num = sscanf(str,"%3d.%3d.%3d.%3d%n",&a0,&a1,&a2,&a3,&length)) == 4 &&
512       BYTE_OK(a0) && BYTE_OK(a1) && BYTE_OK(a2) && BYTE_OK(a3) &&
513       length >= (3+4))
514     {
515       rc = 1;
516       *end = str + length;
517     }
518   return rc;
519 }
520
521 /*
522  * Find the country-code and name from the CNAME. E.g.:
523  *   version 1: CNAME = zzno.countries.nerd.dk with address 127.0.2.66
524  *              yields ccode_A" = "no" and cnumber 578 (2.66).
525  *   version 2: CNAME = <a.b.c.d>.zz.countries.nerd.dk with address 127.0.2.66
526  *              yields cnumber 578 (2.66). ccode_A is "";
527  */
528 static void find_country_from_cname(const char *cname, struct in_addr addr)
529 {
530   const struct search_list *country;
531   char  ccode_A2[3], *ccopy, *dot_4;
532   int   cnumber, z0, z1, ver_1, ver_2;
533   u_long ip;
534
535   ip = ntohl(addr.s_addr);
536   z0 = tolower(cname[0]);
537   z1 = tolower(cname[1]);
538   ccopy = strdup(cname);
539
540   ver_1 = (z0 == 'z' && z1 == 'z' && !strcasecmp(cname+4,nerd_ver1));
541   ver_2 = (is_addr(ccopy,&dot_4) && !strcasecmp(dot_4,nerd_ver2));
542
543   if (ver_1)
544     {
545       const char *dot = strchr(cname, '.');
546       if ((z0 != 'z' && z1 != 'z') || dot != cname+4)
547         {
548           printf("Unexpected CNAME %s (ver_1)\n", cname);
549           return;
550         }
551     }
552   else if (ver_2)
553     {
554       z0 = tolower(dot_4[1]);
555       z1 = tolower(dot_4[2]);
556       if (z0 != 'z' && z1 != 'z')
557         {
558           printf("Unexpected CNAME %s (ver_2)\n", cname);
559           return;
560         }
561     }
562   else
563     {
564       printf("Unexpected CNAME %s (ver?)\n", cname);
565       return;
566     }
567
568   if (ver_1)
569     {
570       ccode_A2[0] = tolower(cname[2]);
571       ccode_A2[1] = tolower(cname[3]);
572       ccode_A2[2] = '\0';
573     }
574   else
575     ccode_A2[0] = '\0';
576
577   cnumber = ip & 0xFFFF;
578
579   TRACE(("Found country-code `%s', number %d\n",
580          ver_1 ? ccode_A2 : "<n/a>", cnumber));
581
582   country = list_lookup(cnumber, country_list,
583                         sizeof(country_list) / sizeof(country_list[0]));
584   if (!country)
585     printf("Name for country-number %d not found.\n", cnumber);
586   else
587     {
588       if (ver_1 && *(unsigned short*)&country->short_name != *(unsigned*)&ccode_A2)
589         printf("short-name mismatch; %s vs %s\n", country->short_name, ccode_A2);
590
591       printf("%s (%s), number %d.\n",
592              country->long_name, country->short_name, cnumber);
593     }
594   free(ccopy);
595 }
596