1/*
2 * Copyright (c) 2017 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include <dns/dns.h>
17#include <vlibapi/api.h>
18#include <vlibmemory/api.h>
19
20#include <vlib/vlib.h>
21#include <vnet/vnet.h>
22
23/* define message IDs */
24#include <dns/dns.api_enum.h>
25#include <dns/dns.api_types.h>
26
27#include <vlibapi/api_helper_macros.h>
28
29int
30vnet_dns_response_to_reply (u8 * response,
31			    vl_api_dns_resolve_name_reply_t * rmp,
32			    u32 * min_ttlp);
33int
34vnet_dns_response_to_name (u8 * response,
35			   vl_api_dns_resolve_ip_reply_t * rmp,
36			   u32 * min_ttlp);
37
38static void
39resolve_event (dns_main_t * dm, f64 now, u8 * reply)
40{
41  vlib_main_t *vm = dm->vlib_main;
42  dns_pending_request_t *pr;
43  dns_header_t *d;
44  u32 pool_index;
45  dns_cache_entry_t *ep;
46  u32 min_ttl;
47  u16 flags;
48  u16 rcode;
49  int i;
50  int entry_was_valid;
51  int remove_count;
52  int rv = 0;
53
54  d = (dns_header_t *) reply;
55  flags = clib_net_to_host_u16 (d->flags);
56  rcode = flags & DNS_RCODE_MASK;
57
58  /* $$$ u16 limits cache to 65K entries, fix later multiple dst ports */
59  pool_index = clib_net_to_host_u16 (d->id);
60  dns_cache_lock (dm, 10);
61
62  if (pool_is_free_index (dm->entries, pool_index))
63    {
64      vec_free (reply);
65      if (0)
66	clib_warning ("pool index %d is free", pool_index);
67      vlib_node_increment_counter (vm, dns46_reply_node.index,
68				   DNS46_REPLY_ERROR_NO_ELT, 1);
69      dns_cache_unlock (dm);
70      return;
71    }
72
73  ep = pool_elt_at_index (dm->entries, pool_index);
74
75  if (ep->dns_response)
76    vec_free (ep->dns_response);
77
78  /* Handle [sic] recursion AKA CNAME indirection */
79  rv = vnet_dns_cname_indirection_nolock (dm, pool_index, reply);
80
81  /* CNAME found, further resolution pending, we're done here */
82  if (rv > 0)
83    {
84      dns_cache_unlock (dm);
85      return;
86    }
87  /* Server backfire: refused to answer, or sent zero replies */
88  if (rv < 0)
89    {
90      /* Try a different server */
91      if (ep->server_af /* ip6 */ )
92	{
93	  if (0)
94	    clib_warning ("Server %U failed to resolve '%s'",
95			  format_ip6_address,
96			  dm->ip6_name_servers + ep->server_rotor, ep->name);
97	  /* Any more servers to try? */
98	  if (ep->server_fails > 1 || vec_len (dm->ip6_name_servers) <= 1)
99	    {
100	      /* No, tell the client to go away */
101	      goto reply;
102	    }
103	  ep->retry_count = 0;
104	  ep->server_rotor++;
105	  ep->server_fails++;
106	  if (ep->server_rotor >= vec_len (dm->ip6_name_servers))
107	    ep->server_rotor = 0;
108	  if (0)
109	    clib_warning ("Try server %U", format_ip6_address,
110			  dm->ip6_name_servers + ep->server_rotor);
111	  vnet_dns_send_dns6_request
112	    (dm, ep, dm->ip6_name_servers + ep->server_rotor);
113	}
114      else
115	{
116	  if (0)
117	    clib_warning ("Server %U failed to resolve '%s'",
118			  format_ip4_address,
119			  dm->ip4_name_servers + ep->server_rotor, ep->name);
120
121	  if (ep->server_fails > 1 || vec_len (dm->ip4_name_servers) <= 1)
122	    {
123	      /* No, tell the client to go away */
124	      goto reply;
125	    }
126	  ep->retry_count = 0;
127	  ep->server_rotor++;
128	  ep->server_fails++;
129	  if (ep->server_rotor >= vec_len (dm->ip4_name_servers))
130	    ep->server_rotor = 0;
131	  if (0)
132	    clib_warning ("Try server %U", format_ip4_address,
133			  dm->ip4_name_servers + ep->server_rotor);
134	  vnet_dns_send_dns4_request
135	    (dm, ep, dm->ip4_name_servers + ep->server_rotor);
136	}
137      dns_cache_unlock (dm);
138      return;
139    }
140
141reply:
142  /* Save the response */
143  ep->dns_response = reply;
144
145  /*
146   * Pick a sensible default cache entry expiration time.
147   * We don't play the 10-second timeout game.
148   */
149  ep->expiration_time = now + 600.0;
150
151  if (0)
152    clib_warning ("resolving '%s', was %s valid",
153		  ep->name, (ep->flags & DNS_CACHE_ENTRY_FLAG_VALID) ?
154		  "already" : "not");
155  /*
156   * The world is a mess. A single DNS request sent to e.g. 8.8.8.8
157   * may yield multiple, subtly different responses - all with the same
158   * DNS protocol-level ID.
159   *
160   * Last response wins in terms of what ends up in the cache.
161   * First response wins in terms of the response sent to the client.
162   */
163
164  /* Strong hint that we may not find a pending resolution entry */
165  entry_was_valid = (ep->flags & DNS_CACHE_ENTRY_FLAG_VALID) ? 1 : 0;
166
167  if (vec_len (ep->dns_response))
168    ep->flags |= DNS_CACHE_ENTRY_FLAG_VALID;
169
170  /* Most likely, send 1 message */
171  for (i = 0; i < vec_len (ep->pending_requests); i++)
172    {
173      vl_api_registration_t *regp;
174
175      pr = vec_elt_at_index (ep->pending_requests, i);
176
177      switch (pr->request_type)
178	{
179	case DNS_API_PENDING_NAME_TO_IP:
180	  {
181	    vl_api_dns_resolve_name_reply_t *rmp;
182	    regp = vl_api_client_index_to_registration (pr->client_index);
183	    if (regp == 0)
184	      continue;
185
186	    rmp = vl_msg_api_alloc (sizeof (*rmp));
187	    rmp->_vl_msg_id =
188	      clib_host_to_net_u16 (VL_API_DNS_RESOLVE_NAME_REPLY
189				    + dm->msg_id_base);
190	    rmp->context = pr->client_context;
191	    min_ttl = ~0;
192	    rv = vnet_dns_response_to_reply (ep->dns_response, rmp, &min_ttl);
193	    if (min_ttl != ~0)
194	      ep->expiration_time = now + min_ttl;
195	    rmp->retval = clib_host_to_net_u32 (rv);
196	    vl_api_send_msg (regp, (u8 *) rmp);
197	  }
198	  break;
199
200	case DNS_API_PENDING_IP_TO_NAME:
201	  {
202	    vl_api_dns_resolve_ip_reply_t *rmp;
203
204	    regp = vl_api_client_index_to_registration (pr->client_index);
205	    if (regp == 0)
206	      continue;
207
208	    rmp = vl_msg_api_alloc (sizeof (*rmp));
209	    rmp->_vl_msg_id =
210	      clib_host_to_net_u16 (VL_API_DNS_RESOLVE_IP_REPLY
211				    + dm->msg_id_base);
212	    rmp->context = pr->client_context;
213	    min_ttl = ~0;
214	    rv = vnet_dns_response_to_name (ep->dns_response, rmp, &min_ttl);
215	    if (min_ttl != ~0)
216	      ep->expiration_time = now + min_ttl;
217	    rmp->retval = clib_host_to_net_u32 (rv);
218	    vl_api_send_msg (regp, (u8 *) rmp);
219	  }
220	  break;
221
222	case DNS_PEER_PENDING_IP_TO_NAME:
223	case DNS_PEER_PENDING_NAME_TO_IP:
224	  if (pr->is_ip6)
225	    vnet_send_dns6_reply (dm, pr, ep, 0 /* allocate a buffer */ );
226	  else
227	    vnet_send_dns4_reply (dm, pr, ep, 0 /* allocate a buffer */ );
228	  break;
229	default:
230	  clib_warning ("request type %d unknown", pr->request_type);
231	  break;
232	}
233    }
234  vec_free (ep->pending_requests);
235
236  remove_count = 0;
237  for (i = 0; i < vec_len (dm->unresolved_entries); i++)
238    {
239      if (dm->unresolved_entries[i] == pool_index)
240	{
241	  vec_delete (dm->unresolved_entries, 1, i);
242	  remove_count++;
243	  i--;
244	}
245    }
246  /* See multiple response comment above... */
247  if (remove_count == 0)
248    {
249      u32 error_code = entry_was_valid ? DNS46_REPLY_ERROR_MULTIPLE_REPLY :
250	DNS46_REPLY_ERROR_NO_UNRESOLVED_ENTRY;
251
252      vlib_node_increment_counter (vm, dns46_reply_node.index, error_code, 1);
253      dns_cache_unlock (dm);
254      return;
255    }
256
257  /* Deal with bogus names, server issues, etc. */
258  switch (rcode)
259    {
260    default:
261    case DNS_RCODE_NO_ERROR:
262      break;
263
264    case DNS_RCODE_SERVER_FAILURE:
265    case DNS_RCODE_NOT_IMPLEMENTED:
266    case DNS_RCODE_REFUSED:
267      if (ep->server_af == 0)
268	clib_warning ("name server %U can't resolve '%s'",
269		      format_ip4_address,
270		      dm->ip4_name_servers + ep->server_rotor, ep->name);
271      else
272	clib_warning ("name server %U can't resolve '%s'",
273		      format_ip6_address,
274		      dm->ip6_name_servers + ep->server_rotor, ep->name);
275      /* FALLTHROUGH */
276    case DNS_RCODE_NAME_ERROR:
277    case DNS_RCODE_FORMAT_ERROR:
278      /* remove trash from the cache... */
279      vnet_dns_delete_entry_by_index_nolock (dm, ep - dm->entries);
280      break;
281    }
282
283
284  dns_cache_unlock (dm);
285  return;
286}
287
288static void
289retry_scan (dns_main_t * dm, f64 now)
290{
291  int i;
292  dns_cache_entry_t *ep;
293
294  for (i = 0; i < vec_len (dm->unresolved_entries); i++)
295    {
296      dns_cache_lock (dm, 11);
297      ep = pool_elt_at_index (dm->entries, dm->unresolved_entries[i]);
298
299      ASSERT ((ep->flags & DNS_CACHE_ENTRY_FLAG_VALID) == 0);
300      vnet_send_dns_request (dm, ep);
301      dns_cache_unlock (dm);
302    }
303}
304
305static uword
306dns_resolver_process (vlib_main_t * vm,
307		      vlib_node_runtime_t * rt, vlib_frame_t * f)
308{
309  dns_main_t *dm = &dns_main;
310  f64 now;
311  f64 timeout = 1000.0;
312  uword *event_data = 0;
313  uword event_type;
314  int i;
315
316  while (1)
317    {
318      vlib_process_wait_for_event_or_clock (vm, timeout);
319
320      now = vlib_time_now (vm);
321
322      event_type = vlib_process_get_events (vm, (uword **) & event_data);
323
324      switch (event_type)
325	{
326	  /* Send one of these when a resolution is pending */
327	case DNS_RESOLVER_EVENT_PENDING:
328	  timeout = 2.0;
329	  break;
330
331	case DNS_RESOLVER_EVENT_RESOLVED:
332	  for (i = 0; i < vec_len (event_data); i++)
333	    resolve_event (dm, now, (u8 *) event_data[i]);
334	  break;
335
336	case ~0:		/* timeout */
337	  retry_scan (dm, now);
338	  break;
339	}
340      vec_reset_length (event_data);
341
342      /* No work? Back to slow timeout mode... */
343      if (vec_len (dm->unresolved_entries) == 0)
344	timeout = 1000.0;
345    }
346  return 0;			/* or not */
347}
348
349void
350vnet_dns_create_resolver_process (dns_main_t * dm)
351{
352  /* Already created the resolver process? */
353  if (dm->resolver_process_node_index > 0)
354    return;
355
356  /* No, create it now and make a note of the node index */
357  dm->resolver_process_node_index = vlib_process_create
358    (dm->vlib_main, "dns-resolver-process",
359     dns_resolver_process, 16 /* log2_n_stack_bytes */ );
360}
361
362/*
363 * fd.io coding-style-patch-verification: ON
364 *
365 * Local Variables:
366 * eval: (c-set-style "gnu")
367 * End:
368 */
369