In preparation for the upcomming IPv6 nameservers patch, the internal
[platform/upstream/c-ares.git] / ares_init.c
1 /* $Id$ */
2
3 /* Copyright 1998 by the Massachusetts Institute of Technology.
4  * Copyright (C) 2007-2008 by Daniel Stenberg
5  *
6  * Permission to use, copy, modify, and distribute this
7  * software and its documentation for any purpose and without
8  * fee is hereby granted, provided that the above copyright
9  * notice appear in all copies and that both that copyright
10  * notice and this permission notice appear in supporting
11  * documentation, and that the name of M.I.T. not be used in
12  * advertising or publicity pertaining to distribution of the
13  * software without specific, written prior permission.
14  * M.I.T. makes no representations about the suitability of
15  * this software for any purpose.  It is provided "as is"
16  * without express or implied warranty.
17  */
18
19 #include "setup.h"
20
21 #if defined(WIN32) && !defined(WATT32)
22 #include <iphlpapi.h>
23 #include <malloc.h>
24 #endif
25
26 #ifdef HAVE_SYS_PARAM_H
27 #include <sys/param.h>
28 #endif
29
30 #ifdef HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37
38 #ifdef HAVE_NETINET_IN_H
39 #include <netinet/in.h>
40 #endif
41
42 #ifdef HAVE_NETDB_H
43 #include <netdb.h>
44 #endif
45
46 #ifdef HAVE_ARPA_INET_H
47 #include <arpa/inet.h>
48 #endif
49
50 #ifdef HAVE_ARPA_NAMESER_H
51 #  include <arpa/nameser.h>
52 #else
53 #  include "nameser.h"
54 #endif
55 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
56 #  include <arpa/nameser_compat.h>
57 #endif
58
59 #ifdef HAVE_UNISTD_H
60 #include <unistd.h>
61 #endif
62
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <ctype.h>
67 #include <time.h>
68 #include <errno.h>
69 #include "ares.h"
70 #include "inet_net_pton.h"
71 #include "ares_private.h"
72
73 #ifdef WATT32
74 #undef WIN32  /* Redefined in MingW/MSVC headers */
75 #endif
76
77 static int init_by_options(ares_channel channel, const struct ares_options *options,
78                            int optmask);
79 static int init_by_environment(ares_channel channel);
80 static int init_by_resolv_conf(ares_channel channel);
81 static int init_by_defaults(ares_channel channel);
82
83 static int config_nameserver(struct server_state **servers, int *nservers,
84                              char *str);
85 static int set_search(ares_channel channel, const char *str);
86 static int set_options(ares_channel channel, const char *str);
87 static const char *try_option(const char *p, const char *q, const char *opt);
88 static int init_id_key(rc4_key* key,int key_data_len);
89
90 #ifndef WIN32
91 static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
92 static int ip_addr(const char *s, int len, struct in_addr *addr);
93 static void natural_mask(struct apattern *pat);
94 static int config_domain(ares_channel channel, char *str);
95 static int config_lookup(ares_channel channel, const char *str,
96                          const char *bindch, const char *filech);
97 static int config_sortlist(struct apattern **sortlist, int *nsort,
98                            const char *str);
99 static char *try_config(char *s, const char *opt);
100 #endif
101
102 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
103                              x->nservers > -1 && \
104                              x->ndomains > -1 && \
105                              x->ndots > -1 && x->timeout > -1 && \
106                              x->tries > -1)
107
108 int ares_init(ares_channel *channelptr)
109 {
110   return ares_init_options(channelptr, NULL, 0);
111 }
112
113 int ares_init_options(ares_channel *channelptr, struct ares_options *options,
114                       int optmask)
115 {
116   ares_channel channel;
117   int i;
118   int status = ARES_SUCCESS;
119   struct server_state *server;
120   struct timeval now;
121
122 #ifdef CURLDEBUG
123   const char *env = getenv("CARES_MEMDEBUG");
124
125   if (env)
126     curl_memdebug(env);
127   env = getenv("CARES_MEMLIMIT");
128   if (env)
129     curl_memlimit(atoi(env));
130 #endif
131
132   channel = malloc(sizeof(struct ares_channeldata));
133   if (!channel) {
134     *channelptr = NULL;
135     return ARES_ENOMEM;
136   }
137
138   now = ares__tvnow();
139
140   /* Set everything to distinguished values so we know they haven't
141    * been set yet.
142    */
143   channel->flags = -1;
144   channel->timeout = -1;
145   channel->tries = -1;
146   channel->ndots = -1;
147   channel->rotate = -1;
148   channel->udp_port = -1;
149   channel->tcp_port = -1;
150   channel->socket_send_buffer_size = -1;
151   channel->socket_receive_buffer_size = -1;
152   channel->nservers = -1;
153   channel->ndomains = -1;
154   channel->nsort = -1;
155   channel->tcp_connection_generation = 0;
156   channel->lookups = NULL;
157   channel->domains = NULL;
158   channel->sortlist = NULL;
159   channel->servers = NULL;
160   channel->sock_state_cb = NULL;
161   channel->sock_state_cb_data = NULL;
162
163   channel->last_server = 0;
164   channel->last_timeout_processed = (time_t)now.tv_sec;
165
166   /* Initialize our lists of queries */
167   ares__init_list_head(&(channel->all_queries));
168   for (i = 0; i < ARES_QID_TABLE_SIZE; i++)
169     {
170       ares__init_list_head(&(channel->queries_by_qid[i]));
171     }
172   for (i = 0; i < ARES_TIMEOUT_TABLE_SIZE; i++)
173     {
174       ares__init_list_head(&(channel->queries_by_timeout[i]));
175     }
176
177   /* Initialize configuration by each of the four sources, from highest
178    * precedence to lowest.
179    */
180
181   if (status == ARES_SUCCESS) {
182   status = init_by_options(channel, options, optmask);
183     if (status != ARES_SUCCESS)
184       DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
185                      ares_strerror(status)));
186   }
187   if (status == ARES_SUCCESS) {
188     status = init_by_environment(channel);
189     if (status != ARES_SUCCESS)
190       DEBUGF(fprintf(stderr, "Error: init_by_environment failed: %s\n",
191                      ares_strerror(status)));
192   }
193   if (status == ARES_SUCCESS) {
194     status = init_by_resolv_conf(channel);
195     if (status != ARES_SUCCESS)
196       DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
197                      ares_strerror(status)));
198   }
199   if (status == ARES_SUCCESS) {
200     status = init_by_defaults(channel);
201     if (status != ARES_SUCCESS)
202       DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
203                      ares_strerror(status)));
204   }
205
206   /* Generate random key */
207
208   if (status == ARES_SUCCESS) {
209     status = init_id_key(&channel->id_key, ARES_ID_KEY_LEN);
210     if (status == ARES_SUCCESS)
211       channel->next_id = ares__generate_new_id(&channel->id_key);
212     else
213       DEBUGF(fprintf(stderr, "Error: init_id_key failed: %s\n",
214                      ares_strerror(status)));
215   }
216
217   if (status != ARES_SUCCESS)
218     {
219       /* Something failed; clean up memory we may have allocated. */
220       if (channel->servers)
221         free(channel->servers);
222       if (channel->domains)
223         {
224           for (i = 0; i < channel->ndomains; i++)
225             free(channel->domains[i]);
226           free(channel->domains);
227         }
228       if (channel->sortlist)
229         free(channel->sortlist);
230       if(channel->lookups)
231         free(channel->lookups);
232       free(channel);
233       return status;
234     }
235
236   /* Trim to one server if ARES_FLAG_PRIMARY is set. */
237   if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
238     channel->nservers = 1;
239
240   /* Initialize server states. */
241   for (i = 0; i < channel->nservers; i++)
242     {
243       server = &channel->servers[i];
244       server->udp_socket = ARES_SOCKET_BAD;
245       server->tcp_socket = ARES_SOCKET_BAD;
246       server->tcp_connection_generation = ++channel->tcp_connection_generation;
247       server->tcp_lenbuf_pos = 0;
248       server->tcp_buffer = NULL;
249       server->qhead = NULL;
250       server->qtail = NULL;
251       ares__init_list_head(&(server->queries_to_server));
252       server->channel = channel;
253       server->is_broken = 0;
254     }
255
256   *channelptr = channel;
257   return ARES_SUCCESS;
258 }
259
260 /* Save options from initialized channel */
261 int ares_save_options(ares_channel channel, struct ares_options *options,
262                       int *optmask)
263 {
264   int i;
265
266   /* Zero everything out */
267   memset(options, 0, sizeof(struct ares_options));
268
269   if (!ARES_CONFIG_CHECK(channel))
270     return ARES_ENODATA;
271
272   (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
273                 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
274                 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
275                 ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
276
277   /* Copy easy stuff */
278   options->flags   = channel->flags;
279
280   /* We return full millisecond resolution but that's only because we don't
281      set the ARES_OPT_TIMEOUT anymore, only the new ARES_OPT_TIMEOUTMS */
282   options->timeout = channel->timeout;
283   options->tries   = channel->tries;
284   options->ndots   = channel->ndots;
285   options->udp_port = (unsigned short)channel->udp_port;
286   options->tcp_port = (unsigned short)channel->tcp_port;
287   options->sock_state_cb     = channel->sock_state_cb;
288   options->sock_state_cb_data = channel->sock_state_cb_data;
289
290   /* Copy servers */
291   if (channel->nservers) {
292     options->servers =
293       malloc(channel->nservers * sizeof(struct server_state));
294     if (!options->servers && channel->nservers != 0)
295       return ARES_ENOMEM;
296     for (i = 0; i < channel->nservers; i++)
297       options->servers[i] = channel->servers[i].addr;
298   }
299   options->nservers = channel->nservers;
300
301   /* copy domains */
302   if (channel->ndomains) {
303     options->domains = malloc(channel->ndomains * sizeof(char *));
304     if (!options->domains)
305       return ARES_ENOMEM;
306
307     for (i = 0; i < channel->ndomains; i++)
308     {
309       options->ndomains = i;
310       options->domains[i] = strdup(channel->domains[i]);
311       if (!options->domains[i])
312         return ARES_ENOMEM;
313     }
314   }
315   options->ndomains = channel->ndomains;
316
317   /* copy lookups */
318   if (channel->lookups) {
319     options->lookups = strdup(channel->lookups);
320     if (!options->lookups && channel->lookups)
321       return ARES_ENOMEM;
322   }
323
324   /* copy sortlist */
325   if (channel->nsort) {
326     options->sortlist = malloc(channel->nsort * sizeof(struct apattern));
327     if (!options->sortlist)
328       return ARES_ENOMEM;
329     for (i = 0; i < channel->nsort; i++)
330     {
331       memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
332              sizeof(struct apattern));
333     }
334   }
335   options->nsort = channel->nsort;
336
337   return ARES_SUCCESS;
338 }
339
340 static int init_by_options(ares_channel channel,
341                            const struct ares_options *options,
342                            int optmask)
343 {
344   int i;
345
346   /* Easy stuff. */
347   if ((optmask & ARES_OPT_FLAGS) && channel->flags == -1)
348     channel->flags = options->flags;
349   if ((optmask & ARES_OPT_TIMEOUTMS) && channel->timeout == -1)
350     channel->timeout = options->timeout;
351   else if ((optmask & ARES_OPT_TIMEOUT) && channel->timeout == -1)
352     channel->timeout = options->timeout * 1000;
353   if ((optmask & ARES_OPT_TRIES) && channel->tries == -1)
354     channel->tries = options->tries;
355   if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
356     channel->ndots = options->ndots;
357   if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
358     channel->rotate = options->rotate;
359   if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
360     channel->udp_port = options->udp_port;
361   if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
362     channel->tcp_port = options->tcp_port;
363   if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
364     {
365       channel->sock_state_cb = options->sock_state_cb;
366       channel->sock_state_cb_data = options->sock_state_cb_data;
367     }
368   if ((optmask & ARES_OPT_SOCK_SNDBUF)
369       && channel->socket_send_buffer_size == -1)
370     channel->socket_send_buffer_size = options->socket_send_buffer_size;
371   if ((optmask & ARES_OPT_SOCK_RCVBUF)
372       && channel->socket_receive_buffer_size == -1)
373     channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
374
375   /* Copy the servers, if given. */
376   if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
377     {
378       /* Avoid zero size allocations at any cost */
379       if (options->nservers > 0)
380         {
381           channel->servers =
382             malloc(options->nservers * sizeof(struct server_state));
383           if (!channel->servers)
384             return ARES_ENOMEM;
385           for (i = 0; i < options->nservers; i++)
386             channel->servers[i].addr = options->servers[i];
387         }
388       channel->nservers = options->nservers;
389     }
390
391   /* Copy the domains, if given.  Keep channel->ndomains consistent so
392    * we can clean up in case of error.
393    */
394   if ((optmask & ARES_OPT_DOMAINS) && channel->ndomains == -1)
395     {
396       /* Avoid zero size allocations at any cost */
397       if (options->ndomains > 0)
398       {
399         channel->domains = malloc(options->ndomains * sizeof(char *));
400         if (!channel->domains)
401           return ARES_ENOMEM;
402         for (i = 0; i < options->ndomains; i++)
403           {
404             channel->ndomains = i;
405             channel->domains[i] = strdup(options->domains[i]);
406             if (!channel->domains[i])
407               return ARES_ENOMEM;
408           }
409       }
410       channel->ndomains = options->ndomains;
411     }
412
413   /* Set lookups, if given. */
414   if ((optmask & ARES_OPT_LOOKUPS) && !channel->lookups)
415     {
416       channel->lookups = strdup(options->lookups);
417       if (!channel->lookups)
418         return ARES_ENOMEM;
419     }
420
421   /* copy sortlist */
422   if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
423     {
424       channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
425       if (!channel->sortlist)
426         return ARES_ENOMEM;
427       for (i = 0; i < options->nsort; i++)
428         {
429           memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
430         }
431       channel->nsort = options->nsort;
432     }
433
434   return ARES_SUCCESS;
435 }
436
437 static int init_by_environment(ares_channel channel)
438 {
439   const char *localdomain, *res_options;
440   int status;
441
442   localdomain = getenv("LOCALDOMAIN");
443   if (localdomain && channel->ndomains == -1)
444     {
445       status = set_search(channel, localdomain);
446       if (status != ARES_SUCCESS)
447         return status;
448     }
449
450   res_options = getenv("RES_OPTIONS");
451   if (res_options)
452     {
453       status = set_options(channel, res_options);
454       if (status != ARES_SUCCESS)
455         return status;
456     }
457
458   return ARES_SUCCESS;
459 }
460
461 #ifdef WIN32
462 /*
463  * Warning: returns a dynamically allocated buffer, the user MUST
464  * use free() if the function returns 1
465  */
466 static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
467 {
468   /* Test for the size we need */
469   DWORD size = 0;
470   int result;
471
472   result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
473   if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
474     return 0;
475   *obuf = malloc(size+1);
476   if (!*obuf)
477     return 0;
478
479   if (RegQueryValueEx(hKey, subkey, 0, NULL,
480                       (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
481   {
482     free(*obuf);
483     return 0;
484   }
485   if (size == 1)
486   {
487     free(*obuf);
488     return 0;
489   }
490   return 1;
491 }
492
493 static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
494 {
495   char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
496   DWORD enum_size = 39;
497   int idx = 0;
498   HKEY hVal;
499
500   while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
501                       NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
502   {
503     int rc;
504
505     enum_size = 39;
506     if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
507         ERROR_SUCCESS)
508       continue;
509     rc = get_res_nt(hVal, subkey, obuf);
510       RegCloseKey(hVal);
511     if (rc)
512       return 1;
513     }
514   return 0;
515 }
516
517 static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
518 {
519   FIXED_INFO    *fi   = alloca (sizeof(*fi));
520   DWORD          size = sizeof (*fi);
521   typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
522   get_net_param_func fpGetNetworkParams;  /* available only on Win-98/2000+ */
523   HMODULE        handle;
524   IP_ADDR_STRING *ipAddr;
525   int            i, count = 0;
526   int            debug  = 0;
527   size_t         ip_size = sizeof("255.255.255.255,")-1;
528   size_t         left = ret_size;
529   char          *ret = ret_buf;
530   HRESULT        res;
531
532   if (!fi)
533      return (0);
534
535   handle = LoadLibrary ("iphlpapi.dll");
536   if (!handle)
537      return (0);
538
539   fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
540   if (!fpGetNetworkParams)
541      goto quit;
542
543   res = (*fpGetNetworkParams) (fi, &size);
544   if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
545      goto quit;
546
547   fi = alloca (size);
548   if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
549      goto quit;
550
551   if (debug)
552   {
553     printf ("Host Name: %s\n", fi->HostName);
554     printf ("Domain Name: %s\n", fi->DomainName);
555     printf ("DNS Servers:\n"
556             "    %s (primary)\n", fi->DnsServerList.IpAddress.String);
557   }
558   if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
559       inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
560       left > ip_size)
561   {
562     ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
563     left -= ret - ret_buf;
564     count++;
565   }
566
567   for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
568        ipAddr = ipAddr->Next, i++)
569   {
570     if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
571     {
572        ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
573        left -= ret - ret_buf;
574        count++;
575     }
576     if (debug)
577        printf ("    %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
578   }
579
580 quit:
581   if (handle)
582      FreeLibrary (handle);
583
584   if (debug && left <= ip_size)
585      printf ("Too many nameservers. Truncating to %d addressess", count);
586   if (ret > ret_buf)
587      ret[-1] = '\0';
588   return (count);
589 }
590 #endif
591
592 static int init_by_resolv_conf(ares_channel channel)
593 {
594   char *line = NULL;
595   int status = -1, nservers = 0, nsort = 0;
596   struct server_state *servers = NULL;
597   struct apattern *sortlist = NULL;
598
599 #ifdef WIN32
600
601     /*
602   NameServer info via IPHLPAPI (IP helper API):
603     GetNetworkParams() should be the trusted source for this.
604     Available in Win-98/2000 and later. If that fail, fall-back to
605     registry information.
606
607   NameServer Registry:
608
609    On Windows 9X, the DNS server can be found in:
610 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
611
612         On Windows NT/2000/XP/2003:
613 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
614         or
615 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
616         or
617 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
618 NameServer
619         or
620 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
621 DhcpNameServer
622    */
623
624   HKEY mykey;
625   HKEY subkey;
626   DWORD data_type;
627   DWORD bytes;
628   DWORD result;
629   char  buf[256];
630
631   if (channel->nservers > -1)  /* don't override ARES_OPT_SERVER */
632      return ARES_SUCCESS;
633
634   if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
635   {
636     status = config_nameserver(&servers, &nservers, buf);
637     if (status == ARES_SUCCESS)
638       goto okay;
639   }
640
641   if (IS_NT())
642   {
643     if (RegOpenKeyEx(
644           HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
645           KEY_READ, &mykey
646           ) == ERROR_SUCCESS)
647     {
648       RegOpenKeyEx(mykey, "Interfaces", 0,
649                    KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
650       if (get_res_nt(mykey, NAMESERVER, &line))
651       {
652         status = config_nameserver(&servers, &nservers, line);
653         free(line);
654       }
655       else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
656       {
657         status = config_nameserver(&servers, &nservers, line);
658         free(line);
659       }
660       /* Try the interfaces */
661       else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
662       {
663         status = config_nameserver(&servers, &nservers, line);
664         free(line);
665       }
666       else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
667       {
668         status = config_nameserver(&servers, &nservers, line);
669         free(line);
670       }
671       RegCloseKey(subkey);
672       RegCloseKey(mykey);
673     }
674   }
675   else
676   {
677     if (RegOpenKeyEx(
678           HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
679           KEY_READ, &mykey
680           ) == ERROR_SUCCESS)
681     {
682       if ((result = RegQueryValueEx(
683              mykey, NAMESERVER, NULL, &data_type,
684              NULL, &bytes
685              )
686             ) == ERROR_SUCCESS ||
687           result == ERROR_MORE_DATA)
688       {
689         if (bytes)
690         {
691           line = malloc(bytes+1);
692           if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
693                               (unsigned char *)line, &bytes) ==
694               ERROR_SUCCESS)
695           {
696             status = config_nameserver(&servers, &nservers, line);
697           }
698           free(line);
699         }
700       }
701     }
702     RegCloseKey(mykey);
703   }
704
705   if (status == ARES_SUCCESS)
706     status = ARES_EOF;
707   else
708     /* Catch the case when all the above checks fail (which happens when there
709        is no network card or the cable is unplugged) */
710     status = ARES_EFILE;
711
712 #elif defined(__riscos__)
713
714   /* Under RISC OS, name servers are listed in the
715      system variable Inet$Resolvers, space separated. */
716
717   line = getenv("Inet$Resolvers");
718   status = ARES_EOF;
719   if (line) {
720     char *resolvers = strdup(line), *pos, *space;
721
722     if (!resolvers)
723       return ARES_ENOMEM;
724
725     pos = resolvers;
726     do {
727       space = strchr(pos, ' ');
728       if (space)
729         *space = '\0';
730       status = config_nameserver(&servers, &nservers, pos);
731       if (status != ARES_SUCCESS)
732         break;
733       pos = space + 1;
734     } while (space);
735
736     if (status == ARES_SUCCESS)
737       status = ARES_EOF;
738
739     free(resolvers);
740   }
741
742 #elif defined(WATT32)
743   int i;
744
745   sock_init();
746   for (i = 0; def_nameservers[i]; i++)
747       ;
748   if (i == 0)
749     return ARES_SUCCESS; /* use localhost DNS server */
750
751   nservers = i;
752   servers = calloc(sizeof(*servers), i);
753   if (!servers)
754      return ARES_ENOMEM;
755
756   for (i = 0; def_nameservers[i]; i++)
757       servers[i].addr.s_addr = htonl(def_nameservers[i]);
758   status = ARES_EOF;
759
760 #else
761   {
762     char *p;
763     FILE *fp;
764     int linesize;
765     int error;
766
767     /* Don't read resolv.conf and friends if we don't have to */
768     if (ARES_CONFIG_CHECK(channel))
769         return ARES_SUCCESS;
770
771     fp = fopen(PATH_RESOLV_CONF, "r");
772     if (fp) {
773       while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
774       {
775         if ((p = try_config(line, "domain")) && channel->ndomains == -1)
776           status = config_domain(channel, p);
777         else if ((p = try_config(line, "lookup")) && !channel->lookups)
778           status = config_lookup(channel, p, "bind", "file");
779         else if ((p = try_config(line, "search")) && channel->ndomains == -1)
780           status = set_search(channel, p);
781         else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
782           status = config_nameserver(&servers, &nservers, p);
783         else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
784           status = config_sortlist(&sortlist, &nsort, p);
785         else if ((p = try_config(line, "options")))
786           status = set_options(channel, p);
787         else
788           status = ARES_SUCCESS;
789         if (status != ARES_SUCCESS)
790           break;
791       }
792       fclose(fp);
793     }
794     else {
795       error = ERRNO;
796       switch(error) {
797       case ENOENT:
798       case ESRCH:
799         status = ARES_EOF;
800         break;
801       default:
802         DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
803                        error, strerror(error)));
804         DEBUGF(fprintf(stderr, "Error opening file: %s\n", PATH_RESOLV_CONF));
805         status = ARES_EFILE;
806       }
807     }
808
809     if ((status == ARES_EOF) && (!channel->lookups)) {
810       /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
811       fp = fopen("/etc/nsswitch.conf", "r");
812       if (fp) {
813         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
814         {
815           if ((p = try_config(line, "hosts:")) && !channel->lookups)
816             status = config_lookup(channel, p, "dns", "files");
817         }
818         fclose(fp);
819       }
820       else {
821         error = ERRNO;
822         switch(error) {
823         case ENOENT:
824         case ESRCH:
825           status = ARES_EOF;
826           break;
827         default:
828           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
829                          error, strerror(error)));
830           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
831           status = ARES_EFILE;
832         }
833       }
834     }
835
836     if ((status == ARES_EOF) && (!channel->lookups)) {
837       /* Linux / GNU libc 2.x and possibly others have host.conf */
838       fp = fopen("/etc/host.conf", "r");
839       if (fp) {
840         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
841         {
842           if ((p = try_config(line, "order")) && !channel->lookups)
843             status = config_lookup(channel, p, "bind", "hosts");
844         }
845         fclose(fp);
846       }
847       else {
848         error = ERRNO;
849         switch(error) {
850         case ENOENT:
851         case ESRCH:
852           status = ARES_EOF;
853           break;
854         default:
855           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
856                          error, strerror(error)));
857           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
858           status = ARES_EFILE;
859         }
860       }
861     }
862
863     if ((status == ARES_EOF) && (!channel->lookups)) {
864       /* Tru64 uses /etc/svc.conf */
865       fp = fopen("/etc/svc.conf", "r");
866       if (fp) {
867         while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
868         {
869           if ((p = try_config(line, "hosts=")) && !channel->lookups)
870             status = config_lookup(channel, p, "bind", "local");
871         }
872         fclose(fp);
873       }
874       else {
875         error = ERRNO;
876         switch(error) {
877         case ENOENT:
878         case ESRCH:
879           status = ARES_EOF;
880           break;
881         default:
882           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
883                          error, strerror(error)));
884           DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/svc.conf"));
885           status = ARES_EFILE;
886         }
887       }
888     }
889
890     if(line)
891       free(line);
892   }
893
894 #endif
895
896   /* Handle errors. */
897   if (status != ARES_EOF)
898     {
899       if (servers != NULL)
900         free(servers);
901       if (sortlist != NULL)
902         free(sortlist);
903       return status;
904     }
905
906   /* If we got any name server entries, fill them in. */
907 #ifdef WIN32
908 okay:
909 #endif
910   if (servers)
911     {
912       channel->servers = servers;
913       channel->nservers = nservers;
914     }
915
916   /* If we got any sortlist entries, fill them in. */
917   if (sortlist)
918     {
919       channel->sortlist = sortlist;
920       channel->nsort = nsort;
921     }
922
923   return ARES_SUCCESS;
924 }
925
926 static int init_by_defaults(ares_channel channel)
927 {
928   char *hostname = NULL;
929   int rc = ARES_SUCCESS;
930
931   if (channel->flags == -1)
932     channel->flags = 0;
933   if (channel->timeout == -1)
934     channel->timeout = DEFAULT_TIMEOUT;
935   if (channel->tries == -1)
936     channel->tries = DEFAULT_TRIES;
937   if (channel->ndots == -1)
938     channel->ndots = 1;
939   if (channel->rotate == -1)
940     channel->rotate = 0;
941   if (channel->udp_port == -1)
942     channel->udp_port = htons(NAMESERVER_PORT);
943   if (channel->tcp_port == -1)
944     channel->tcp_port = htons(NAMESERVER_PORT);
945
946   if (channel->nservers == -1) {
947     /* If nobody specified servers, try a local named. */
948     channel->servers = malloc(sizeof(struct server_state));
949     if (!channel->servers) {
950       rc = ARES_ENOMEM;
951       goto error;
952     }
953     channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
954     channel->nservers = 1;
955   }
956
957 #ifdef ENAMETOOLONG
958 #define toolong(x) (x == -1) && ((ENAMETOOLONG == errno) || (EINVAL == errno))
959 #else
960 #define toolong(x) (x == -1) && (EINVAL == errno)
961 #endif
962
963   if (channel->ndomains == -1) {
964     /* Derive a default domain search list from the kernel hostname,
965      * or set it to empty if the hostname isn't helpful.
966      */
967     size_t len = 64;
968     int res;
969
970     hostname = malloc(len);
971     if(!hostname) {
972       rc = ARES_ENOMEM;
973       goto error;
974     }
975
976     do {
977       res = gethostname(hostname, len);
978
979       if(toolong(res)) {
980         char *p;
981         len *= 2;
982         p = realloc(hostname, len);
983         if(!p) {
984           rc = ARES_ENOMEM;
985           goto error;
986         }
987         hostname = p;
988         continue;
989       }
990       else if(res) {
991         rc = ARES_EBADNAME;
992         goto error;
993       }
994
995     } while(0);
996
997     channel->ndomains = 0; /* default to none */
998     if (strchr(hostname, '.'))  {
999       /* a dot was found */
1000
1001       channel->domains = malloc(sizeof(char *));
1002       if (!channel->domains) {
1003         rc = ARES_ENOMEM;
1004         goto error;
1005       }
1006       channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1007       if (!channel->domains[0]) {
1008         rc = ARES_ENOMEM;
1009         goto error;
1010       }
1011       channel->ndomains = 1;
1012     }
1013   }
1014
1015   if (channel->nsort == -1) {
1016     channel->sortlist = NULL;
1017     channel->nsort = 0;
1018   }
1019
1020   if (!channel->lookups) {
1021     channel->lookups = strdup("fb");
1022     if (!channel->lookups)
1023       rc = ARES_ENOMEM;
1024   }
1025
1026   error:
1027   if(rc) {
1028     if(channel->servers)
1029       free(channel->servers);
1030
1031     if(channel->domains && channel->domains[0])
1032       free(channel->domains[0]);
1033     if(channel->domains)
1034       free(channel->domains);
1035     if(channel->lookups)
1036       free(channel->lookups);
1037   }
1038
1039   if(hostname)
1040     free(hostname);
1041
1042   return rc;
1043 }
1044
1045 #ifndef WIN32
1046 static int config_domain(ares_channel channel, char *str)
1047 {
1048   char *q;
1049
1050   /* Set a single search domain. */
1051   q = str;
1052   while (*q && !ISSPACE(*q))
1053     q++;
1054   *q = '\0';
1055   return set_search(channel, str);
1056 }
1057
1058 static int config_lookup(ares_channel channel, const char *str,
1059                          const char *bindch, const char *filech)
1060 {
1061   char lookups[3], *l;
1062   const char *p;
1063
1064   /* Set the lookup order.  Only the first letter of each work
1065    * is relevant, and it has to be "b" for DNS or "f" for the
1066    * host file.  Ignore everything else.
1067    */
1068   l = lookups;
1069   p = str;
1070   while (*p)
1071     {
1072       if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1073         if (*p == *bindch) *l++ = 'b';
1074         else *l++ = 'f';
1075       }
1076       while (*p && !ISSPACE(*p) && (*p != ','))
1077         p++;
1078       while (*p && (ISSPACE(*p) || (*p == ',')))
1079         p++;
1080     }
1081   *l = '\0';
1082   channel->lookups = strdup(lookups);
1083   return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1084 }
1085
1086 #endif
1087
1088 static int config_nameserver(struct server_state **servers, int *nservers,
1089                              char *str)
1090 {
1091   struct in_addr addr;
1092   struct server_state *newserv;
1093   /* On Windows, there may be more than one nameserver specified in the same
1094    * registry key, so we parse it as a space or comma seperated list.
1095    */
1096 #ifdef WIN32
1097   char *p = str;
1098   char *begin = str;
1099   int more = 1;
1100   while (more)
1101   {
1102     more = 0;
1103     while (*p && !ISSPACE(*p) && *p != ',')
1104       p++;
1105
1106     if (*p)
1107     {
1108       *p = '\0';
1109       more = 1;
1110     }
1111
1112     /* Skip multiple spaces or trailing spaces */
1113     if (!*begin)
1114     {
1115       begin = ++p;
1116       continue;
1117     }
1118
1119     /* This is the part that actually sets the nameserver */
1120     addr.s_addr = inet_addr(begin);
1121     if (addr.s_addr == INADDR_NONE)
1122       continue;
1123     newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1124     if (!newserv)
1125       return ARES_ENOMEM;
1126     newserv[*nservers].addr = addr;
1127     *servers = newserv;
1128     (*nservers)++;
1129
1130     if (!more)
1131       break;
1132     begin = ++p;
1133   }
1134 #else
1135   /* Add a nameserver entry, if this is a valid address. */
1136   addr.s_addr = inet_addr(str);
1137   if (addr.s_addr == INADDR_NONE)
1138     return ARES_SUCCESS;
1139   newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1140   if (!newserv)
1141     return ARES_ENOMEM;
1142   newserv[*nservers].addr = addr;
1143   *servers = newserv;
1144   (*nservers)++;
1145 #endif
1146   return ARES_SUCCESS;
1147 }
1148
1149 #ifndef WIN32
1150 static int config_sortlist(struct apattern **sortlist, int *nsort,
1151                            const char *str)
1152 {
1153   struct apattern pat;
1154   const char *q;
1155
1156   /* Add sortlist entries. */
1157   while (*str && *str != ';')
1158     {
1159       int bits;
1160       char ipbuf[16], ipbufpfx[32];
1161       /* Find just the IP */
1162       q = str;
1163       while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1164         q++;
1165       memcpy(ipbuf, str, (int)(q-str));
1166       ipbuf[(int)(q-str)] = '\0';
1167       /* Find the prefix */
1168       if (*q == '/')
1169         {
1170           const char *str2 = q+1;
1171           while (*q && *q != ';' && !ISSPACE(*q))
1172             q++;
1173           memcpy(ipbufpfx, str, (int)(q-str));
1174           ipbufpfx[(int)(q-str)] = '\0';
1175           str = str2;
1176         }
1177       else
1178         ipbufpfx[0] = '\0';
1179       /* Lets see if it is CIDR */
1180       /* First we'll try IPv6 */
1181       if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1182                                      &pat.addrV6,
1183                                      sizeof(pat.addrV6))) > 0)
1184         {
1185           pat.type = PATTERN_CIDR;
1186           pat.mask.bits = (unsigned short)bits;
1187           pat.family = AF_INET6;
1188           if (!sortlist_alloc(sortlist, nsort, &pat))
1189             return ARES_ENOMEM;
1190         }
1191       if (ipbufpfx[0] &&
1192           (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1193                                      sizeof(pat.addrV4))) > 0)
1194         {
1195           pat.type = PATTERN_CIDR;
1196           pat.mask.bits = (unsigned short)bits;
1197           pat.family = AF_INET;
1198           if (!sortlist_alloc(sortlist, nsort, &pat))
1199             return ARES_ENOMEM;
1200         }
1201       /* See if it is just a regular IP */
1202       else if (ip_addr(ipbuf, (int)(q-str), &pat.addrV4) == 0)
1203         {
1204           if (ipbufpfx[0])
1205             {
1206               memcpy(ipbuf, str, (int)(q-str));
1207               ipbuf[(int)(q-str)] = '\0';
1208               if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr4) != 0)
1209                 natural_mask(&pat);
1210             }
1211           else
1212             natural_mask(&pat);
1213           pat.family = AF_INET;
1214           pat.type = PATTERN_MASK;
1215           if (!sortlist_alloc(sortlist, nsort, &pat))
1216             return ARES_ENOMEM;
1217         }
1218       else
1219         {
1220           while (*q && *q != ';' && !ISSPACE(*q))
1221             q++;
1222         }
1223       str = q;
1224       while (ISSPACE(*str))
1225         str++;
1226     }
1227
1228   return ARES_SUCCESS;
1229 }
1230 #endif
1231
1232 static int set_search(ares_channel channel, const char *str)
1233 {
1234   int n;
1235   const char *p, *q;
1236
1237   if(channel->ndomains != -1) {
1238     /* if we already have some domains present, free them first */
1239     for(n=0; n < channel->ndomains; n++)
1240       free(channel->domains[n]);
1241     free(channel->domains);
1242     channel->domains = NULL;
1243     channel->ndomains = -1;
1244   }
1245
1246   /* Count the domains given. */
1247   n = 0;
1248   p = str;
1249   while (*p)
1250     {
1251       while (*p && !ISSPACE(*p))
1252         p++;
1253       while (ISSPACE(*p))
1254         p++;
1255       n++;
1256     }
1257
1258   if (!n)
1259     {
1260       channel->ndomains = 0;
1261       return ARES_SUCCESS;
1262     }
1263
1264   channel->domains = malloc(n * sizeof(char *));
1265   if (!channel->domains)
1266     return ARES_ENOMEM;
1267
1268   /* Now copy the domains. */
1269   n = 0;
1270   p = str;
1271   while (*p)
1272     {
1273       channel->ndomains = n;
1274       q = p;
1275       while (*q && !ISSPACE(*q))
1276         q++;
1277       channel->domains[n] = malloc(q - p + 1);
1278       if (!channel->domains[n])
1279         return ARES_ENOMEM;
1280       memcpy(channel->domains[n], p, q - p);
1281       channel->domains[n][q - p] = 0;
1282       p = q;
1283       while (ISSPACE(*p))
1284         p++;
1285       n++;
1286     }
1287   channel->ndomains = n;
1288
1289   return ARES_SUCCESS;
1290 }
1291
1292 static int set_options(ares_channel channel, const char *str)
1293 {
1294   const char *p, *q, *val;
1295
1296   p = str;
1297   while (*p)
1298     {
1299       q = p;
1300       while (*q && !ISSPACE(*q))
1301         q++;
1302       val = try_option(p, q, "ndots:");
1303       if (val && channel->ndots == -1)
1304         channel->ndots = atoi(val);
1305       val = try_option(p, q, "retrans:");
1306       if (val && channel->timeout == -1)
1307         channel->timeout = atoi(val);
1308       val = try_option(p, q, "retry:");
1309       if (val && channel->tries == -1)
1310         channel->tries = atoi(val);
1311       val = try_option(p, q, "rotate");
1312       if (val && channel->rotate == -1)
1313         channel->rotate = 1;
1314       p = q;
1315       while (ISSPACE(*p))
1316         p++;
1317     }
1318
1319   return ARES_SUCCESS;
1320 }
1321
1322 #ifndef WIN32
1323 static char *try_config(char *s, const char *opt)
1324 {
1325   size_t len;
1326   ssize_t i;
1327   ssize_t j;
1328   char *p;
1329
1330   if (!s || !opt)
1331     /* no line or no option */
1332     return NULL;
1333
1334   /* trim line comment */
1335   for (i = 0; s[i] && s[i] != '#'; ++i);
1336   s[i] = '\0';
1337
1338   /* trim trailing whitespace */
1339   for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1340   s[++j] = '\0';
1341
1342   /* skip leading whitespace */
1343   for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1344   p = &s[i];
1345
1346   if (!*p)
1347     /* empty line */
1348     return NULL;
1349
1350   if ((len = strlen(opt)) == 0)
1351     /* empty option */
1352     return NULL;
1353
1354   if (strncmp(p, opt, len) != 0)
1355     /* line and option do not match */
1356     return NULL;
1357
1358   /* skip over given option name */
1359   p += len;
1360
1361   if (!*p)
1362     /* no option value */
1363     return NULL;
1364
1365   if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1366     /* whitespace between option name and value is mandatory
1367        for given option names which do not end with ':' or '=' */
1368     return NULL;
1369
1370   /* skip over whitespace */
1371   while (*p && ISSPACE(*p))
1372     p++;
1373
1374   if (!*p)
1375     /* no option value */
1376     return NULL;
1377
1378   /* return pointer to option value */
1379   return p;
1380 }
1381 #endif
1382
1383 static const char *try_option(const char *p, const char *q, const char *opt)
1384 {
1385   size_t len = strlen(opt);
1386   return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1387 }
1388
1389 #ifndef WIN32
1390 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1391                           struct apattern *pat)
1392 {
1393   struct apattern *newsort;
1394   newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1395   if (!newsort)
1396     return 0;
1397   newsort[*nsort] = *pat;
1398   *sortlist = newsort;
1399   (*nsort)++;
1400   return 1;
1401 }
1402
1403 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1404 {
1405
1406   /* Four octets and three periods yields at most 15 characters. */
1407   if (len > 15)
1408     return -1;
1409
1410   addr->s_addr = inet_addr(ipbuf);
1411   if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1412     return -1;
1413   return 0;
1414 }
1415
1416 static void natural_mask(struct apattern *pat)
1417 {
1418   struct in_addr addr;
1419
1420   /* Store a host-byte-order copy of pat in a struct in_addr.  Icky,
1421    * but portable.
1422    */
1423   addr.s_addr = ntohl(pat->addrV4.s_addr);
1424
1425   /* This is out of date in the CIDR world, but some people might
1426    * still rely on it.
1427    */
1428   if (IN_CLASSA(addr.s_addr))
1429     pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1430   else if (IN_CLASSB(addr.s_addr))
1431     pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1432   else
1433     pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1434 }
1435 #endif
1436 /* initialize an rc4 key. If possible a cryptographically secure random key
1437    is generated using a suitable function (for example win32's RtlGenRandom as
1438    described in
1439    http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1440    otherwise the code defaults to cross-platform albeit less secure mechanism
1441    using rand
1442 */
1443 static void randomize_key(unsigned char* key,int key_data_len)
1444 {
1445   int randomized = 0;
1446   int counter=0;
1447 #ifdef WIN32
1448   HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1449   if (lib) {
1450     BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1451       (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1452     if (pfn && pfn(key,key_data_len) )
1453       randomized = 1;
1454
1455     FreeLibrary(lib);
1456   }
1457 #else /* !WIN32 */
1458 #ifdef RANDOM_FILE
1459   FILE *f = fopen(RANDOM_FILE, "rb");
1460   if(f) {
1461     counter = fread(key, 1, key_data_len, f);
1462     fclose(f);
1463   }
1464 #endif
1465 #endif /* WIN32 */
1466
1467   if ( !randomized ) {
1468     for (;counter<key_data_len;counter++)
1469       key[counter]=(unsigned char)(rand() % 256);
1470   }
1471 }
1472
1473 static int init_id_key(rc4_key* key,int key_data_len)
1474 {
1475   unsigned char index1;
1476   unsigned char index2;
1477   unsigned char* state;
1478   short counter;
1479   unsigned char *key_data_ptr = 0;
1480
1481   key_data_ptr = calloc(1,key_data_len);
1482   if (!key_data_ptr)
1483     return ARES_ENOMEM;
1484
1485   state = &key->state[0];
1486   for(counter = 0; counter < 256; counter++)
1487     /* unnecessary AND but it keeps some compilers happier */
1488     state[counter] = (unsigned char)(counter & 0xff);
1489   randomize_key(key->state,key_data_len);
1490   key->x = 0;
1491   key->y = 0;
1492   index1 = 0;
1493   index2 = 0;
1494   for(counter = 0; counter < 256; counter++)
1495   {
1496     index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1497                               index2) % 256);
1498     ARES_SWAP_BYTE(&state[counter], &state[index2]);
1499
1500     index1 = (unsigned char)((index1 + 1) % key_data_len);
1501   }
1502   free(key_data_ptr);
1503   return ARES_SUCCESS;
1504 }
1505
1506 unsigned short ares__generate_new_id(rc4_key* key)
1507 {
1508   unsigned short r=0;
1509   ares__rc4(key, (unsigned char *)&r, sizeof(r));
1510   return r;
1511 }