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