Make use of gethostname() conditional on it being available
[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     channel->ndomains = 0; /* default to none */
970
971 #ifdef HAVE_GETHOSTNAME
972     hostname = malloc(len);
973     if(!hostname) {
974       rc = ARES_ENOMEM;
975       goto error;
976     }
977
978     do {
979       res = gethostname(hostname, len);
980
981       if(toolong(res)) {
982         char *p;
983         len *= 2;
984         p = realloc(hostname, len);
985         if(!p) {
986           rc = ARES_ENOMEM;
987           goto error;
988         }
989         hostname = p;
990         continue;
991       }
992       else if(res) {
993         rc = ARES_EBADNAME;
994         goto error;
995       }
996
997     } while(0);
998
999     if (strchr(hostname, '.'))  {
1000       /* a dot was found */
1001
1002       channel->domains = malloc(sizeof(char *));
1003       if (!channel->domains) {
1004         rc = ARES_ENOMEM;
1005         goto error;
1006       }
1007       channel->domains[0] = strdup(strchr(hostname, '.') + 1);
1008       if (!channel->domains[0]) {
1009         rc = ARES_ENOMEM;
1010         goto error;
1011       }
1012       channel->ndomains = 1;
1013     }
1014 #endif
1015   }
1016
1017   if (channel->nsort == -1) {
1018     channel->sortlist = NULL;
1019     channel->nsort = 0;
1020   }
1021
1022   if (!channel->lookups) {
1023     channel->lookups = strdup("fb");
1024     if (!channel->lookups)
1025       rc = ARES_ENOMEM;
1026   }
1027
1028   error:
1029   if(rc) {
1030     if(channel->servers)
1031       free(channel->servers);
1032
1033     if(channel->domains && channel->domains[0])
1034       free(channel->domains[0]);
1035     if(channel->domains)
1036       free(channel->domains);
1037     if(channel->lookups)
1038       free(channel->lookups);
1039   }
1040
1041   if(hostname)
1042     free(hostname);
1043
1044   return rc;
1045 }
1046
1047 #ifndef WIN32
1048 static int config_domain(ares_channel channel, char *str)
1049 {
1050   char *q;
1051
1052   /* Set a single search domain. */
1053   q = str;
1054   while (*q && !ISSPACE(*q))
1055     q++;
1056   *q = '\0';
1057   return set_search(channel, str);
1058 }
1059
1060 static int config_lookup(ares_channel channel, const char *str,
1061                          const char *bindch, const char *filech)
1062 {
1063   char lookups[3], *l;
1064   const char *p;
1065
1066   /* Set the lookup order.  Only the first letter of each work
1067    * is relevant, and it has to be "b" for DNS or "f" for the
1068    * host file.  Ignore everything else.
1069    */
1070   l = lookups;
1071   p = str;
1072   while (*p)
1073     {
1074       if ((*p == *bindch || *p == *filech) && l < lookups + 2) {
1075         if (*p == *bindch) *l++ = 'b';
1076         else *l++ = 'f';
1077       }
1078       while (*p && !ISSPACE(*p) && (*p != ','))
1079         p++;
1080       while (*p && (ISSPACE(*p) || (*p == ',')))
1081         p++;
1082     }
1083   *l = '\0';
1084   channel->lookups = strdup(lookups);
1085   return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
1086 }
1087
1088 #endif
1089
1090 static int config_nameserver(struct server_state **servers, int *nservers,
1091                              char *str)
1092 {
1093   struct in_addr addr;
1094   struct server_state *newserv;
1095   /* On Windows, there may be more than one nameserver specified in the same
1096    * registry key, so we parse it as a space or comma seperated list.
1097    */
1098 #ifdef WIN32
1099   char *p = str;
1100   char *begin = str;
1101   int more = 1;
1102   while (more)
1103   {
1104     more = 0;
1105     while (*p && !ISSPACE(*p) && *p != ',')
1106       p++;
1107
1108     if (*p)
1109     {
1110       *p = '\0';
1111       more = 1;
1112     }
1113
1114     /* Skip multiple spaces or trailing spaces */
1115     if (!*begin)
1116     {
1117       begin = ++p;
1118       continue;
1119     }
1120
1121     /* This is the part that actually sets the nameserver */
1122     addr.s_addr = inet_addr(begin);
1123     if (addr.s_addr == INADDR_NONE)
1124       continue;
1125     newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1126     if (!newserv)
1127       return ARES_ENOMEM;
1128     newserv[*nservers].addr = addr;
1129     *servers = newserv;
1130     (*nservers)++;
1131
1132     if (!more)
1133       break;
1134     begin = ++p;
1135   }
1136 #else
1137   /* Add a nameserver entry, if this is a valid address. */
1138   addr.s_addr = inet_addr(str);
1139   if (addr.s_addr == INADDR_NONE)
1140     return ARES_SUCCESS;
1141   newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
1142   if (!newserv)
1143     return ARES_ENOMEM;
1144   newserv[*nservers].addr = addr;
1145   *servers = newserv;
1146   (*nservers)++;
1147 #endif
1148   return ARES_SUCCESS;
1149 }
1150
1151 #ifndef WIN32
1152 static int config_sortlist(struct apattern **sortlist, int *nsort,
1153                            const char *str)
1154 {
1155   struct apattern pat;
1156   const char *q;
1157
1158   /* Add sortlist entries. */
1159   while (*str && *str != ';')
1160     {
1161       int bits;
1162       char ipbuf[16], ipbufpfx[32];
1163       /* Find just the IP */
1164       q = str;
1165       while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
1166         q++;
1167       memcpy(ipbuf, str, (int)(q-str));
1168       ipbuf[(int)(q-str)] = '\0';
1169       /* Find the prefix */
1170       if (*q == '/')
1171         {
1172           const char *str2 = q+1;
1173           while (*q && *q != ';' && !ISSPACE(*q))
1174             q++;
1175           memcpy(ipbufpfx, str, (int)(q-str));
1176           ipbufpfx[(int)(q-str)] = '\0';
1177           str = str2;
1178         }
1179       else
1180         ipbufpfx[0] = '\0';
1181       /* Lets see if it is CIDR */
1182       /* First we'll try IPv6 */
1183       if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
1184                                      &pat.addrV6,
1185                                      sizeof(pat.addrV6))) > 0)
1186         {
1187           pat.type = PATTERN_CIDR;
1188           pat.mask.bits = (unsigned short)bits;
1189           pat.family = AF_INET6;
1190           if (!sortlist_alloc(sortlist, nsort, &pat))
1191             return ARES_ENOMEM;
1192         }
1193       if (ipbufpfx[0] &&
1194           (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
1195                                      sizeof(pat.addrV4))) > 0)
1196         {
1197           pat.type = PATTERN_CIDR;
1198           pat.mask.bits = (unsigned short)bits;
1199           pat.family = AF_INET;
1200           if (!sortlist_alloc(sortlist, nsort, &pat))
1201             return ARES_ENOMEM;
1202         }
1203       /* See if it is just a regular IP */
1204       else if (ip_addr(ipbuf, (int)(q-str), &pat.addrV4) == 0)
1205         {
1206           if (ipbufpfx[0])
1207             {
1208               memcpy(ipbuf, str, (int)(q-str));
1209               ipbuf[(int)(q-str)] = '\0';
1210               if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr4) != 0)
1211                 natural_mask(&pat);
1212             }
1213           else
1214             natural_mask(&pat);
1215           pat.family = AF_INET;
1216           pat.type = PATTERN_MASK;
1217           if (!sortlist_alloc(sortlist, nsort, &pat))
1218             return ARES_ENOMEM;
1219         }
1220       else
1221         {
1222           while (*q && *q != ';' && !ISSPACE(*q))
1223             q++;
1224         }
1225       str = q;
1226       while (ISSPACE(*str))
1227         str++;
1228     }
1229
1230   return ARES_SUCCESS;
1231 }
1232 #endif
1233
1234 static int set_search(ares_channel channel, const char *str)
1235 {
1236   int n;
1237   const char *p, *q;
1238
1239   if(channel->ndomains != -1) {
1240     /* if we already have some domains present, free them first */
1241     for(n=0; n < channel->ndomains; n++)
1242       free(channel->domains[n]);
1243     free(channel->domains);
1244     channel->domains = NULL;
1245     channel->ndomains = -1;
1246   }
1247
1248   /* Count the domains given. */
1249   n = 0;
1250   p = str;
1251   while (*p)
1252     {
1253       while (*p && !ISSPACE(*p))
1254         p++;
1255       while (ISSPACE(*p))
1256         p++;
1257       n++;
1258     }
1259
1260   if (!n)
1261     {
1262       channel->ndomains = 0;
1263       return ARES_SUCCESS;
1264     }
1265
1266   channel->domains = malloc(n * sizeof(char *));
1267   if (!channel->domains)
1268     return ARES_ENOMEM;
1269
1270   /* Now copy the domains. */
1271   n = 0;
1272   p = str;
1273   while (*p)
1274     {
1275       channel->ndomains = n;
1276       q = p;
1277       while (*q && !ISSPACE(*q))
1278         q++;
1279       channel->domains[n] = malloc(q - p + 1);
1280       if (!channel->domains[n])
1281         return ARES_ENOMEM;
1282       memcpy(channel->domains[n], p, q - p);
1283       channel->domains[n][q - p] = 0;
1284       p = q;
1285       while (ISSPACE(*p))
1286         p++;
1287       n++;
1288     }
1289   channel->ndomains = n;
1290
1291   return ARES_SUCCESS;
1292 }
1293
1294 static int set_options(ares_channel channel, const char *str)
1295 {
1296   const char *p, *q, *val;
1297
1298   p = str;
1299   while (*p)
1300     {
1301       q = p;
1302       while (*q && !ISSPACE(*q))
1303         q++;
1304       val = try_option(p, q, "ndots:");
1305       if (val && channel->ndots == -1)
1306         channel->ndots = atoi(val);
1307       val = try_option(p, q, "retrans:");
1308       if (val && channel->timeout == -1)
1309         channel->timeout = atoi(val);
1310       val = try_option(p, q, "retry:");
1311       if (val && channel->tries == -1)
1312         channel->tries = atoi(val);
1313       val = try_option(p, q, "rotate");
1314       if (val && channel->rotate == -1)
1315         channel->rotate = 1;
1316       p = q;
1317       while (ISSPACE(*p))
1318         p++;
1319     }
1320
1321   return ARES_SUCCESS;
1322 }
1323
1324 #ifndef WIN32
1325 static char *try_config(char *s, const char *opt)
1326 {
1327   size_t len;
1328   ssize_t i;
1329   ssize_t j;
1330   char *p;
1331
1332   if (!s || !opt)
1333     /* no line or no option */
1334     return NULL;
1335
1336   /* trim line comment */
1337   for (i = 0; s[i] && s[i] != '#'; ++i);
1338   s[i] = '\0';
1339
1340   /* trim trailing whitespace */
1341   for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
1342   s[++j] = '\0';
1343
1344   /* skip leading whitespace */
1345   for (i = 0; s[i] && ISSPACE(s[i]); ++i);
1346   p = &s[i];
1347
1348   if (!*p)
1349     /* empty line */
1350     return NULL;
1351
1352   if ((len = strlen(opt)) == 0)
1353     /* empty option */
1354     return NULL;
1355
1356   if (strncmp(p, opt, len) != 0)
1357     /* line and option do not match */
1358     return NULL;
1359
1360   /* skip over given option name */
1361   p += len;
1362
1363   if (!*p)
1364     /* no option value */
1365     return NULL;
1366
1367   if ((opt[len-1] != ':') && (opt[len-1] != '=') && !ISSPACE(*p))
1368     /* whitespace between option name and value is mandatory
1369        for given option names which do not end with ':' or '=' */
1370     return NULL;
1371
1372   /* skip over whitespace */
1373   while (*p && ISSPACE(*p))
1374     p++;
1375
1376   if (!*p)
1377     /* no option value */
1378     return NULL;
1379
1380   /* return pointer to option value */
1381   return p;
1382 }
1383 #endif
1384
1385 static const char *try_option(const char *p, const char *q, const char *opt)
1386 {
1387   size_t len = strlen(opt);
1388   return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
1389 }
1390
1391 #ifndef WIN32
1392 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
1393                           struct apattern *pat)
1394 {
1395   struct apattern *newsort;
1396   newsort = realloc(*sortlist, (*nsort + 1) * sizeof(struct apattern));
1397   if (!newsort)
1398     return 0;
1399   newsort[*nsort] = *pat;
1400   *sortlist = newsort;
1401   (*nsort)++;
1402   return 1;
1403 }
1404
1405 static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
1406 {
1407
1408   /* Four octets and three periods yields at most 15 characters. */
1409   if (len > 15)
1410     return -1;
1411
1412   addr->s_addr = inet_addr(ipbuf);
1413   if (addr->s_addr == INADDR_NONE && strcmp(ipbuf, "255.255.255.255") != 0)
1414     return -1;
1415   return 0;
1416 }
1417
1418 static void natural_mask(struct apattern *pat)
1419 {
1420   struct in_addr addr;
1421
1422   /* Store a host-byte-order copy of pat in a struct in_addr.  Icky,
1423    * but portable.
1424    */
1425   addr.s_addr = ntohl(pat->addrV4.s_addr);
1426
1427   /* This is out of date in the CIDR world, but some people might
1428    * still rely on it.
1429    */
1430   if (IN_CLASSA(addr.s_addr))
1431     pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
1432   else if (IN_CLASSB(addr.s_addr))
1433     pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
1434   else
1435     pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
1436 }
1437 #endif
1438 /* initialize an rc4 key. If possible a cryptographically secure random key
1439    is generated using a suitable function (for example win32's RtlGenRandom as
1440    described in
1441    http://blogs.msdn.com/michael_howard/archive/2005/01/14/353379.aspx
1442    otherwise the code defaults to cross-platform albeit less secure mechanism
1443    using rand
1444 */
1445 static void randomize_key(unsigned char* key,int key_data_len)
1446 {
1447   int randomized = 0;
1448   int counter=0;
1449 #ifdef WIN32
1450   HMODULE lib=LoadLibrary("ADVAPI32.DLL");
1451   if (lib) {
1452     BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
1453       (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
1454     if (pfn && pfn(key,key_data_len) )
1455       randomized = 1;
1456
1457     FreeLibrary(lib);
1458   }
1459 #else /* !WIN32 */
1460 #ifdef RANDOM_FILE
1461   FILE *f = fopen(RANDOM_FILE, "rb");
1462   if(f) {
1463     counter = fread(key, 1, key_data_len, f);
1464     fclose(f);
1465   }
1466 #endif
1467 #endif /* WIN32 */
1468
1469   if ( !randomized ) {
1470     for (;counter<key_data_len;counter++)
1471       key[counter]=(unsigned char)(rand() % 256);
1472   }
1473 }
1474
1475 static int init_id_key(rc4_key* key,int key_data_len)
1476 {
1477   unsigned char index1;
1478   unsigned char index2;
1479   unsigned char* state;
1480   short counter;
1481   unsigned char *key_data_ptr = 0;
1482
1483   key_data_ptr = calloc(1,key_data_len);
1484   if (!key_data_ptr)
1485     return ARES_ENOMEM;
1486
1487   state = &key->state[0];
1488   for(counter = 0; counter < 256; counter++)
1489     /* unnecessary AND but it keeps some compilers happier */
1490     state[counter] = (unsigned char)(counter & 0xff);
1491   randomize_key(key->state,key_data_len);
1492   key->x = 0;
1493   key->y = 0;
1494   index1 = 0;
1495   index2 = 0;
1496   for(counter = 0; counter < 256; counter++)
1497   {
1498     index2 = (unsigned char)((key_data_ptr[index1] + state[counter] +
1499                               index2) % 256);
1500     ARES_SWAP_BYTE(&state[counter], &state[index2]);
1501
1502     index1 = (unsigned char)((index1 + 1) % key_data_len);
1503   }
1504   free(key_data_ptr);
1505   return ARES_SUCCESS;
1506 }
1507
1508 unsigned short ares__generate_new_id(rc4_key* key)
1509 {
1510   unsigned short r=0;
1511   ares__rc4(key, (unsigned char *)&r, sizeof(r));
1512   return r;
1513 }