lisp: fix use-after-free
[vpp.git] / src / vnet / lisp-cp / control.c
1 /*
2  * Copyright (c) 2016 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 <vlibmemory/api.h>
17 #include <vnet/lisp-cp/control.h>
18 #include <vnet/lisp-cp/packets.h>
19 #include <vnet/lisp-cp/lisp_msg_serdes.h>
20 #include <vnet/lisp-gpe/lisp_gpe_fwd_entry.h>
21 #include <vnet/lisp-gpe/lisp_gpe_tenant.h>
22 #include <vnet/lisp-gpe/lisp_gpe_tunnel.h>
23 #include <vnet/fib/fib_entry.h>
24 #include <vnet/fib/fib_table.h>
25 #include <vnet/ethernet/arp_packet.h>
26 #include <vnet/ethernet/packet.h>
27
28 #include <openssl/evp.h>
29 #include <vnet/crypto/crypto.h>
30
31 #define MAX_VALUE_U24 0xffffff
32
33 /* mapping timer control constants (in seconds) */
34 #define TIME_UNTIL_REFETCH_OR_DELETE  20
35 #define MAPPING_TIMEOUT (((m->ttl) * 60) - TIME_UNTIL_REFETCH_OR_DELETE)
36
37 lisp_cp_main_t lisp_control_main;
38
39 u8 *format_lisp_cp_input_trace (u8 * s, va_list * args);
40 static void *send_map_request_thread_fn (void *arg);
41
42 typedef enum
43 {
44   LISP_CP_INPUT_NEXT_DROP,
45   LISP_CP_INPUT_N_NEXT,
46 } lisp_cp_input_next_t;
47
48 typedef struct
49 {
50   u8 is_resend;
51   gid_address_t seid;
52   gid_address_t deid;
53   u8 smr_invoked;
54 } map_request_args_t;
55
56 u8
57 vnet_lisp_get_map_request_mode (void)
58 {
59   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
60   return lcm->map_request_mode;
61 }
62
63 static u16
64 auth_data_len_by_key_id (lisp_key_type_t key_id)
65 {
66   switch (key_id)
67     {
68     case HMAC_SHA_1_96:
69       return SHA1_AUTH_DATA_LEN;
70     case HMAC_SHA_256_128:
71       return SHA256_AUTH_DATA_LEN;
72     default:
73       clib_warning ("unsupported key type: %d!", key_id);
74       return (u16) ~ 0;
75     }
76   return (u16) ~ 0;
77 }
78
79 static int
80 queue_map_request (gid_address_t * seid, gid_address_t * deid,
81                    u8 smr_invoked, u8 is_resend);
82
83 ip_interface_address_t *
84 ip_interface_get_first_interface_address (ip_lookup_main_t * lm,
85                                           u32 sw_if_index, u8 loop)
86 {
87   vnet_main_t *vnm = vnet_get_main ();
88   vnet_sw_interface_t *swif = vnet_get_sw_interface (vnm, sw_if_index);
89   if (loop && swif->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED)
90     sw_if_index = swif->unnumbered_sw_if_index;
91   u32 ia =
92     (vec_len ((lm)->if_address_pool_index_by_sw_if_index) > (sw_if_index)) ?
93     vec_elt ((lm)->if_address_pool_index_by_sw_if_index, (sw_if_index)) :
94     (u32) ~ 0;
95   return pool_elt_at_index ((lm)->if_address_pool, ia);
96 }
97
98 void *
99 ip_interface_get_first_address (ip_lookup_main_t * lm, u32 sw_if_index,
100                                 u8 version)
101 {
102   ip_interface_address_t *ia;
103
104   ia = ip_interface_get_first_interface_address (lm, sw_if_index, 1);
105   if (!ia)
106     return 0;
107   return ip_interface_address_get_address (lm, ia);
108 }
109
110 int
111 ip_interface_get_first_ip_address (lisp_cp_main_t * lcm, u32 sw_if_index,
112                                    u8 version, ip_address_t * result)
113 {
114   ip_lookup_main_t *lm;
115   void *addr;
116
117   lm = (version == AF_IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
118   addr = ip_interface_get_first_address (lm, sw_if_index, version);
119   if (!addr)
120     return 0;
121
122   ip_address_set (result, addr, version);
123   return 1;
124 }
125
126 /**
127  * convert from a LISP address to a FIB prefix
128  */
129 void
130 ip_address_to_fib_prefix (const ip_address_t * addr, fib_prefix_t * prefix)
131 {
132   if (addr->version == AF_IP4)
133     {
134       prefix->fp_len = 32;
135       prefix->fp_proto = FIB_PROTOCOL_IP4;
136       clib_memset (&prefix->fp_addr.pad, 0, sizeof (prefix->fp_addr.pad));
137       memcpy (&prefix->fp_addr.ip4, &addr->ip.ip4,
138               sizeof (prefix->fp_addr.ip4));
139     }
140   else
141     {
142       prefix->fp_len = 128;
143       prefix->fp_proto = FIB_PROTOCOL_IP6;
144       memcpy (&prefix->fp_addr.ip6, &addr->ip.ip6,
145               sizeof (prefix->fp_addr.ip6));
146     }
147   prefix->___fp___pad = 0;
148 }
149
150 /**
151  * convert from a LISP to a FIB prefix
152  */
153 void
154 ip_prefix_to_fib_prefix (const ip_prefix_t * ip_prefix,
155                          fib_prefix_t * fib_prefix)
156 {
157   ip_address_to_fib_prefix (&ip_prefix->addr, fib_prefix);
158   fib_prefix->fp_len = ip_prefix->len;
159 }
160
161 /**
162  * Find the sw_if_index of the interface that would be used to egress towards
163  * dst.
164  */
165 u32
166 ip_fib_get_egress_iface_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst)
167 {
168   fib_node_index_t fei;
169   fib_prefix_t prefix;
170
171   ip_address_to_fib_prefix (dst, &prefix);
172
173   fei = fib_table_lookup (0, &prefix);
174
175   return (fib_entry_get_resolving_interface (fei));
176 }
177
178 /**
179  * Find first IP of the interface that would be used to egress towards dst.
180  * Returns 1 if the address is found 0 otherwise.
181  */
182 int
183 ip_fib_get_first_egress_ip_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst,
184                                     ip_address_t * result)
185 {
186   u32 si;
187   ip_lookup_main_t *lm;
188   void *addr = 0;
189   u8 ipver;
190
191   ASSERT (result != 0);
192
193   ipver = ip_addr_version (dst);
194
195   lm = (ipver == AF_IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
196   si = ip_fib_get_egress_iface_for_dst (lcm, dst);
197
198   if ((u32) ~ 0 == si)
199     return 0;
200
201   /* find the first ip address */
202   addr = ip_interface_get_first_address (lm, si, ipver);
203   if (0 == addr)
204     return 0;
205
206   ip_address_set (result, addr, ipver);
207   return 1;
208 }
209
210 static int
211 dp_add_del_iface (lisp_cp_main_t * lcm, u32 vni, u8 is_l2, u8 is_add,
212                   u8 with_default_route)
213 {
214   uword *dp_table;
215
216   if (!is_l2)
217     {
218       dp_table = hash_get (lcm->table_id_by_vni, vni);
219
220       if (!dp_table)
221         {
222           clib_warning ("vni %d not associated to a vrf!", vni);
223           return VNET_API_ERROR_INVALID_VALUE;
224         }
225     }
226   else
227     {
228       dp_table = hash_get (lcm->bd_id_by_vni, vni);
229       if (!dp_table)
230         {
231           clib_warning ("vni %d not associated to a bridge domain!", vni);
232           return VNET_API_ERROR_INVALID_VALUE;
233         }
234     }
235
236   /* enable/disable data-plane interface */
237   if (is_add)
238     {
239       if (is_l2)
240         lisp_gpe_tenant_l2_iface_add_or_lock (vni, dp_table[0]);
241       else
242         lisp_gpe_tenant_l3_iface_add_or_lock (vni, dp_table[0],
243                                               with_default_route);
244     }
245   else
246     {
247       if (is_l2)
248         lisp_gpe_tenant_l2_iface_unlock (vni);
249       else
250         lisp_gpe_tenant_l3_iface_unlock (vni);
251     }
252
253   return 0;
254 }
255
256 static void
257 dp_del_fwd_entry (lisp_cp_main_t * lcm, u32 dst_map_index)
258 {
259   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
260   fwd_entry_t *fe = 0;
261   uword *feip = 0;
262   clib_memset (a, 0, sizeof (*a));
263
264   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
265   if (!feip)
266     return;
267
268   fe = pool_elt_at_index (lcm->fwd_entry_pool, feip[0]);
269
270   /* delete dp fwd entry */
271   u32 sw_if_index;
272   a->is_add = 0;
273   a->locator_pairs = fe->locator_pairs;
274   a->vni = gid_address_vni (&fe->reid);
275   gid_address_copy (&a->rmt_eid, &fe->reid);
276   if (fe->is_src_dst)
277     gid_address_copy (&a->lcl_eid, &fe->leid);
278
279   vnet_lisp_gpe_del_fwd_counters (a, feip[0]);
280   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
281
282   /* delete entry in fwd table */
283   hash_unset (lcm->fwd_entry_by_mapping_index, dst_map_index);
284   vec_free (fe->locator_pairs);
285   pool_put (lcm->fwd_entry_pool, fe);
286 }
287
288 /**
289  * Finds first remote locator with best (lowest) priority that has a local
290  * peer locator with an underlying route to it.
291  *
292  */
293 static u32
294 get_locator_pairs (lisp_cp_main_t * lcm, mapping_t * lcl_map,
295                    mapping_t * rmt_map, locator_pair_t ** locator_pairs)
296 {
297   u32 i, limitp = 0, li, found = 0, esi;
298   locator_set_t *rmt_ls, *lcl_ls;
299   ip_address_t _lcl_addr, *lcl_addr = &_lcl_addr;
300   locator_t *lp, *rmt = 0;
301   uword *checked = 0;
302   locator_pair_t pair;
303
304   rmt_ls =
305     pool_elt_at_index (lcm->locator_set_pool, rmt_map->locator_set_index);
306   lcl_ls =
307     pool_elt_at_index (lcm->locator_set_pool, lcl_map->locator_set_index);
308
309   if (!rmt_ls || vec_len (rmt_ls->locator_indices) == 0)
310     return 0;
311
312   while (1)
313     {
314       rmt = 0;
315
316       /* find unvisited remote locator with best priority */
317       for (i = 0; i < vec_len (rmt_ls->locator_indices); i++)
318         {
319           if (0 != hash_get (checked, i))
320             continue;
321
322           li = vec_elt (rmt_ls->locator_indices, i);
323           lp = pool_elt_at_index (lcm->locator_pool, li);
324
325           /* we don't support non-IP locators for now */
326           if (gid_address_type (&lp->address) != GID_ADDR_IP_PREFIX)
327             continue;
328
329           if ((found && lp->priority == limitp)
330               || (!found && lp->priority >= limitp))
331             {
332               rmt = lp;
333
334               /* don't search for locators with lower priority and don't
335                * check this locator again*/
336               limitp = lp->priority;
337               hash_set (checked, i, 1);
338               break;
339             }
340         }
341       /* check if a local locator with a route to remote locator exists */
342       if (rmt != 0)
343         {
344           /* find egress sw_if_index for rmt locator */
345           esi =
346             ip_fib_get_egress_iface_for_dst (lcm,
347                                              &gid_address_ip (&rmt->address));
348           if ((u32) ~ 0 == esi)
349             continue;
350
351           for (i = 0; i < vec_len (lcl_ls->locator_indices); i++)
352             {
353               li = vec_elt (lcl_ls->locator_indices, i);
354               locator_t *sl = pool_elt_at_index (lcm->locator_pool, li);
355
356               /* found local locator with the needed sw_if_index */
357               if (sl->sw_if_index == esi)
358                 {
359                   /* and it has an address */
360                   if (0 == ip_interface_get_first_ip_address (lcm,
361                                                               sl->sw_if_index,
362                                                               gid_address_ip_version
363                                                               (&rmt->address),
364                                                               lcl_addr))
365                     continue;
366
367                   clib_memset (&pair, 0, sizeof (pair));
368                   ip_address_copy (&pair.rmt_loc,
369                                    &gid_address_ip (&rmt->address));
370                   ip_address_copy (&pair.lcl_loc, lcl_addr);
371                   pair.weight = rmt->weight;
372                   pair.priority = rmt->priority;
373                   vec_add1 (locator_pairs[0], pair);
374                   found = 1;
375                 }
376             }
377         }
378       else
379         break;
380     }
381
382   hash_free (checked);
383   return found;
384 }
385
386 static void
387 gid_address_sd_to_flat (gid_address_t * dst, gid_address_t * src,
388                         fid_address_t * fid)
389 {
390   ASSERT (GID_ADDR_SRC_DST == gid_address_type (src));
391
392   dst[0] = src[0];
393
394   switch (fid_addr_type (fid))
395     {
396     case FID_ADDR_IP_PREF:
397       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
398       gid_address_ippref (dst) = fid_addr_ippref (fid);
399       break;
400     case FID_ADDR_MAC:
401       gid_address_type (dst) = GID_ADDR_MAC;
402       mac_copy (gid_address_mac (dst), fid_addr_mac (fid));
403       break;
404     default:
405       clib_warning ("Unsupported fid type %d!", fid_addr_type (fid));
406       break;
407     }
408 }
409
410 u8
411 vnet_lisp_map_register_state_get (void)
412 {
413   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
414   return lcm->map_registering;
415 }
416
417 u8
418 vnet_lisp_rloc_probe_state_get (void)
419 {
420   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
421   return lcm->rloc_probing;
422 }
423
424 static void
425 dp_add_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index)
426 {
427   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
428   gid_address_t *rmt_eid, *lcl_eid;
429   mapping_t *lcl_map, *rmt_map;
430   u32 sw_if_index, **rmts, rmts_idx;
431   uword *feip = 0, *dpid, *rmts_stored_idxp = 0;
432   fwd_entry_t *fe;
433   u8 type, is_src_dst = 0;
434   int rv;
435
436   clib_memset (a, 0, sizeof (*a));
437
438   /* remove entry if it already exists */
439   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
440   if (feip)
441     dp_del_fwd_entry (lcm, dst_map_index);
442
443   /*
444    * Determine local mapping and eid
445    */
446   if (lcm->flags & LISP_FLAG_PITR_MODE)
447     {
448       if (lcm->pitr_map_index != ~0)
449         lcl_map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
450       else
451         {
452           clib_warning ("no PITR mapping configured!");
453           return;
454         }
455     }
456   else
457     lcl_map = pool_elt_at_index (lcm->mapping_pool, src_map_index);
458   lcl_eid = &lcl_map->eid;
459
460   /*
461    * Determine remote mapping and eid
462    */
463   rmt_map = pool_elt_at_index (lcm->mapping_pool, dst_map_index);
464   rmt_eid = &rmt_map->eid;
465
466   /*
467    * Build and insert data plane forwarding entry
468    */
469   a->is_add = 1;
470
471   if (MR_MODE_SRC_DST == lcm->map_request_mode)
472     {
473       if (GID_ADDR_SRC_DST == gid_address_type (rmt_eid))
474         {
475           gid_address_sd_to_flat (&a->rmt_eid, rmt_eid,
476                                   &gid_address_sd_dst (rmt_eid));
477           gid_address_sd_to_flat (&a->lcl_eid, rmt_eid,
478                                   &gid_address_sd_src (rmt_eid));
479         }
480       else
481         {
482           gid_address_copy (&a->rmt_eid, rmt_eid);
483           gid_address_copy (&a->lcl_eid, lcl_eid);
484         }
485       is_src_dst = 1;
486     }
487   else
488     gid_address_copy (&a->rmt_eid, rmt_eid);
489
490   a->vni = gid_address_vni (&a->rmt_eid);
491   a->is_src_dst = is_src_dst;
492
493   /* get vrf or bd_index associated to vni */
494   type = gid_address_type (&a->rmt_eid);
495   if (GID_ADDR_IP_PREFIX == type)
496     {
497       dpid = hash_get (lcm->table_id_by_vni, a->vni);
498       if (!dpid)
499         {
500           clib_warning ("vni %d not associated to a vrf!", a->vni);
501           return;
502         }
503       a->table_id = dpid[0];
504     }
505   else if (GID_ADDR_MAC == type)
506     {
507       dpid = hash_get (lcm->bd_id_by_vni, a->vni);
508       if (!dpid)
509         {
510           clib_warning ("vni %d not associated to a bridge domain !", a->vni);
511           return;
512         }
513       a->bd_id = dpid[0];
514     }
515
516   /* find best locator pair that 1) verifies LISP policy 2) are connected */
517   rv = get_locator_pairs (lcm, lcl_map, rmt_map, &a->locator_pairs);
518
519   /* Either rmt mapping is negative or we can't find underlay path.
520    * Try again with petr if configured */
521   if (rv == 0 && (lcm->flags & LISP_FLAG_USE_PETR))
522     {
523       rmt_map = lisp_get_petr_mapping (lcm);
524       rv = get_locator_pairs (lcm, lcl_map, rmt_map, &a->locator_pairs);
525     }
526
527   /* negative entry */
528   if (rv == 0)
529     {
530       a->is_negative = 1;
531       a->action = rmt_map->action;
532     }
533
534   rv = vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
535   if (rv)
536     {
537       if (a->locator_pairs)
538         vec_free (a->locator_pairs);
539       return;
540     }
541
542   /* add tunnel to fwd entry table */
543   pool_get (lcm->fwd_entry_pool, fe);
544   vnet_lisp_gpe_add_fwd_counters (a, fe - lcm->fwd_entry_pool);
545
546   fe->locator_pairs = a->locator_pairs;
547   gid_address_copy (&fe->reid, &a->rmt_eid);
548
549   if (is_src_dst)
550     gid_address_copy (&fe->leid, &a->lcl_eid);
551   else
552     gid_address_copy (&fe->leid, lcl_eid);
553
554   fe->is_src_dst = is_src_dst;
555   hash_set (lcm->fwd_entry_by_mapping_index, dst_map_index,
556             fe - lcm->fwd_entry_pool);
557
558   /* Add rmt mapping to the vector of adjacent mappings to lcl mapping */
559   rmts_stored_idxp =
560     hash_get (lcm->lcl_to_rmt_adjs_by_lcl_idx, src_map_index);
561   if (!rmts_stored_idxp)
562     {
563       pool_get (lcm->lcl_to_rmt_adjacencies, rmts);
564       clib_memset (rmts, 0, sizeof (*rmts));
565       rmts_idx = rmts - lcm->lcl_to_rmt_adjacencies;
566       hash_set (lcm->lcl_to_rmt_adjs_by_lcl_idx, src_map_index, rmts_idx);
567     }
568   else
569     {
570       rmts_idx = (u32) (*rmts_stored_idxp);
571       rmts = pool_elt_at_index (lcm->lcl_to_rmt_adjacencies, rmts_idx);
572     }
573   vec_add1 (rmts[0], dst_map_index);
574 }
575
576 typedef struct
577 {
578   u32 si;
579   u32 di;
580 } fwd_entry_mt_arg_t;
581
582 static void *
583 dp_add_fwd_entry_thread_fn (void *arg)
584 {
585   fwd_entry_mt_arg_t *a = arg;
586   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
587   dp_add_fwd_entry (lcm, a->si, a->di);
588   return 0;
589 }
590
591 static int
592 dp_add_fwd_entry_from_mt (u32 si, u32 di)
593 {
594   fwd_entry_mt_arg_t a;
595
596   clib_memset (&a, 0, sizeof (a));
597   a.si = si;
598   a.di = di;
599
600   vl_api_rpc_call_main_thread (dp_add_fwd_entry_thread_fn,
601                                (u8 *) & a, sizeof (a));
602   return 0;
603 }
604
605 /**
606  * Returns vector of adjacencies.
607  *
608  * The caller must free the vector returned by this function.
609  *
610  * @param vni virtual network identifier
611  * @return vector of adjacencies
612  */
613 lisp_adjacency_t *
614 vnet_lisp_adjacencies_get_by_vni (u32 vni)
615 {
616   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
617   fwd_entry_t *fwd;
618   lisp_adjacency_t *adjs = 0, adj;
619
620   /* *INDENT-OFF* */
621   pool_foreach(fwd, lcm->fwd_entry_pool,
622   ({
623     if (gid_address_vni (&fwd->reid) != vni)
624       continue;
625
626     gid_address_copy (&adj.reid, &fwd->reid);
627     gid_address_copy (&adj.leid, &fwd->leid);
628     vec_add1 (adjs, adj);
629   }));
630   /* *INDENT-ON* */
631
632   return adjs;
633 }
634
635 static lisp_msmr_t *
636 get_map_server (ip_address_t * a)
637 {
638   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
639   lisp_msmr_t *m;
640
641   vec_foreach (m, lcm->map_servers)
642   {
643     if (!ip_address_cmp (&m->address, a))
644       {
645         return m;
646       }
647   }
648   return 0;
649 }
650
651 static lisp_msmr_t *
652 get_map_resolver (ip_address_t * a)
653 {
654   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
655   lisp_msmr_t *m;
656
657   vec_foreach (m, lcm->map_resolvers)
658   {
659     if (!ip_address_cmp (&m->address, a))
660       {
661         return m;
662       }
663   }
664   return 0;
665 }
666
667 int
668 vnet_lisp_add_del_map_server (ip_address_t * addr, u8 is_add)
669 {
670   u32 i;
671   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
672   lisp_msmr_t _ms, *ms = &_ms;
673
674   if (vnet_lisp_enable_disable_status () == 0)
675     {
676       clib_warning ("LISP is disabled!");
677       return VNET_API_ERROR_LISP_DISABLED;
678     }
679
680   if (is_add)
681     {
682       if (get_map_server (addr))
683         {
684           clib_warning ("map-server %U already exists!", format_ip_address,
685                         addr);
686           return -1;
687         }
688
689       clib_memset (ms, 0, sizeof (*ms));
690       ip_address_copy (&ms->address, addr);
691       vec_add1 (lcm->map_servers, ms[0]);
692
693       if (vec_len (lcm->map_servers) == 1)
694         lcm->do_map_server_election = 1;
695     }
696   else
697     {
698       for (i = 0; i < vec_len (lcm->map_servers); i++)
699         {
700           ms = vec_elt_at_index (lcm->map_servers, i);
701           if (!ip_address_cmp (&ms->address, addr))
702             {
703               if (!ip_address_cmp (&ms->address, &lcm->active_map_server))
704                 lcm->do_map_server_election = 1;
705
706               vec_del1 (lcm->map_servers, i);
707               break;
708             }
709         }
710     }
711
712   return 0;
713 }
714
715 /**
716  * Add/remove mapping to/from map-cache. Overwriting not allowed.
717  */
718 int
719 vnet_lisp_map_cache_add_del (vnet_lisp_add_del_mapping_args_t * a,
720                              u32 * map_index_result)
721 {
722   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
723   u32 mi, *map_indexp, map_index, i;
724   u32 **rmts = 0, *remote_idxp, rmts_itr, remote_idx;
725   uword *rmts_idxp;
726   mapping_t *m, *old_map;
727   u32 **eid_indexes;
728
729   if (gid_address_type (&a->eid) == GID_ADDR_NSH)
730     {
731       if (gid_address_vni (&a->eid) != 0)
732         {
733           clib_warning ("Supported only default VNI for NSH!");
734           return VNET_API_ERROR_INVALID_ARGUMENT;
735         }
736       if (gid_address_nsh_spi (&a->eid) > MAX_VALUE_U24)
737         {
738           clib_warning ("SPI is greater than 24bit!");
739           return VNET_API_ERROR_INVALID_ARGUMENT;
740         }
741     }
742
743   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->eid);
744   old_map = mi != ~0 ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
745   if (a->is_add)
746     {
747       /* TODO check if overwriting and take appropriate actions */
748       if (mi != GID_LOOKUP_MISS && !gid_address_cmp (&old_map->eid, &a->eid))
749         {
750           clib_warning ("eid %U found in the eid-table", format_gid_address,
751                         &a->eid);
752           return VNET_API_ERROR_VALUE_EXIST;
753         }
754
755       pool_get (lcm->mapping_pool, m);
756       gid_address_copy (&m->eid, &a->eid);
757       m->locator_set_index = a->locator_set_index;
758       m->ttl = a->ttl;
759       m->action = a->action;
760       m->local = a->local;
761       m->is_static = a->is_static;
762       m->key = vec_dup (a->key);
763       m->key_id = a->key_id;
764       m->authoritative = a->authoritative;
765
766       map_index = m - lcm->mapping_pool;
767       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, map_index,
768                               1);
769
770       if (pool_is_free_index (lcm->locator_set_pool, a->locator_set_index))
771         {
772           clib_warning ("Locator set with index %d doesn't exist",
773                         a->locator_set_index);
774           return VNET_API_ERROR_INVALID_VALUE;
775         }
776
777       /* add eid to list of eids supported by locator-set */
778       vec_validate (lcm->locator_set_to_eids, a->locator_set_index);
779       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
780                                       a->locator_set_index);
781       vec_add1 (eid_indexes[0], map_index);
782
783       if (a->local)
784         {
785           /* mark as local */
786           vec_add1 (lcm->local_mappings_indexes, map_index);
787         }
788       map_index_result[0] = map_index;
789     }
790   else
791     {
792       if (mi == GID_LOOKUP_MISS)
793         {
794           clib_warning ("eid %U not found in the eid-table",
795                         format_gid_address, &a->eid);
796           return VNET_API_ERROR_INVALID_VALUE;
797         }
798
799       /* clear locator-set to eids binding */
800       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
801                                       a->locator_set_index);
802       for (i = 0; i < vec_len (eid_indexes[0]); i++)
803         {
804           map_indexp = vec_elt_at_index (eid_indexes[0], i);
805           if (map_indexp[0] == mi)
806             break;
807         }
808       vec_del1 (eid_indexes[0], i);
809
810       /* remove local mark if needed */
811       m = pool_elt_at_index (lcm->mapping_pool, mi);
812       if (m->local)
813         {
814           /* Remove adjacencies associated with the local mapping */
815           rmts_idxp = hash_get (lcm->lcl_to_rmt_adjs_by_lcl_idx, mi);
816           if (rmts_idxp)
817             {
818               rmts =
819                 pool_elt_at_index (lcm->lcl_to_rmt_adjacencies, rmts_idxp[0]);
820               vec_foreach (remote_idxp, rmts[0])
821               {
822                 dp_del_fwd_entry (lcm, remote_idxp[0]);
823               }
824               vec_free (rmts[0]);
825               pool_put (lcm->lcl_to_rmt_adjacencies, rmts);
826               hash_unset (lcm->lcl_to_rmt_adjs_by_lcl_idx, mi);
827             }
828
829           u32 k, *lm_indexp;
830           for (k = 0; k < vec_len (lcm->local_mappings_indexes); k++)
831             {
832               lm_indexp = vec_elt_at_index (lcm->local_mappings_indexes, k);
833               if (lm_indexp[0] == mi)
834                 break;
835             }
836           vec_del1 (lcm->local_mappings_indexes, k);
837         }
838       else
839         {
840           /* Remove remote (if present) from the vectors of lcl-to-rmts
841            * TODO: Address this in a more efficient way.
842            */
843           /* *INDENT-OFF* */
844           pool_foreach (rmts, lcm->lcl_to_rmt_adjacencies,
845           ({
846             vec_foreach_index (rmts_itr, rmts[0])
847             {
848               remote_idx = vec_elt (rmts[0], rmts_itr);
849               if (mi == remote_idx)
850                 {
851                   vec_del1 (rmts[0], rmts_itr);
852                   break;
853                 }
854             }
855           }));
856           /* *INDENT-ON* */
857         }
858
859       /* remove mapping from dictionary */
860       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, 0, 0);
861       gid_address_free (&m->eid);
862       pool_put_index (lcm->mapping_pool, mi);
863     }
864
865   return 0;
866 }
867
868 /**
869  *  Add/update/delete mapping to/in/from map-cache.
870  */
871 int
872 vnet_lisp_add_del_local_mapping (vnet_lisp_add_del_mapping_args_t * a,
873                                  u32 * map_index_result)
874 {
875   uword *dp_table = 0;
876   u32 vni;
877   u8 type;
878
879   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
880
881   if (vnet_lisp_enable_disable_status () == 0)
882     {
883       clib_warning ("LISP is disabled!");
884       return VNET_API_ERROR_LISP_DISABLED;
885     }
886
887   vni = gid_address_vni (&a->eid);
888   type = gid_address_type (&a->eid);
889   if (GID_ADDR_IP_PREFIX == type)
890     dp_table = hash_get (lcm->table_id_by_vni, vni);
891   else if (GID_ADDR_MAC == type)
892     dp_table = hash_get (lcm->bd_id_by_vni, vni);
893
894   if (!dp_table && GID_ADDR_NSH != type)
895     {
896       clib_warning ("vni %d not associated to a %s!", vni,
897                     GID_ADDR_IP_PREFIX == type ? "vrf" : "bd");
898       return VNET_API_ERROR_INVALID_VALUE;
899     }
900
901   /* store/remove mapping from map-cache */
902   return vnet_lisp_map_cache_add_del (a, map_index_result);
903 }
904
905 static int
906 add_l2_arp_bd (BVT (clib_bihash_kv) * kvp, void *arg)
907 {
908   u32 **ht = arg;
909   u32 version = (u32) kvp->key[0];
910   if (AF_IP6 == version)
911     return (BIHASH_WALK_CONTINUE);
912
913   u32 bd = (u32) (kvp->key[0] >> 32);
914   hash_set (ht[0], bd, 0);
915   return (BIHASH_WALK_CONTINUE);
916 }
917
918 u32 *
919 vnet_lisp_l2_arp_bds_get (void)
920 {
921   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
922   u32 *bds = 0;
923
924   gid_dict_foreach_l2_arp_ndp_entry (&lcm->mapping_index_by_gid,
925                                      add_l2_arp_bd, &bds);
926   return bds;
927 }
928
929 static int
930 add_ndp_bd (BVT (clib_bihash_kv) * kvp, void *arg)
931 {
932   u32 **ht = arg;
933   u32 version = (u32) kvp->key[0];
934   if (AF_IP4 == version)
935     return (BIHASH_WALK_CONTINUE);
936
937   u32 bd = (u32) (kvp->key[0] >> 32);
938   hash_set (ht[0], bd, 0);
939   return (BIHASH_WALK_CONTINUE);
940 }
941
942 u32 *
943 vnet_lisp_ndp_bds_get (void)
944 {
945   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
946   u32 *bds = 0;
947
948   gid_dict_foreach_l2_arp_ndp_entry (&lcm->mapping_index_by_gid,
949                                      add_ndp_bd, &bds);
950   return bds;
951 }
952
953 typedef struct
954 {
955   void *vector;
956   u32 bd;
957 } lisp_add_l2_arp_ndp_args_t;
958
959 static int
960 add_l2_arp_entry (BVT (clib_bihash_kv) * kvp, void *arg)
961 {
962   lisp_add_l2_arp_ndp_args_t *a = arg;
963   lisp_api_l2_arp_entry_t **vector = a->vector, e;
964
965   u32 version = (u32) kvp->key[0];
966   if (AF_IP6 == version)
967     return (BIHASH_WALK_CONTINUE);
968
969   u32 bd = (u32) (kvp->key[0] >> 32);
970
971   if (bd == a->bd)
972     {
973       mac_copy (e.mac, (void *) &kvp->value);
974       e.ip4 = (u32) kvp->key[1];
975       vec_add1 (vector[0], e);
976     }
977   return (BIHASH_WALK_CONTINUE);
978 }
979
980 lisp_api_l2_arp_entry_t *
981 vnet_lisp_l2_arp_entries_get_by_bd (u32 bd)
982 {
983   lisp_api_l2_arp_entry_t *entries = 0;
984   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
985   lisp_add_l2_arp_ndp_args_t a;
986
987   a.vector = &entries;
988   a.bd = bd;
989
990   gid_dict_foreach_l2_arp_ndp_entry (&lcm->mapping_index_by_gid,
991                                      add_l2_arp_entry, &a);
992   return entries;
993 }
994
995 static int
996 add_ndp_entry (BVT (clib_bihash_kv) * kvp, void *arg)
997 {
998   lisp_add_l2_arp_ndp_args_t *a = arg;
999   lisp_api_ndp_entry_t **vector = a->vector, e;
1000
1001   u32 version = (u32) kvp->key[0];
1002   if (AF_IP4 == version)
1003     return (BIHASH_WALK_CONTINUE);
1004
1005   u32 bd = (u32) (kvp->key[0] >> 32);
1006
1007   if (bd == a->bd)
1008     {
1009       mac_copy (e.mac, (void *) &kvp->value);
1010       clib_memcpy (e.ip6, &kvp->key[1], 16);
1011       vec_add1 (vector[0], e);
1012     }
1013   return (BIHASH_WALK_CONTINUE);
1014 }
1015
1016 lisp_api_ndp_entry_t *
1017 vnet_lisp_ndp_entries_get_by_bd (u32 bd)
1018 {
1019   lisp_api_ndp_entry_t *entries = 0;
1020   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1021   lisp_add_l2_arp_ndp_args_t a;
1022
1023   a.vector = &entries;
1024   a.bd = bd;
1025
1026   gid_dict_foreach_l2_arp_ndp_entry (&lcm->mapping_index_by_gid,
1027                                      add_ndp_entry, &a);
1028   return entries;
1029 }
1030
1031 int
1032 vnet_lisp_add_del_l2_arp_ndp_entry (gid_address_t * key, u8 * mac, u8 is_add)
1033 {
1034   if (vnet_lisp_enable_disable_status () == 0)
1035     {
1036       clib_warning ("LISP is disabled!");
1037       return VNET_API_ERROR_LISP_DISABLED;
1038     }
1039
1040   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1041   int rc = 0;
1042
1043   u64 res = gid_dictionary_lookup (&lcm->mapping_index_by_gid, key);
1044   if (is_add)
1045     {
1046       if (res != GID_LOOKUP_MISS_L2)
1047         {
1048           clib_warning ("Entry %U exists in DB!", format_gid_address, key);
1049           return VNET_API_ERROR_ENTRY_ALREADY_EXISTS;
1050         }
1051       u64 val = mac_to_u64 (mac);
1052       gid_dictionary_add_del (&lcm->mapping_index_by_gid, key, val,
1053                               1 /* is_add */ );
1054     }
1055   else
1056     {
1057       if (res == GID_LOOKUP_MISS_L2)
1058         {
1059           clib_warning ("ONE entry %U not found - cannot delete!",
1060                         format_gid_address, key);
1061           return -1;
1062         }
1063       gid_dictionary_add_del (&lcm->mapping_index_by_gid, key, 0,
1064                               0 /* is_add */ );
1065     }
1066
1067   return rc;
1068 }
1069
1070 int
1071 vnet_lisp_eid_table_map (u32 vni, u32 dp_id, u8 is_l2, u8 is_add)
1072 {
1073   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1074   uword *dp_idp, *vnip, **dp_table_by_vni, **vni_by_dp_table;
1075
1076   if (vnet_lisp_enable_disable_status () == 0)
1077     {
1078       clib_warning ("LISP is disabled!");
1079       return VNET_API_ERROR_LISP_DISABLED;
1080     }
1081
1082   dp_table_by_vni = is_l2 ? &lcm->bd_id_by_vni : &lcm->table_id_by_vni;
1083   vni_by_dp_table = is_l2 ? &lcm->vni_by_bd_id : &lcm->vni_by_table_id;
1084
1085   if (!is_l2 && (vni == 0 || dp_id == 0))
1086     {
1087       clib_warning ("can't add/del default vni-vrf mapping!");
1088       return -1;
1089     }
1090
1091   dp_idp = hash_get (dp_table_by_vni[0], vni);
1092   vnip = hash_get (vni_by_dp_table[0], dp_id);
1093
1094   if (is_add)
1095     {
1096       if (dp_idp || vnip)
1097         {
1098           clib_warning ("vni %d or vrf %d already used in vrf/vni "
1099                         "mapping!", vni, dp_id);
1100           return -1;
1101         }
1102       hash_set (dp_table_by_vni[0], vni, dp_id);
1103       hash_set (vni_by_dp_table[0], dp_id, vni);
1104
1105       /* create dp iface */
1106       dp_add_del_iface (lcm, vni, is_l2, 1 /* is_add */ ,
1107                         1 /* with_default_route */ );
1108     }
1109   else
1110     {
1111       if (!dp_idp || !vnip)
1112         {
1113           clib_warning ("vni %d or vrf %d not used in any vrf/vni! "
1114                         "mapping!", vni, dp_id);
1115           return -1;
1116         }
1117       /* remove dp iface */
1118       dp_add_del_iface (lcm, vni, is_l2, 0 /* is_add */ , 0 /* unused */ );
1119
1120       hash_unset (dp_table_by_vni[0], vni);
1121       hash_unset (vni_by_dp_table[0], dp_id);
1122     }
1123   return 0;
1124
1125 }
1126
1127 /* return 0 if the two locator sets are identical 1 otherwise */
1128 static u8
1129 compare_locators (lisp_cp_main_t * lcm, u32 * old_ls_indexes,
1130                   locator_t * new_locators)
1131 {
1132   u32 i, old_li;
1133   locator_t *old_loc, *new_loc;
1134
1135   if (vec_len (old_ls_indexes) != vec_len (new_locators))
1136     return 1;
1137
1138   for (i = 0; i < vec_len (new_locators); i++)
1139     {
1140       old_li = vec_elt (old_ls_indexes, i);
1141       old_loc = pool_elt_at_index (lcm->locator_pool, old_li);
1142
1143       new_loc = vec_elt_at_index (new_locators, i);
1144
1145       if (locator_cmp (old_loc, new_loc))
1146         return 1;
1147     }
1148   return 0;
1149 }
1150
1151 typedef struct
1152 {
1153   u8 is_negative;
1154   void *lcm;
1155   gid_address_t *eids_to_be_deleted;
1156 } remove_mapping_args_t;
1157
1158 /**
1159  * Callback invoked when a sub-prefix is found
1160  */
1161 static void
1162 remove_mapping_if_needed (u32 mi, void *arg)
1163 {
1164   u8 delete = 0;
1165   remove_mapping_args_t *a = arg;
1166   lisp_cp_main_t *lcm = a->lcm;
1167   mapping_t *m;
1168   locator_set_t *ls;
1169
1170   m = pool_elt_at_index (lcm->mapping_pool, mi);
1171   if (!m)
1172     return;
1173
1174   ls = pool_elt_at_index (lcm->locator_set_pool, m->locator_set_index);
1175
1176   if (a->is_negative)
1177     {
1178       if (0 != vec_len (ls->locator_indices))
1179         delete = 1;
1180     }
1181   else
1182     {
1183       if (0 == vec_len (ls->locator_indices))
1184         delete = 1;
1185     }
1186
1187   if (delete)
1188     vec_add1 (a->eids_to_be_deleted, m->eid);
1189 }
1190
1191 /**
1192  * This function searches map cache and looks for IP prefixes that are subset
1193  * of the provided one. If such prefix is found depending on 'is_negative'
1194  * it does follows:
1195  *
1196  * 1) if is_negative is true and found prefix points to positive mapping,
1197  *    then the mapping is removed
1198  * 2) if is_negative is false and found prefix points to negative mapping,
1199  *    then the mapping is removed
1200  */
1201 static void
1202 remove_overlapping_sub_prefixes (lisp_cp_main_t * lcm, gid_address_t * eid,
1203                                  u8 is_negative)
1204 {
1205   gid_address_t *e;
1206   remove_mapping_args_t a;
1207
1208   clib_memset (&a, 0, sizeof (a));
1209
1210   /* do this only in src/dst mode ... */
1211   if (MR_MODE_SRC_DST != lcm->map_request_mode)
1212     return;
1213
1214   /* ... and  only for IP prefix */
1215   if (GID_ADDR_SRC_DST != gid_address_type (eid)
1216       || (FID_ADDR_IP_PREF != gid_address_sd_dst_type (eid)))
1217     return;
1218
1219   a.is_negative = is_negative;
1220   a.lcm = lcm;
1221
1222   gid_dict_foreach_subprefix (&lcm->mapping_index_by_gid, eid,
1223                               remove_mapping_if_needed, &a);
1224
1225   vec_foreach (e, a.eids_to_be_deleted)
1226   {
1227     vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
1228
1229     clib_memset (adj_args, 0, sizeof (adj_args[0]));
1230     gid_address_copy (&adj_args->reid, e);
1231     adj_args->is_add = 0;
1232     if (vnet_lisp_add_del_adjacency (adj_args))
1233       clib_warning ("failed to del adjacency!");
1234
1235     vnet_lisp_del_mapping (e, NULL);
1236   }
1237
1238   vec_free (a.eids_to_be_deleted);
1239 }
1240
1241 static void
1242 mapping_delete_timer (lisp_cp_main_t * lcm, u32 mi)
1243 {
1244   timing_wheel_delete (&lcm->wheel, mi);
1245 }
1246
1247 static int
1248 is_local_ip (lisp_cp_main_t * lcm, ip_address_t * addr)
1249 {
1250   fib_node_index_t fei;
1251   fib_prefix_t prefix;
1252   fib_entry_flag_t flags;
1253
1254   ip_address_to_fib_prefix (addr, &prefix);
1255
1256   fei = fib_table_lookup (0, &prefix);
1257   flags = fib_entry_get_flags (fei);
1258   return (FIB_ENTRY_FLAG_LOCAL & flags);
1259 }
1260
1261 /**
1262  * Adds/updates mapping. Does not program forwarding.
1263  *
1264  * @param a parameters of the new mapping
1265  * @param rlocs vector of remote locators
1266  * @param res_map_index index of the newly created mapping
1267  * @param locators_changed indicator if locators were updated in the mapping
1268  * @return return code
1269  */
1270 int
1271 vnet_lisp_add_mapping (vnet_lisp_add_del_mapping_args_t * a,
1272                        locator_t * rlocs,
1273                        u32 * res_map_index, u8 * is_updated)
1274 {
1275   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1276   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1277   u32 mi, ls_index = 0, dst_map_index;
1278   mapping_t *old_map;
1279   locator_t *loc;
1280
1281   if (vnet_lisp_enable_disable_status () == 0)
1282     {
1283       clib_warning ("LISP is disabled!");
1284       return VNET_API_ERROR_LISP_DISABLED;
1285     }
1286
1287   if (res_map_index)
1288     res_map_index[0] = ~0;
1289   if (is_updated)
1290     is_updated[0] = 0;
1291
1292   clib_memset (ls_args, 0, sizeof (ls_args[0]));
1293
1294   ls_args->locators = rlocs;
1295   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->eid);
1296   old_map = ((u32) ~ 0 != mi) ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
1297
1298   /* check if none of the locators match locally configured address */
1299   vec_foreach (loc, rlocs)
1300   {
1301     ip_prefix_t *p = &gid_address_ippref (&loc->address);
1302     if (is_local_ip (lcm, &ip_prefix_addr (p)))
1303       {
1304         clib_warning ("RLOC %U matches a local address!",
1305                       format_gid_address, &loc->address);
1306         return VNET_API_ERROR_LISP_RLOC_LOCAL;
1307       }
1308   }
1309
1310   /* overwrite: if mapping already exists, decide if locators should be
1311    * updated and be done */
1312   if (old_map && gid_address_cmp (&old_map->eid, &a->eid) == 0)
1313     {
1314       if (!a->is_static && (old_map->is_static || old_map->local))
1315         {
1316           /* do not overwrite local or static remote mappings */
1317           clib_warning ("mapping %U rejected due to collision with local "
1318                         "or static remote mapping!", format_gid_address,
1319                         &a->eid);
1320           return 0;
1321         }
1322
1323       locator_set_t *old_ls;
1324
1325       /* update mapping attributes */
1326       old_map->action = a->action;
1327       if (old_map->action != a->action && NULL != is_updated)
1328         is_updated[0] = 1;
1329
1330       old_map->authoritative = a->authoritative;
1331       old_map->ttl = a->ttl;
1332
1333       old_ls = pool_elt_at_index (lcm->locator_set_pool,
1334                                   old_map->locator_set_index);
1335       if (compare_locators (lcm, old_ls->locator_indices, ls_args->locators))
1336         {
1337           /* set locator-set index to overwrite */
1338           ls_args->is_add = 1;
1339           ls_args->index = old_map->locator_set_index;
1340           vnet_lisp_add_del_locator_set (ls_args, 0);
1341           if (is_updated)
1342             is_updated[0] = 1;
1343         }
1344       if (res_map_index)
1345         res_map_index[0] = mi;
1346     }
1347   /* new mapping */
1348   else
1349     {
1350       if (is_updated)
1351         is_updated[0] = 1;
1352       remove_overlapping_sub_prefixes (lcm, &a->eid, 0 == ls_args->locators);
1353
1354       ls_args->is_add = 1;
1355       ls_args->index = ~0;
1356
1357       vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1358
1359       /* add mapping */
1360       a->is_add = 1;
1361       a->locator_set_index = ls_index;
1362       vnet_lisp_map_cache_add_del (a, &dst_map_index);
1363
1364       if (res_map_index)
1365         res_map_index[0] = dst_map_index;
1366     }
1367
1368   /* success */
1369   return 0;
1370 }
1371
1372 /**
1373  * Removes a mapping. Does not program forwarding.
1374  *
1375  * @param eid end-host identifier
1376  * @param res_map_index index of the removed mapping
1377  * @return return code
1378  */
1379 int
1380 vnet_lisp_del_mapping (gid_address_t * eid, u32 * res_map_index)
1381 {
1382   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1383   vnet_lisp_add_del_mapping_args_t _m_args, *m_args = &_m_args;
1384   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1385   mapping_t *old_map;
1386   u32 mi;
1387
1388   clib_memset (ls_args, 0, sizeof (ls_args[0]));
1389   clib_memset (m_args, 0, sizeof (m_args[0]));
1390   if (res_map_index)
1391     res_map_index[0] = ~0;
1392
1393   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, eid);
1394   old_map = ((u32) ~ 0 != mi) ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
1395
1396   if (old_map == 0 || gid_address_cmp (&old_map->eid, eid) != 0)
1397     {
1398       clib_warning ("cannot delete mapping for eid %U",
1399                     format_gid_address, eid);
1400       return -1;
1401     }
1402
1403   m_args->is_add = 0;
1404   gid_address_copy (&m_args->eid, eid);
1405   m_args->locator_set_index = old_map->locator_set_index;
1406
1407   ls_args->is_add = 0;
1408   ls_args->index = old_map->locator_set_index;
1409
1410   /* delete timer associated to the mapping if any */
1411   if (old_map->timer_set)
1412     mapping_delete_timer (lcm, mi);
1413
1414   /* delete locator set */
1415   vnet_lisp_add_del_locator_set (ls_args, 0);
1416
1417   /* delete mapping associated from map-cache */
1418   vnet_lisp_map_cache_add_del (m_args, 0);
1419
1420   /* return old mapping index */
1421   if (res_map_index)
1422     res_map_index[0] = mi;
1423
1424   /* success */
1425   return 0;
1426 }
1427
1428 int
1429 vnet_lisp_clear_all_remote_adjacencies (void)
1430 {
1431   int rv = 0;
1432   u32 mi, *map_indices = 0, *map_indexp;
1433   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1434   vnet_lisp_add_del_mapping_args_t _dm_args, *dm_args = &_dm_args;
1435   vnet_lisp_add_del_locator_set_args_t _ls, *ls = &_ls;
1436
1437   /* *INDENT-OFF* */
1438   pool_foreach_index (mi, lcm->mapping_pool,
1439   ({
1440     vec_add1 (map_indices, mi);
1441   }));
1442   /* *INDENT-ON* */
1443
1444   vec_foreach (map_indexp, map_indices)
1445   {
1446     mapping_t *map = pool_elt_at_index (lcm->mapping_pool, map_indexp[0]);
1447     if (!map->local)
1448       {
1449         dp_del_fwd_entry (lcm, map_indexp[0]);
1450
1451         dm_args->is_add = 0;
1452         gid_address_copy (&dm_args->eid, &map->eid);
1453         dm_args->locator_set_index = map->locator_set_index;
1454
1455         /* delete mapping associated to fwd entry */
1456         vnet_lisp_map_cache_add_del (dm_args, 0);
1457
1458         ls->is_add = 0;
1459         ls->local = 0;
1460         ls->index = map->locator_set_index;
1461         /* delete locator set */
1462         rv = vnet_lisp_add_del_locator_set (ls, 0);
1463         if (rv != 0)
1464           goto cleanup;
1465       }
1466   }
1467
1468 cleanup:
1469   if (map_indices)
1470     vec_free (map_indices);
1471   return rv;
1472 }
1473
1474 /**
1475  * Adds adjacency or removes forwarding entry associated to remote mapping.
1476  * Note that adjacencies are not stored, they only result in forwarding entries
1477  * being created.
1478  */
1479 int
1480 vnet_lisp_add_del_adjacency (vnet_lisp_add_del_adjacency_args_t * a)
1481 {
1482   lisp_cp_main_t *lcm = &lisp_control_main;
1483   u32 local_mi, remote_mi = ~0;
1484
1485   if (vnet_lisp_enable_disable_status () == 0)
1486     {
1487       clib_warning ("LISP is disabled!");
1488       return VNET_API_ERROR_LISP_DISABLED;
1489     }
1490
1491   remote_mi = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid,
1492                                         &a->reid, &a->leid);
1493   if (GID_LOOKUP_MISS == remote_mi)
1494     {
1495       clib_warning ("Remote eid %U not found. Cannot add adjacency!",
1496                     format_gid_address, &a->reid);
1497
1498       return -1;
1499     }
1500
1501   if (a->is_add)
1502     {
1503       /* check if source eid has an associated mapping. If pitr mode is on,
1504        * just use the pitr's mapping */
1505       if (lcm->flags & LISP_FLAG_PITR_MODE)
1506         {
1507           if (lcm->pitr_map_index != ~0)
1508             {
1509               local_mi = lcm->pitr_map_index;
1510             }
1511           else
1512             {
1513               /* PITR mode is on, but no mapping is configured */
1514               return -1;
1515             }
1516         }
1517       else
1518         {
1519           if (gid_address_type (&a->reid) == GID_ADDR_NSH)
1520             {
1521               if (lcm->nsh_map_index == ~0)
1522                 local_mi = GID_LOOKUP_MISS;
1523               else
1524                 local_mi = lcm->nsh_map_index;
1525             }
1526           else
1527             {
1528               local_mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid,
1529                                                 &a->leid);
1530             }
1531         }
1532
1533       if (GID_LOOKUP_MISS == local_mi)
1534         {
1535           clib_warning ("Local eid %U not found. Cannot add adjacency!",
1536                         format_gid_address, &a->leid);
1537
1538           return -1;
1539         }
1540
1541       /* update forwarding */
1542       dp_add_fwd_entry (lcm, local_mi, remote_mi);
1543     }
1544   else
1545     dp_del_fwd_entry (lcm, remote_mi);
1546
1547   return 0;
1548 }
1549
1550 int
1551 vnet_lisp_set_map_request_mode (u8 mode)
1552 {
1553   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1554
1555   if (vnet_lisp_enable_disable_status () == 0)
1556     {
1557       clib_warning ("LISP is disabled!");
1558       return VNET_API_ERROR_LISP_DISABLED;
1559     }
1560
1561   if (mode >= _MR_MODE_MAX)
1562     {
1563       clib_warning ("Invalid LISP map request mode %d!", mode);
1564       return VNET_API_ERROR_INVALID_ARGUMENT;
1565     }
1566
1567   lcm->map_request_mode = mode;
1568   return 0;
1569 }
1570
1571 int
1572 vnet_lisp_nsh_set_locator_set (u8 * locator_set_name, u8 is_add)
1573 {
1574   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1575   lisp_gpe_main_t *lgm = vnet_lisp_gpe_get_main ();
1576   u32 locator_set_index = ~0;
1577   mapping_t *m;
1578   uword *p;
1579
1580   if (vnet_lisp_enable_disable_status () == 0)
1581     {
1582       clib_warning ("LISP is disabled!");
1583       return VNET_API_ERROR_LISP_DISABLED;
1584     }
1585
1586   if (is_add)
1587     {
1588       if (lcm->nsh_map_index == (u32) ~ 0)
1589         {
1590           p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
1591           if (!p)
1592             {
1593               clib_warning ("locator-set %v doesn't exist", locator_set_name);
1594               return -1;
1595             }
1596           locator_set_index = p[0];
1597
1598           pool_get (lcm->mapping_pool, m);
1599           clib_memset (m, 0, sizeof *m);
1600           m->locator_set_index = locator_set_index;
1601           m->local = 1;
1602           m->nsh_set = 1;
1603           lcm->nsh_map_index = m - lcm->mapping_pool;
1604
1605           if (~0 == vnet_lisp_gpe_add_nsh_iface (lgm))
1606             return -1;
1607         }
1608     }
1609   else
1610     {
1611       if (lcm->nsh_map_index != (u32) ~ 0)
1612         {
1613           /* remove NSH mapping */
1614           pool_put_index (lcm->mapping_pool, lcm->nsh_map_index);
1615           lcm->nsh_map_index = ~0;
1616           vnet_lisp_gpe_del_nsh_iface (lgm);
1617         }
1618     }
1619   return 0;
1620 }
1621
1622 int
1623 vnet_lisp_pitr_set_locator_set (u8 * locator_set_name, u8 is_add)
1624 {
1625   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1626   u32 locator_set_index = ~0;
1627   mapping_t *m;
1628   uword *p;
1629
1630   if (vnet_lisp_enable_disable_status () == 0)
1631     {
1632       clib_warning ("LISP is disabled!");
1633       return VNET_API_ERROR_LISP_DISABLED;
1634     }
1635
1636   p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
1637   if (!p)
1638     {
1639       clib_warning ("locator-set %v doesn't exist", locator_set_name);
1640       return -1;
1641     }
1642   locator_set_index = p[0];
1643
1644   if (is_add)
1645     {
1646       pool_get (lcm->mapping_pool, m);
1647       m->locator_set_index = locator_set_index;
1648       m->local = 1;
1649       m->pitr_set = 1;
1650       lcm->pitr_map_index = m - lcm->mapping_pool;
1651     }
1652   else
1653     {
1654       /* remove pitr mapping */
1655       pool_put_index (lcm->mapping_pool, lcm->pitr_map_index);
1656       lcm->pitr_map_index = ~0;
1657     }
1658   return 0;
1659 }
1660
1661 int
1662 vnet_lisp_map_register_fallback_threshold_set (u32 value)
1663 {
1664   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1665   if (0 == value)
1666     {
1667       return VNET_API_ERROR_INVALID_ARGUMENT;
1668     }
1669
1670   lcm->max_expired_map_registers = value;
1671   return 0;
1672 }
1673
1674 u32
1675 vnet_lisp_map_register_fallback_threshold_get (void)
1676 {
1677   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1678   return lcm->max_expired_map_registers;
1679 }
1680
1681 /**
1682  * Configure Proxy-ETR
1683  *
1684  * @param ip PETR's IP address
1685  * @param is_add Flag that indicates if this is an addition or removal
1686  *
1687  * return 0 on success
1688  */
1689 int
1690 vnet_lisp_use_petr (ip_address_t * ip, u8 is_add)
1691 {
1692   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1693   u32 ls_index = ~0;
1694   mapping_t *m;
1695   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1696   locator_t loc;
1697
1698   if (vnet_lisp_enable_disable_status () == 0)
1699     {
1700       clib_warning ("LISP is disabled!");
1701       return VNET_API_ERROR_LISP_DISABLED;
1702     }
1703
1704   clib_memset (ls_args, 0, sizeof (*ls_args));
1705
1706   if (is_add)
1707     {
1708       /* Create dummy petr locator-set */
1709       clib_memset (&loc, 0, sizeof (loc));
1710       gid_address_from_ip (&loc.address, ip);
1711       loc.priority = 1;
1712       loc.state = loc.weight = 1;
1713       loc.local = 0;
1714
1715       ls_args->is_add = 1;
1716       ls_args->index = ~0;
1717       vec_add1 (ls_args->locators, loc);
1718       vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1719
1720       /* Add petr mapping */
1721       pool_get (lcm->mapping_pool, m);
1722       m->locator_set_index = ls_index;
1723       lcm->petr_map_index = m - lcm->mapping_pool;
1724
1725       /* Enable use-petr */
1726       lcm->flags |= LISP_FLAG_USE_PETR;
1727     }
1728   else
1729     {
1730       m = pool_elt_at_index (lcm->mapping_pool, lcm->petr_map_index);
1731
1732       /* Remove petr locator */
1733       ls_args->is_add = 0;
1734       ls_args->index = m->locator_set_index;
1735       vnet_lisp_add_del_locator_set (ls_args, 0);
1736
1737       /* Remove petr mapping */
1738       pool_put_index (lcm->mapping_pool, lcm->petr_map_index);
1739
1740       /* Disable use-petr */
1741       lcm->flags &= ~LISP_FLAG_USE_PETR;
1742       lcm->petr_map_index = ~0;
1743     }
1744   return 0;
1745 }
1746
1747 /* cleans locator to locator-set data and removes locators not part of
1748  * any locator-set */
1749 static void
1750 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
1751 {
1752   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes, *to_be_deleted = 0;
1753   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool, lsi);
1754   for (i = 0; i < vec_len (ls->locator_indices); i++)
1755     {
1756       loc_indexp = vec_elt_at_index (ls->locator_indices, i);
1757       ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1758                                      loc_indexp[0]);
1759       for (j = 0; j < vec_len (ls_indexes[0]); j++)
1760         {
1761           ls_indexp = vec_elt_at_index (ls_indexes[0], j);
1762           if (ls_indexp[0] == lsi)
1763             break;
1764         }
1765
1766       /* delete index for removed locator-set */
1767       vec_del1 (ls_indexes[0], j);
1768
1769       /* delete locator if it's part of no locator-set */
1770       if (vec_len (ls_indexes[0]) == 0)
1771         {
1772           pool_put_index (lcm->locator_pool, loc_indexp[0]);
1773           vec_add1 (to_be_deleted, i);
1774         }
1775     }
1776
1777   if (to_be_deleted)
1778     {
1779       for (i = 0; i < vec_len (to_be_deleted); i++)
1780         {
1781           loc_indexp = vec_elt_at_index (to_be_deleted, i);
1782           vec_del1 (ls->locator_indices, loc_indexp[0]);
1783         }
1784       vec_free (to_be_deleted);
1785     }
1786 }
1787
1788 static inline uword *
1789 get_locator_set_index (vnet_lisp_add_del_locator_set_args_t * a, uword * p)
1790 {
1791   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1792
1793   ASSERT (a != NULL);
1794   ASSERT (p != NULL);
1795
1796   /* find locator-set */
1797   if (a->local)
1798     {
1799       ASSERT (a->name);
1800       p = hash_get_mem (lcm->locator_set_index_by_name, a->name);
1801     }
1802   else
1803     {
1804       *p = a->index;
1805     }
1806
1807   return p;
1808 }
1809
1810 static inline int
1811 is_locator_in_locator_set (lisp_cp_main_t * lcm, locator_set_t * ls,
1812                            locator_t * loc)
1813 {
1814   locator_t *itloc;
1815   u32 *locit;
1816
1817   ASSERT (ls != NULL);
1818   ASSERT (loc != NULL);
1819
1820   vec_foreach (locit, ls->locator_indices)
1821   {
1822     itloc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1823     if ((ls->local && itloc->sw_if_index == loc->sw_if_index) ||
1824         (!ls->local && !gid_address_cmp (&itloc->address, &loc->address)))
1825       {
1826         clib_warning ("Duplicate locator");
1827         return VNET_API_ERROR_VALUE_EXIST;
1828       }
1829   }
1830
1831   return 0;
1832 }
1833
1834 static void
1835 update_adjacencies_by_map_index (lisp_cp_main_t * lcm,
1836                                  u32 mapping_index, u8 remove_only)
1837 {
1838   fwd_entry_t *fwd;
1839   mapping_t *map;
1840   uword *fei = 0, *rmts_idxp = 0;
1841   u32 **rmts = 0, *remote_idxp = 0, *rmts_copy = 0;
1842   vnet_lisp_add_del_adjacency_args_t _a, *a = &_a;
1843   clib_memset (a, 0, sizeof (*a));
1844
1845   map = pool_elt_at_index (lcm->mapping_pool, mapping_index);
1846
1847   if (map->local)
1848     {
1849       rmts_idxp = hash_get (lcm->lcl_to_rmt_adjs_by_lcl_idx, mapping_index);
1850       if (rmts_idxp)
1851         {
1852           rmts =
1853             pool_elt_at_index (lcm->lcl_to_rmt_adjacencies, rmts_idxp[0]);
1854           rmts_copy = vec_dup (rmts[0]);
1855
1856           vec_foreach (remote_idxp, rmts_copy)
1857           {
1858             fei = hash_get (lcm->fwd_entry_by_mapping_index, remote_idxp[0]);
1859             if (!fei)
1860               continue;
1861
1862             fwd = pool_elt_at_index (lcm->fwd_entry_pool, fei[0]);
1863             a->is_add = 0;
1864             gid_address_copy (&a->leid, &fwd->leid);
1865             gid_address_copy (&a->reid, &fwd->reid);
1866             vnet_lisp_add_del_adjacency (a);
1867
1868             if (!remove_only)
1869               {
1870                 a->is_add = 1;
1871                 vnet_lisp_add_del_adjacency (a);
1872               }
1873           }
1874           vec_free (rmts_copy);
1875         }
1876     }
1877   else
1878     {
1879       fei = hash_get (lcm->fwd_entry_by_mapping_index, mapping_index);
1880       if (!fei)
1881         return;
1882
1883       fwd = pool_elt_at_index (lcm->fwd_entry_pool, fei[0]);
1884       a->is_add = 0;
1885       gid_address_copy (&a->leid, &fwd->leid);
1886       gid_address_copy (&a->reid, &fwd->reid);
1887       vnet_lisp_add_del_adjacency (a);
1888
1889       if (!remove_only)
1890         {
1891           a->is_add = 1;
1892           vnet_lisp_add_del_adjacency (a);
1893         }
1894     }
1895 }
1896
1897 static void
1898 update_fwd_entries_by_locator_set (lisp_cp_main_t * lcm,
1899                                    u32 ls_index, u8 remove_only)
1900 {
1901   u32 i, *map_indexp;
1902   u32 **eid_indexes;
1903
1904   if (vec_len (lcm->locator_set_to_eids) <= ls_index)
1905     return;
1906
1907   eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids, ls_index);
1908
1909   for (i = 0; i < vec_len (eid_indexes[0]); i++)
1910     {
1911       map_indexp = vec_elt_at_index (eid_indexes[0], i);
1912       update_adjacencies_by_map_index (lcm, map_indexp[0], remove_only);
1913     }
1914 }
1915
1916 static inline void
1917 remove_locator_from_locator_set (locator_set_t * ls, u32 * locit,
1918                                  u32 ls_index, u32 loc_id)
1919 {
1920   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1921   u32 **ls_indexes = NULL;
1922
1923   ASSERT (ls != NULL);
1924   ASSERT (locit != NULL);
1925
1926   ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets, locit[0]);
1927   pool_put_index (lcm->locator_pool, locit[0]);
1928   vec_del1 (ls->locator_indices, loc_id);
1929   vec_del1 (ls_indexes[0], ls_index);
1930 }
1931
1932 int
1933 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t * a,
1934                            locator_set_t * ls, u32 * ls_result)
1935 {
1936   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1937   locator_t *loc = NULL, *itloc = NULL;
1938   uword _p = (u32) ~ 0, *p = &_p;
1939   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
1940   u32 loc_id = ~0;
1941   int ret = 0;
1942
1943   ASSERT (a != NULL);
1944
1945   if (vnet_lisp_enable_disable_status () == 0)
1946     {
1947       clib_warning ("LISP is disabled!");
1948       return VNET_API_ERROR_LISP_DISABLED;
1949     }
1950
1951   p = get_locator_set_index (a, p);
1952   if (!p)
1953     {
1954       clib_warning ("locator-set %v doesn't exist", a->name);
1955       return VNET_API_ERROR_INVALID_ARGUMENT;
1956     }
1957
1958   if (ls == 0)
1959     {
1960       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1961       if (!ls)
1962         {
1963           clib_warning ("locator-set %d to be overwritten doesn't exist!",
1964                         p[0]);
1965           return VNET_API_ERROR_INVALID_ARGUMENT;
1966         }
1967     }
1968
1969   if (a->is_add)
1970     {
1971       if (ls_result)
1972         ls_result[0] = p[0];
1973
1974       /* allocate locators */
1975       vec_foreach (itloc, a->locators)
1976       {
1977         ret = is_locator_in_locator_set (lcm, ls, itloc);
1978         if (0 != ret)
1979           {
1980             return ret;
1981           }
1982
1983         pool_get (lcm->locator_pool, loc);
1984         loc[0] = itloc[0];
1985         loc_index = loc - lcm->locator_pool;
1986
1987         vec_add1 (ls->locator_indices, loc_index);
1988
1989         vec_validate (lcm->locator_to_locator_sets, loc_index);
1990         ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1991                                        loc_index);
1992         vec_add1 (ls_indexes[0], p[0]);
1993       }
1994     }
1995   else
1996     {
1997       ls_index = p[0];
1998       u8 removed;
1999
2000       vec_foreach (itloc, a->locators)
2001       {
2002         removed = 0;
2003         loc_id = 0;
2004         vec_foreach (locit, ls->locator_indices)
2005         {
2006           loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
2007
2008           if (loc->local && loc->sw_if_index == itloc->sw_if_index)
2009             {
2010               removed = 1;
2011               remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
2012             }
2013           else if (0 == loc->local &&
2014                    !gid_address_cmp (&loc->address, &itloc->address))
2015             {
2016               removed = 1;
2017               remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
2018             }
2019
2020           if (removed)
2021             {
2022               /* update fwd entries using this locator in DP */
2023               update_fwd_entries_by_locator_set (lcm, ls_index,
2024                                                  vec_len (ls->locator_indices)
2025                                                  == 0);
2026             }
2027
2028           loc_id++;
2029         }
2030       }
2031     }
2032
2033   return 0;
2034 }
2035
2036 int
2037 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
2038                                u32 * ls_result)
2039 {
2040   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2041   locator_set_t *ls;
2042   uword _p = (u32) ~ 0, *p = &_p;
2043   u32 ls_index;
2044   u32 **eid_indexes;
2045   int ret = 0;
2046
2047   if (vnet_lisp_enable_disable_status () == 0)
2048     {
2049       clib_warning ("LISP is disabled!");
2050       return VNET_API_ERROR_LISP_DISABLED;
2051     }
2052
2053   if (a->is_add)
2054     {
2055       p = get_locator_set_index (a, p);
2056
2057       /* overwrite */
2058       if (p && p[0] != (u32) ~ 0)
2059         {
2060           ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
2061           if (!ls)
2062             {
2063               clib_warning ("locator-set %d to be overwritten doesn't exist!",
2064                             p[0]);
2065               return -1;
2066             }
2067
2068           /* clean locator to locator-set vectors and remove locators if
2069            * they're not part of another locator-set */
2070           clean_locator_to_locator_set (lcm, p[0]);
2071
2072           /* remove locator indices from locator set */
2073           vec_free (ls->locator_indices);
2074
2075           ls_index = p[0];
2076
2077           if (ls_result)
2078             ls_result[0] = p[0];
2079         }
2080       /* new locator-set */
2081       else
2082         {
2083           pool_get (lcm->locator_set_pool, ls);
2084           clib_memset (ls, 0, sizeof (*ls));
2085           ls_index = ls - lcm->locator_set_pool;
2086
2087           if (a->local)
2088             {
2089               ls->name = vec_dup (a->name);
2090
2091               if (!lcm->locator_set_index_by_name)
2092                 lcm->locator_set_index_by_name = hash_create_vec (
2093                                                                    /* size */
2094                                                                    0,
2095                                                                    sizeof
2096                                                                    (ls->name
2097                                                                     [0]),
2098                                                                    sizeof
2099                                                                    (uword));
2100               hash_set_mem (lcm->locator_set_index_by_name, ls->name,
2101                             ls_index);
2102
2103               /* mark as local locator-set */
2104               vec_add1 (lcm->local_locator_set_indexes, ls_index);
2105             }
2106           ls->local = a->local;
2107           if (ls_result)
2108             ls_result[0] = ls_index;
2109         }
2110
2111       ret = vnet_lisp_add_del_locator (a, ls, NULL);
2112       if (0 != ret)
2113         {
2114           return ret;
2115         }
2116     }
2117   else
2118     {
2119       p = get_locator_set_index (a, p);
2120       if (!p)
2121         {
2122           clib_warning ("locator-set %v doesn't exists", a->name);
2123           return -1;
2124         }
2125
2126       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
2127       if (!ls)
2128         {
2129           clib_warning ("locator-set with index %d doesn't exists", p[0]);
2130           return -1;
2131         }
2132
2133       if (lcm->mreq_itr_rlocs == p[0])
2134         {
2135           clib_warning ("Can't delete the locator-set used to constrain "
2136                         "the itr-rlocs in map-requests!");
2137           return -1;
2138         }
2139
2140       if (vec_len (lcm->locator_set_to_eids) != 0)
2141         {
2142           eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids, p[0]);
2143           if (vec_len (eid_indexes[0]) != 0)
2144             {
2145               clib_warning
2146                 ("Can't delete a locator that supports a mapping!");
2147               return -1;
2148             }
2149         }
2150
2151       /* clean locator to locator-sets data */
2152       clean_locator_to_locator_set (lcm, p[0]);
2153
2154       if (ls->local)
2155         {
2156           u32 it, lsi;
2157
2158           vec_foreach_index (it, lcm->local_locator_set_indexes)
2159           {
2160             lsi = vec_elt (lcm->local_locator_set_indexes, it);
2161             if (lsi == p[0])
2162               {
2163                 vec_del1 (lcm->local_locator_set_indexes, it);
2164                 break;
2165               }
2166           }
2167           hash_unset_mem (lcm->locator_set_index_by_name, ls->name);
2168         }
2169       vec_free (ls->name);
2170       vec_free (ls->locator_indices);
2171       pool_put (lcm->locator_set_pool, ls);
2172     }
2173   return 0;
2174 }
2175
2176 int
2177 vnet_lisp_rloc_probe_enable_disable (u8 is_enable)
2178 {
2179   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2180
2181   lcm->rloc_probing = is_enable;
2182   return 0;
2183 }
2184
2185 int
2186 vnet_lisp_map_register_enable_disable (u8 is_enable)
2187 {
2188   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2189
2190   lcm->map_registering = is_enable;
2191   return 0;
2192 }
2193
2194 static void
2195 lisp_cp_register_dst_port (vlib_main_t * vm)
2196 {
2197   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
2198                          lisp_cp_input_node.index, 1 /* is_ip4 */ );
2199   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
2200                          lisp_cp_input_node.index, 0 /* is_ip4 */ );
2201 }
2202
2203 static void
2204 lisp_cp_unregister_dst_port (vlib_main_t * vm)
2205 {
2206   udp_unregister_dst_port (vm, UDP_DST_PORT_lisp_cp, 0 /* is_ip4 */ );
2207   udp_unregister_dst_port (vm, UDP_DST_PORT_lisp_cp6, 1 /* is_ip4 */ );
2208 }
2209
2210 /**
2211  * lisp_cp_enable_l2_l3_ifaces
2212  *
2213  * Enable all l2 and l3 ifaces
2214  */
2215 static void
2216 lisp_cp_enable_l2_l3_ifaces (lisp_cp_main_t * lcm, u8 with_default_route)
2217 {
2218   u32 vni, dp_table;
2219
2220   /* *INDENT-OFF* */
2221   hash_foreach(vni, dp_table, lcm->table_id_by_vni, ({
2222     dp_add_del_iface(lcm, vni, /* is_l2 */ 0, /* is_add */1,
2223                      with_default_route);
2224   }));
2225   hash_foreach(vni, dp_table, lcm->bd_id_by_vni, ({
2226     dp_add_del_iface(lcm, vni, /* is_l2 */ 1, 1,
2227                      with_default_route);
2228   }));
2229   /* *INDENT-ON* */
2230 }
2231
2232 static void
2233 lisp_cp_disable_l2_l3_ifaces (lisp_cp_main_t * lcm)
2234 {
2235   u32 **rmts;
2236
2237   /* clear interface table */
2238   hash_free (lcm->fwd_entry_by_mapping_index);
2239   pool_free (lcm->fwd_entry_pool);
2240   /* Clear state tracking rmt-lcl fwd entries */
2241   /* *INDENT-OFF* */
2242   pool_foreach(rmts, lcm->lcl_to_rmt_adjacencies,
2243   {
2244     vec_free(rmts[0]);
2245   });
2246   /* *INDENT-ON* */
2247   hash_free (lcm->lcl_to_rmt_adjs_by_lcl_idx);
2248   pool_free (lcm->lcl_to_rmt_adjacencies);
2249 }
2250
2251 clib_error_t *
2252 vnet_lisp_enable_disable (u8 is_enable)
2253 {
2254   clib_error_t *error = 0;
2255   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2256   vnet_lisp_gpe_enable_disable_args_t _a, *a = &_a;
2257
2258   a->is_en = is_enable;
2259   error = vnet_lisp_gpe_enable_disable (a);
2260   if (error)
2261     {
2262       return clib_error_return (0, "failed to %s data-plane!",
2263                                 a->is_en ? "enable" : "disable");
2264     }
2265
2266   /* decide what to do based on mode */
2267
2268   if (lcm->flags & LISP_FLAG_XTR_MODE)
2269     {
2270       if (is_enable)
2271         {
2272           lisp_cp_register_dst_port (lcm->vlib_main);
2273           lisp_cp_enable_l2_l3_ifaces (lcm, 1 /* with_default_route */ );
2274         }
2275       else
2276         {
2277           lisp_cp_unregister_dst_port (lcm->vlib_main);
2278           lisp_cp_disable_l2_l3_ifaces (lcm);
2279         }
2280     }
2281
2282   if (lcm->flags & LISP_FLAG_PETR_MODE)
2283     {
2284       /* if in xTR mode, the LISP ports were already (un)registered above */
2285       if (!(lcm->flags & LISP_FLAG_XTR_MODE))
2286         {
2287           if (is_enable)
2288             lisp_cp_register_dst_port (lcm->vlib_main);
2289           else
2290             lisp_cp_unregister_dst_port (lcm->vlib_main);
2291         }
2292     }
2293
2294   if (lcm->flags & LISP_FLAG_PITR_MODE)
2295     {
2296       if (is_enable)
2297         {
2298           /* install interfaces, but no default routes */
2299           lisp_cp_enable_l2_l3_ifaces (lcm, 0 /* with_default_route */ );
2300         }
2301       else
2302         {
2303           lisp_cp_disable_l2_l3_ifaces (lcm);
2304         }
2305     }
2306
2307   if (is_enable)
2308     vnet_lisp_create_retry_process (lcm);
2309
2310   /* update global flag */
2311   lcm->is_enabled = is_enable;
2312
2313   return 0;
2314 }
2315
2316 u8
2317 vnet_lisp_enable_disable_status (void)
2318 {
2319   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2320   return lcm->is_enabled;
2321 }
2322
2323 int
2324 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
2325 {
2326   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2327   u32 i;
2328   lisp_msmr_t _mr, *mr = &_mr;
2329
2330   if (vnet_lisp_enable_disable_status () == 0)
2331     {
2332       clib_warning ("LISP is disabled!");
2333       return VNET_API_ERROR_LISP_DISABLED;
2334     }
2335
2336   if (a->is_add)
2337     {
2338
2339       if (get_map_resolver (&a->address))
2340         {
2341           clib_warning ("map-resolver %U already exists!", format_ip_address,
2342                         &a->address);
2343           return -1;
2344         }
2345
2346       clib_memset (mr, 0, sizeof (*mr));
2347       ip_address_copy (&mr->address, &a->address);
2348       vec_add1 (lcm->map_resolvers, *mr);
2349
2350       if (vec_len (lcm->map_resolvers) == 1)
2351         lcm->do_map_resolver_election = 1;
2352     }
2353   else
2354     {
2355       for (i = 0; i < vec_len (lcm->map_resolvers); i++)
2356         {
2357           mr = vec_elt_at_index (lcm->map_resolvers, i);
2358           if (!ip_address_cmp (&mr->address, &a->address))
2359             {
2360               if (!ip_address_cmp (&mr->address, &lcm->active_map_resolver))
2361                 lcm->do_map_resolver_election = 1;
2362
2363               vec_del1 (lcm->map_resolvers, i);
2364               break;
2365             }
2366         }
2367     }
2368   return 0;
2369 }
2370
2371 int
2372 vnet_lisp_map_register_set_ttl (u32 ttl)
2373 {
2374   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2375   lcm->map_register_ttl = ttl;
2376   return 0;
2377 }
2378
2379 u32
2380 vnet_lisp_map_register_get_ttl (void)
2381 {
2382   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2383   return lcm->map_register_ttl;
2384 }
2385
2386 int
2387 vnet_lisp_add_del_mreq_itr_rlocs (vnet_lisp_add_del_mreq_itr_rloc_args_t * a)
2388 {
2389   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2390   uword *p = 0;
2391
2392   if (vnet_lisp_enable_disable_status () == 0)
2393     {
2394       clib_warning ("LISP is disabled!");
2395       return VNET_API_ERROR_LISP_DISABLED;
2396     }
2397
2398   if (a->is_add)
2399     {
2400       p = hash_get_mem (lcm->locator_set_index_by_name, a->locator_set_name);
2401       if (!p)
2402         {
2403           clib_warning ("locator-set %v doesn't exist", a->locator_set_name);
2404           return VNET_API_ERROR_INVALID_ARGUMENT;
2405         }
2406
2407       lcm->mreq_itr_rlocs = p[0];
2408     }
2409   else
2410     {
2411       lcm->mreq_itr_rlocs = ~0;
2412     }
2413
2414   return 0;
2415 }
2416
2417 /* Statistics (not really errors) */
2418 #define foreach_lisp_cp_lookup_error           \
2419 _(DROP, "drop")                                \
2420 _(MAP_REQUESTS_SENT, "map-request sent")       \
2421 _(ARP_REPLY_TX, "ARP replies sent")            \
2422 _(NDP_NEIGHBOR_ADVERTISEMENT_TX,               \
2423   "neighbor advertisement sent")
2424
2425 static char *lisp_cp_lookup_error_strings[] = {
2426 #define _(sym,string) string,
2427   foreach_lisp_cp_lookup_error
2428 #undef _
2429 };
2430
2431 typedef enum
2432 {
2433 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
2434   foreach_lisp_cp_lookup_error
2435 #undef _
2436     LISP_CP_LOOKUP_N_ERROR,
2437 } lisp_cp_lookup_error_t;
2438
2439 typedef enum
2440 {
2441   LISP_CP_LOOKUP_NEXT_DROP,
2442   LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX,
2443   LISP_CP_LOOKUP_N_NEXT,
2444 } lisp_cp_lookup_next_t;
2445
2446 typedef struct
2447 {
2448   gid_address_t dst_eid;
2449   ip_address_t map_resolver_ip;
2450 } lisp_cp_lookup_trace_t;
2451
2452 u8 *
2453 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
2454 {
2455   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
2456   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
2457   lisp_cp_lookup_trace_t *t = va_arg (*args, lisp_cp_lookup_trace_t *);
2458
2459   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
2460               format_ip_address, &t->map_resolver_ip, format_gid_address,
2461               &t->dst_eid);
2462   return s;
2463 }
2464
2465 int
2466 get_mr_and_local_iface_ip (lisp_cp_main_t * lcm, ip_address_t * mr_ip,
2467                            ip_address_t * sloc)
2468 {
2469   lisp_msmr_t *mrit;
2470   ip_address_t *a;
2471
2472   if (vec_len (lcm->map_resolvers) == 0)
2473     {
2474       clib_warning ("No map-resolver configured");
2475       return 0;
2476     }
2477
2478   /* find the first mr ip we have a route to and the ip of the
2479    * iface that has a route to it */
2480   vec_foreach (mrit, lcm->map_resolvers)
2481   {
2482     a = &mrit->address;
2483     if (0 != ip_fib_get_first_egress_ip_for_dst (lcm, a, sloc))
2484       {
2485         ip_address_copy (mr_ip, a);
2486
2487         /* also update globals */
2488         return 1;
2489       }
2490   }
2491
2492   clib_warning ("Can't find map-resolver and local interface ip!");
2493   return 0;
2494 }
2495
2496 static gid_address_t *
2497 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
2498 {
2499   void *addr;
2500   u32 i;
2501   locator_t *loc;
2502   u32 *loc_indexp;
2503   ip_interface_address_t *ia = 0;
2504   gid_address_t gid_data, *gid = &gid_data;
2505   gid_address_t *rlocs = 0;
2506   ip_prefix_t *ippref = &gid_address_ippref (gid);
2507   ip_address_t *rloc = &ip_prefix_addr (ippref);
2508
2509   clib_memset (gid, 0, sizeof (gid[0]));
2510   gid_address_type (gid) = GID_ADDR_IP_PREFIX;
2511   for (i = 0; i < vec_len (loc_set->locator_indices); i++)
2512     {
2513       loc_indexp = vec_elt_at_index (loc_set->locator_indices, i);
2514       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
2515
2516       /* Add ipv4 locators first TODO sort them */
2517
2518       /* *INDENT-OFF* */
2519       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
2520                                     loc->sw_if_index, 1 /* unnumbered */,
2521       ({
2522         addr = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
2523         ip_address_set (rloc, addr, AF_IP4);
2524         ip_prefix_len (ippref) = 32;
2525         ip_prefix_normalize (ippref);
2526         vec_add1 (rlocs, gid[0]);
2527       }));
2528
2529       /* Add ipv6 locators */
2530       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
2531                                     loc->sw_if_index, 1 /* unnumbered */,
2532       ({
2533         addr = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
2534         ip_address_set (rloc, addr, AF_IP6);
2535         ip_prefix_len (ippref) = 128;
2536         ip_prefix_normalize (ippref);
2537         vec_add1 (rlocs, gid[0]);
2538       }));
2539       /* *INDENT-ON* */
2540
2541     }
2542   return rlocs;
2543 }
2544
2545 static vlib_buffer_t *
2546 build_map_request (lisp_cp_main_t * lcm, gid_address_t * deid,
2547                    ip_address_t * sloc, ip_address_t * rloc,
2548                    gid_address_t * itr_rlocs, u64 * nonce_res, u32 * bi_res)
2549 {
2550   vlib_buffer_t *b;
2551   u32 bi;
2552   vlib_main_t *vm = lcm->vlib_main;
2553
2554   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2555     {
2556       clib_warning ("Can't allocate buffer for Map-Request!");
2557       return 0;
2558     }
2559
2560   b = vlib_get_buffer (vm, bi);
2561
2562   /* leave some space for the encap headers */
2563   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2564
2565   /* put lisp msg */
2566   lisp_msg_put_mreq (lcm, b, NULL, deid, itr_rlocs, 0 /* smr invoked */ ,
2567                      1 /* rloc probe */ , nonce_res);
2568
2569   /* push outer ip header */
2570   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2571                        rloc, 1);
2572
2573   bi_res[0] = bi;
2574
2575   return b;
2576 }
2577
2578 static vlib_buffer_t *
2579 build_encapsulated_map_request (lisp_cp_main_t * lcm,
2580                                 gid_address_t * seid, gid_address_t * deid,
2581                                 locator_set_t * loc_set, ip_address_t * mr_ip,
2582                                 ip_address_t * sloc, u8 is_smr_invoked,
2583                                 u64 * nonce_res, u32 * bi_res)
2584 {
2585   vlib_buffer_t *b;
2586   u32 bi;
2587   gid_address_t *rlocs = 0;
2588   vlib_main_t *vm = lcm->vlib_main;
2589
2590   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2591     {
2592       clib_warning ("Can't allocate buffer for Map-Request!");
2593       return 0;
2594     }
2595
2596   b = vlib_get_buffer (vm, bi);
2597   b->flags = 0;
2598
2599   /* leave some space for the encap headers */
2600   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2601
2602   /* get rlocs */
2603   rlocs = build_itr_rloc_list (lcm, loc_set);
2604
2605   if (MR_MODE_SRC_DST == lcm->map_request_mode
2606       && GID_ADDR_SRC_DST != gid_address_type (deid))
2607     {
2608       gid_address_t sd;
2609       clib_memset (&sd, 0, sizeof (sd));
2610       build_src_dst (&sd, seid, deid);
2611       lisp_msg_put_mreq (lcm, b, seid, &sd, rlocs, is_smr_invoked,
2612                          0 /* rloc probe */ , nonce_res);
2613     }
2614   else
2615     {
2616       /* put lisp msg */
2617       lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked,
2618                          0 /* rloc probe */ , nonce_res);
2619     }
2620
2621   /* push ecm: udp-ip-lisp */
2622   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
2623
2624   /* push outer ip header */
2625   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2626                        mr_ip, 1);
2627
2628   bi_res[0] = bi;
2629
2630   vec_free (rlocs);
2631   return b;
2632 }
2633
2634 static void
2635 reset_pending_mr_counters (pending_map_request_t * r)
2636 {
2637   r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
2638   r->retries_num = 0;
2639 }
2640
2641 #define foreach_msmr \
2642   _(server) \
2643   _(resolver)
2644
2645 #define _(name) \
2646 static int                                                              \
2647 elect_map_ ## name (lisp_cp_main_t * lcm)                               \
2648 {                                                                       \
2649   lisp_msmr_t *mr;                                                      \
2650   vec_foreach (mr, lcm->map_ ## name ## s)                              \
2651   {                                                                     \
2652     if (!mr->is_down)                                                   \
2653       {                                                                 \
2654         ip_address_copy (&lcm->active_map_ ##name, &mr->address);       \
2655         lcm->do_map_ ## name ## _election = 0;                          \
2656         return 1;                                                       \
2657       }                                                                 \
2658   }                                                                     \
2659   return 0;                                                             \
2660 }
2661 foreach_msmr
2662 #undef _
2663   static void
2664 free_map_register_records (mapping_t * maps)
2665 {
2666   mapping_t *map;
2667   vec_foreach (map, maps) vec_free (map->locators);
2668
2669   vec_free (maps);
2670 }
2671
2672 static void
2673 add_locators (lisp_cp_main_t * lcm, mapping_t * m, u32 locator_set_index,
2674               ip_address_t * probed_loc)
2675 {
2676   u32 *li;
2677   locator_t *loc, new;
2678   ip_interface_address_t *ia = 0;
2679   void *addr;
2680   ip_address_t *new_ip = &gid_address_ip (&new.address);
2681
2682   m->locators = 0;
2683   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool,
2684                                          locator_set_index);
2685   vec_foreach (li, ls->locator_indices)
2686   {
2687     loc = pool_elt_at_index (lcm->locator_pool, li[0]);
2688     new = loc[0];
2689     if (loc->local)
2690       {
2691           /* *INDENT-OFF* */
2692           foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
2693                                         loc->sw_if_index, 1 /* unnumbered */,
2694           ({
2695             addr = ip_interface_address_get_address (&lcm->im4->lookup_main,
2696                                                      ia);
2697             ip_address_set (new_ip, addr, AF_IP4);
2698           }));
2699
2700           /* Add ipv6 locators */
2701           foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
2702                                         loc->sw_if_index, 1 /* unnumbered */,
2703           ({
2704             addr = ip_interface_address_get_address (&lcm->im6->lookup_main,
2705                                                      ia);
2706             ip_address_set (new_ip, addr, AF_IP6);
2707           }));
2708           /* *INDENT-ON* */
2709
2710         if (probed_loc && ip_address_cmp (probed_loc, new_ip) == 0)
2711           new.probed = 1;
2712       }
2713     vec_add1 (m->locators, new);
2714   }
2715 }
2716
2717 static mapping_t *
2718 build_map_register_record_list (lisp_cp_main_t * lcm)
2719 {
2720   mapping_t *recs = 0, rec, *m;
2721
2722   /* *INDENT-OFF* */
2723   pool_foreach(m, lcm->mapping_pool,
2724   {
2725     /* for now build only local mappings */
2726     if (!m->local)
2727       continue;
2728
2729     rec = m[0];
2730     add_locators (lcm, &rec, m->locator_set_index, NULL);
2731     vec_add1 (recs, rec);
2732   });
2733   /* *INDENT-ON* */
2734
2735   return recs;
2736 }
2737
2738 static vnet_crypto_alg_t
2739 lisp_key_type_to_crypto_alg (lisp_key_type_t key_id)
2740 {
2741   switch (key_id)
2742     {
2743     case HMAC_SHA_1_96:
2744       return VNET_CRYPTO_ALG_HMAC_SHA1;
2745     case HMAC_SHA_256_128:
2746       return VNET_CRYPTO_ALG_HMAC_SHA256;
2747     default:
2748       clib_warning ("unsupported encryption key type: %d!", key_id);
2749       break;
2750     }
2751   return VNET_CRYPTO_ALG_NONE;
2752 }
2753
2754 static vnet_crypto_op_id_t
2755 lisp_key_type_to_crypto_op (lisp_key_type_t key_id)
2756 {
2757   switch (key_id)
2758     {
2759     case HMAC_SHA_1_96:
2760       return VNET_CRYPTO_OP_SHA1_HMAC;
2761     case HMAC_SHA_256_128:
2762       return VNET_CRYPTO_OP_SHA256_HMAC;
2763     default:
2764       clib_warning ("unsupported encryption key type: %d!", key_id);
2765       break;
2766     }
2767   return VNET_CRYPTO_OP_NONE;
2768 }
2769
2770 static int
2771 update_map_register_auth_data (map_register_hdr_t * map_reg_hdr,
2772                                lisp_key_type_t key_id, u8 * key,
2773                                u16 auth_data_len, u32 msg_len)
2774 {
2775   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2776   MREG_KEY_ID (map_reg_hdr) = clib_host_to_net_u16 (key_id);
2777   MREG_AUTH_DATA_LEN (map_reg_hdr) = clib_host_to_net_u16 (auth_data_len);
2778   vnet_crypto_op_t _op, *op = &_op;
2779   vnet_crypto_key_index_t ki;
2780
2781   vnet_crypto_op_init (op, lisp_key_type_to_crypto_op (key_id));
2782   op->len = msg_len;
2783   op->digest = MREG_DATA (map_reg_hdr);
2784   op->src = (u8 *) map_reg_hdr;
2785   op->digest_len = 0;
2786   op->iv = 0;
2787
2788   ki = vnet_crypto_key_add (lcm->vlib_main,
2789                             lisp_key_type_to_crypto_alg (key_id), key,
2790                             vec_len (key));
2791
2792   op->key_index = ki;
2793
2794   vnet_crypto_process_ops (lcm->vlib_main, op, 1);
2795   vnet_crypto_key_del (lcm->vlib_main, ki);
2796
2797   return 0;
2798 }
2799
2800 static vlib_buffer_t *
2801 build_map_register (lisp_cp_main_t * lcm, ip_address_t * sloc,
2802                     ip_address_t * ms_ip, u64 * nonce_res, u8 want_map_notif,
2803                     mapping_t * records, lisp_key_type_t key_id, u8 * key,
2804                     u32 * bi_res)
2805 {
2806   void *map_reg_hdr;
2807   vlib_buffer_t *b;
2808   u32 bi, auth_data_len = 0, msg_len = 0;
2809   vlib_main_t *vm = lcm->vlib_main;
2810
2811   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2812     {
2813       clib_warning ("Can't allocate buffer for Map-Register!");
2814       return 0;
2815     }
2816
2817   b = vlib_get_buffer (vm, bi);
2818
2819   /* leave some space for the encap headers */
2820   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2821
2822   auth_data_len = auth_data_len_by_key_id (key_id);
2823   map_reg_hdr = lisp_msg_put_map_register (b, records, want_map_notif,
2824                                            auth_data_len, nonce_res,
2825                                            &msg_len);
2826
2827   update_map_register_auth_data (map_reg_hdr, key_id, key, auth_data_len,
2828                                  msg_len);
2829
2830   /* push outer ip header */
2831   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2832                        ms_ip, 1);
2833
2834   bi_res[0] = bi;
2835   return b;
2836 }
2837
2838 #define _(name) \
2839 static int                                                              \
2840 get_egress_map_ ##name## _ip (lisp_cp_main_t * lcm, ip_address_t * ip)  \
2841 {                                                                       \
2842   lisp_msmr_t *mr;                                                      \
2843   while (lcm->do_map_ ## name ## _election                              \
2844          | (0 == ip_fib_get_first_egress_ip_for_dst                     \
2845             (lcm, &lcm->active_map_ ##name, ip)))                       \
2846     {                                                                   \
2847       if (0 == elect_map_ ## name (lcm))                                \
2848         /* all map resolvers/servers are down */                        \
2849         {                                                               \
2850           /* restart MR/MS checking by marking all of them up */        \
2851           vec_foreach (mr, lcm->map_ ## name ## s) mr->is_down = 0;     \
2852           return -1;                                                    \
2853         }                                                               \
2854     }                                                                   \
2855   return 0;                                                             \
2856 }
2857
2858 foreach_msmr
2859 #undef _
2860 /* CP output statistics */
2861 #define foreach_lisp_cp_output_error                  \
2862 _(MAP_REGISTERS_SENT, "map-registers sent")           \
2863 _(MAP_REQUESTS_SENT, "map-requests sent")             \
2864 _(RLOC_PROBES_SENT, "rloc-probes sent")
2865 static char *lisp_cp_output_error_strings[] = {
2866 #define _(sym,string) string,
2867   foreach_lisp_cp_output_error
2868 #undef _
2869 };
2870
2871 typedef enum
2872 {
2873 #define _(sym,str) LISP_CP_OUTPUT_ERROR_##sym,
2874   foreach_lisp_cp_output_error
2875 #undef _
2876     LISP_CP_OUTPUT_N_ERROR,
2877 } lisp_cp_output_error_t;
2878
2879 static uword
2880 lisp_cp_output (vlib_main_t * vm, vlib_node_runtime_t * node,
2881                 vlib_frame_t * from_frame)
2882 {
2883   return 0;
2884 }
2885
2886 /* dummy node used only for statistics */
2887 /* *INDENT-OFF* */
2888 VLIB_REGISTER_NODE (lisp_cp_output_node) = {
2889   .function = lisp_cp_output,
2890   .name = "lisp-cp-output",
2891   .vector_size = sizeof (u32),
2892   .format_trace = format_lisp_cp_input_trace,
2893   .type = VLIB_NODE_TYPE_INTERNAL,
2894
2895   .n_errors = LISP_CP_OUTPUT_N_ERROR,
2896   .error_strings = lisp_cp_output_error_strings,
2897
2898   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
2899
2900   .next_nodes = {
2901       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
2902   },
2903 };
2904 /* *INDENT-ON* */
2905
2906 static int
2907 send_rloc_probe (lisp_cp_main_t * lcm, gid_address_t * deid,
2908                  u32 local_locator_set_index, ip_address_t * sloc,
2909                  ip_address_t * rloc)
2910 {
2911   locator_set_t *ls;
2912   u32 bi;
2913   vlib_buffer_t *b;
2914   vlib_frame_t *f;
2915   u64 nonce = 0;
2916   u32 next_index, *to_next;
2917   gid_address_t *itr_rlocs;
2918
2919   ls = pool_elt_at_index (lcm->locator_set_pool, local_locator_set_index);
2920   itr_rlocs = build_itr_rloc_list (lcm, ls);
2921
2922   b = build_map_request (lcm, deid, sloc, rloc, itr_rlocs, &nonce, &bi);
2923   vec_free (itr_rlocs);
2924   if (!b)
2925     return -1;
2926
2927   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2928
2929   next_index = (ip_addr_version (rloc) == AF_IP4) ?
2930     ip4_lookup_node.index : ip6_lookup_node.index;
2931
2932   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2933
2934   /* Enqueue the packet */
2935   to_next = vlib_frame_vector_args (f);
2936   to_next[0] = bi;
2937   f->n_vectors = 1;
2938   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2939
2940   return 0;
2941 }
2942
2943 static int
2944 send_rloc_probes (lisp_cp_main_t * lcm)
2945 {
2946   u8 lprio = 0;
2947   mapping_t *lm;
2948   fwd_entry_t *e;
2949   locator_pair_t *lp;
2950   u32 si, rloc_probes_sent = 0;
2951
2952   /* *INDENT-OFF* */
2953   pool_foreach (e, lcm->fwd_entry_pool,
2954   {
2955     if (vec_len (e->locator_pairs) == 0)
2956       continue;
2957
2958     si = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &e->leid);
2959     if (~0 == si)
2960       {
2961         clib_warning ("internal error: cannot find local eid %U in "
2962                       "map-cache!", format_gid_address, &e->leid);
2963         continue;
2964       }
2965     lm = pool_elt_at_index (lcm->mapping_pool, si);
2966
2967     /* get the best (lowest) priority */
2968     lprio = e->locator_pairs[0].priority;
2969
2970     /* send rloc-probe for pair(s) with the best remote locator priority */
2971     vec_foreach (lp, e->locator_pairs)
2972       {
2973         if (lp->priority != lprio)
2974           break;
2975
2976         /* get first remote locator */
2977         send_rloc_probe (lcm, &e->reid, lm->locator_set_index, &lp->lcl_loc,
2978                          &lp->rmt_loc);
2979         rloc_probes_sent++;
2980       }
2981   });
2982   /* *INDENT-ON* */
2983
2984   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
2985                                LISP_CP_OUTPUT_ERROR_RLOC_PROBES_SENT,
2986                                rloc_probes_sent);
2987   return 0;
2988 }
2989
2990 static int
2991 send_map_register (lisp_cp_main_t * lcm, u8 want_map_notif)
2992 {
2993   pending_map_register_t *pmr;
2994   u32 bi, map_registers_sent = 0;
2995   vlib_buffer_t *b;
2996   ip_address_t sloc;
2997   vlib_frame_t *f;
2998   u64 nonce = 0;
2999   u32 next_index, *to_next;
3000   mapping_t *records, *r, *group, *k;
3001
3002   if (get_egress_map_server_ip (lcm, &sloc) < 0)
3003     return -1;
3004
3005   records = build_map_register_record_list (lcm);
3006   if (!records)
3007     return -1;
3008
3009   vec_foreach (r, records)
3010   {
3011     u8 *key = r->key;
3012     u8 key_id = r->key_id;
3013
3014     if (!key)
3015       continue;                 /* no secret key -> map-register cannot be sent */
3016
3017     group = 0;
3018     vec_add1 (group, r[0]);
3019
3020     /* group mappings that share common key */
3021     for (k = r + 1; k < vec_end (records); k++)
3022       {
3023         if (k->key_id != r->key_id)
3024           continue;
3025
3026         if (vec_is_equal (k->key, r->key))
3027           {
3028             vec_add1 (group, k[0]);
3029             k->key = 0;         /* don't process this mapping again */
3030           }
3031       }
3032
3033     b = build_map_register (lcm, &sloc, &lcm->active_map_server, &nonce,
3034                             want_map_notif, group, key_id, key, &bi);
3035     vec_free (group);
3036     if (!b)
3037       continue;
3038
3039     vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3040
3041     next_index = (ip_addr_version (&lcm->active_map_server) == AF_IP4) ?
3042       ip4_lookup_node.index : ip6_lookup_node.index;
3043
3044     f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3045
3046     /* Enqueue the packet */
3047     to_next = vlib_frame_vector_args (f);
3048     to_next[0] = bi;
3049     f->n_vectors = 1;
3050     vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3051     map_registers_sent++;
3052
3053     pool_get (lcm->pending_map_registers_pool, pmr);
3054     clib_memset (pmr, 0, sizeof (*pmr));
3055     pmr->time_to_expire = PENDING_MREG_EXPIRATION_TIME;
3056     hash_set (lcm->map_register_messages_by_nonce, nonce,
3057               pmr - lcm->pending_map_registers_pool);
3058   }
3059   free_map_register_records (records);
3060
3061   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
3062                                LISP_CP_OUTPUT_ERROR_MAP_REGISTERS_SENT,
3063                                map_registers_sent);
3064
3065   return 0;
3066 }
3067
3068 #define send_encapsulated_map_request(lcm, seid, deid, smr) \
3069   _send_encapsulated_map_request(lcm, seid, deid, smr, 0)
3070
3071 #define resend_encapsulated_map_request(lcm, seid, deid, smr) \
3072   _send_encapsulated_map_request(lcm, seid, deid, smr, 1)
3073
3074 static int
3075 _send_encapsulated_map_request (lisp_cp_main_t * lcm,
3076                                 gid_address_t * seid, gid_address_t * deid,
3077                                 u8 is_smr_invoked, u8 is_resend)
3078 {
3079   u32 next_index, bi = 0, *to_next, map_index;
3080   vlib_buffer_t *b;
3081   vlib_frame_t *f;
3082   u64 nonce = 0;
3083   locator_set_t *loc_set;
3084   mapping_t *map;
3085   pending_map_request_t *pmr, *duplicate_pmr = 0;
3086   ip_address_t sloc;
3087   u32 ls_index;
3088
3089   /* if there is already a pending request remember it */
3090
3091   /* *INDENT-OFF* */
3092   pool_foreach(pmr, lcm->pending_map_requests_pool,
3093   ({
3094     if (!gid_address_cmp (&pmr->src, seid)
3095         && !gid_address_cmp (&pmr->dst, deid))
3096       {
3097         duplicate_pmr = pmr;
3098         break;
3099       }
3100   }));
3101   /* *INDENT-ON* */
3102
3103   if (!is_resend && duplicate_pmr)
3104     {
3105       /* don't send the request if there is a pending map request already */
3106       return 0;
3107     }
3108
3109   u8 pitr_mode = lcm->flags & LISP_FLAG_PITR_MODE;
3110
3111   /* get locator-set for seid */
3112   if (!pitr_mode && gid_address_type (deid) != GID_ADDR_NSH)
3113     {
3114       map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
3115       if (map_index == ~0)
3116         {
3117           clib_warning ("No local mapping found in eid-table for %U!",
3118                         format_gid_address, seid);
3119           return -1;
3120         }
3121
3122       map = pool_elt_at_index (lcm->mapping_pool, map_index);
3123
3124       if (!map->local)
3125         {
3126           clib_warning
3127             ("Mapping found for src eid %U is not marked as local!",
3128              format_gid_address, seid);
3129           return -1;
3130         }
3131       ls_index = map->locator_set_index;
3132     }
3133   else
3134     {
3135       if (pitr_mode)
3136         {
3137           if (lcm->pitr_map_index != ~0)
3138             {
3139               map =
3140                 pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
3141               ls_index = map->locator_set_index;
3142             }
3143           else
3144             {
3145               return -1;
3146             }
3147         }
3148       else
3149         {
3150           if (lcm->nsh_map_index == (u32) ~ 0)
3151             {
3152               clib_warning ("No locator-set defined for NSH!");
3153               return -1;
3154             }
3155           else
3156             {
3157               map = pool_elt_at_index (lcm->mapping_pool, lcm->nsh_map_index);
3158               ls_index = map->locator_set_index;
3159             }
3160         }
3161     }
3162
3163   /* overwrite locator set if map-request itr-rlocs configured */
3164   if (~0 != lcm->mreq_itr_rlocs)
3165     {
3166       ls_index = lcm->mreq_itr_rlocs;
3167     }
3168
3169   loc_set = pool_elt_at_index (lcm->locator_set_pool, ls_index);
3170
3171   if (get_egress_map_resolver_ip (lcm, &sloc) < 0)
3172     {
3173       if (duplicate_pmr)
3174         duplicate_pmr->to_be_removed = 1;
3175       return -1;
3176     }
3177
3178   /* build the encapsulated map request */
3179   b = build_encapsulated_map_request (lcm, seid, deid, loc_set,
3180                                       &lcm->active_map_resolver,
3181                                       &sloc, is_smr_invoked, &nonce, &bi);
3182
3183   if (!b)
3184     return -1;
3185
3186   /* set fib index to default and lookup node */
3187   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3188   next_index = (ip_addr_version (&lcm->active_map_resolver) == AF_IP4) ?
3189     ip4_lookup_node.index : ip6_lookup_node.index;
3190
3191   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3192
3193   /* Enqueue the packet */
3194   to_next = vlib_frame_vector_args (f);
3195   to_next[0] = bi;
3196   f->n_vectors = 1;
3197   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3198
3199   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
3200                                LISP_CP_OUTPUT_ERROR_MAP_REQUESTS_SENT, 1);
3201
3202   if (duplicate_pmr)
3203     /* if there is a pending request already update it */
3204     {
3205       if (clib_fifo_elts (duplicate_pmr->nonces) >= PENDING_MREQ_QUEUE_LEN)
3206         {
3207           /* remove the oldest nonce */
3208           u64 CLIB_UNUSED (tmp), *nonce_del;
3209           nonce_del = clib_fifo_head (duplicate_pmr->nonces);
3210           hash_unset (lcm->pending_map_requests_by_nonce, nonce_del[0]);
3211           clib_fifo_sub1 (duplicate_pmr->nonces, tmp);
3212         }
3213
3214       clib_fifo_add1 (duplicate_pmr->nonces, nonce);
3215       hash_set (lcm->pending_map_requests_by_nonce, nonce,
3216                 duplicate_pmr - lcm->pending_map_requests_pool);
3217     }
3218   else
3219     {
3220       /* add map-request to pending requests table */
3221       pool_get (lcm->pending_map_requests_pool, pmr);
3222       clib_memset (pmr, 0, sizeof (*pmr));
3223       gid_address_copy (&pmr->src, seid);
3224       gid_address_copy (&pmr->dst, deid);
3225       clib_fifo_add1 (pmr->nonces, nonce);
3226       pmr->is_smr_invoked = is_smr_invoked;
3227       reset_pending_mr_counters (pmr);
3228       hash_set (lcm->pending_map_requests_by_nonce, nonce,
3229                 pmr - lcm->pending_map_requests_pool);
3230     }
3231
3232   return 0;
3233 }
3234
3235 static void
3236 get_src_and_dst_ip (void *hdr, ip_address_t * src, ip_address_t * dst)
3237 {
3238   ip4_header_t *ip4 = hdr;
3239   ip6_header_t *ip6;
3240
3241   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
3242     {
3243       ip_address_set (src, &ip4->src_address, AF_IP4);
3244       ip_address_set (dst, &ip4->dst_address, AF_IP4);
3245     }
3246   else
3247     {
3248       ip6 = hdr;
3249       ip_address_set (src, &ip6->src_address, AF_IP6);
3250       ip_address_set (dst, &ip6->dst_address, AF_IP6);
3251     }
3252 }
3253
3254 static u32
3255 lisp_get_vni_from_buffer_ip (lisp_cp_main_t * lcm, vlib_buffer_t * b,
3256                              u8 version)
3257 {
3258   uword *vnip;
3259   u32 vni = ~0, table_id = ~0;
3260
3261   table_id = fib_table_get_table_id_for_sw_if_index ((version ==
3262                                                       AF_IP4 ?
3263                                                       FIB_PROTOCOL_IP4 :
3264                                                       FIB_PROTOCOL_IP6),
3265                                                      vnet_buffer
3266                                                      (b)->sw_if_index
3267                                                      [VLIB_RX]);
3268
3269   vnip = hash_get (lcm->vni_by_table_id, table_id);
3270   if (vnip)
3271     vni = vnip[0];
3272   else
3273     clib_warning ("vrf %d is not mapped to any vni!", table_id);
3274
3275   return vni;
3276 }
3277
3278 always_inline u32
3279 lisp_get_bd_from_buffer_eth (vlib_buffer_t * b)
3280 {
3281   u32 sw_if_index0;
3282
3283   l2input_main_t *l2im = &l2input_main;
3284   l2_input_config_t *config;
3285   l2_bridge_domain_t *bd_config;
3286
3287   sw_if_index0 = vnet_buffer (b)->sw_if_index[VLIB_RX];
3288   config = vec_elt_at_index (l2im->configs, sw_if_index0);
3289   bd_config = vec_elt_at_index (l2im->bd_configs, config->bd_index);
3290
3291   return bd_config->bd_id;
3292 }
3293
3294 always_inline u32
3295 lisp_get_vni_from_buffer_eth (lisp_cp_main_t * lcm, vlib_buffer_t * b)
3296 {
3297   uword *vnip;
3298   u32 vni = ~0;
3299   u32 bd = lisp_get_bd_from_buffer_eth (b);
3300
3301   vnip = hash_get (lcm->vni_by_bd_id, bd);
3302   if (vnip)
3303     vni = vnip[0];
3304   else
3305     clib_warning ("bridge domain %d is not mapped to any vni!", bd);
3306
3307   return vni;
3308 }
3309
3310 void
3311 get_src_and_dst_eids_from_buffer (lisp_cp_main_t * lcm, vlib_buffer_t * b,
3312                                   gid_address_t * src, gid_address_t * dst,
3313                                   u16 type)
3314 {
3315   ethernet_header_t *eh;
3316   u32 vni = 0;
3317   icmp6_neighbor_discovery_ethernet_link_layer_address_option_t *opt;
3318
3319   clib_memset (src, 0, sizeof (*src));
3320   clib_memset (dst, 0, sizeof (*dst));
3321
3322   gid_address_type (dst) = GID_ADDR_NO_ADDRESS;
3323   gid_address_type (src) = GID_ADDR_NO_ADDRESS;
3324
3325   if (LISP_AFI_IP == type || LISP_AFI_IP6 == type)
3326     {
3327       ip4_header_t *ip;
3328       u8 version, preflen;
3329
3330       gid_address_type (src) = GID_ADDR_IP_PREFIX;
3331       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
3332
3333       ip = vlib_buffer_get_current (b);
3334       get_src_and_dst_ip (ip, &gid_address_ip (src), &gid_address_ip (dst));
3335
3336       version = gid_address_ip_version (src);
3337       preflen = ip_address_max_len (version);
3338       gid_address_ippref_len (src) = preflen;
3339       gid_address_ippref_len (dst) = preflen;
3340
3341       vni = lisp_get_vni_from_buffer_ip (lcm, b, version);
3342       gid_address_vni (dst) = vni;
3343       gid_address_vni (src) = vni;
3344     }
3345   else if (LISP_AFI_MAC == type)
3346     {
3347       ethernet_arp_header_t *ah;
3348
3349       eh = vlib_buffer_get_current (b);
3350
3351       if (clib_net_to_host_u16 (eh->type) == ETHERNET_TYPE_ARP)
3352         {
3353           ah = (ethernet_arp_header_t *) (((u8 *) eh) + sizeof (*eh));
3354           gid_address_type (dst) = GID_ADDR_ARP;
3355
3356           if (clib_net_to_host_u16 (ah->opcode)
3357               != ETHERNET_ARP_OPCODE_request)
3358             {
3359               clib_memset (&gid_address_arp_ndp_ip (dst), 0,
3360                            sizeof (ip_address_t));
3361               ip_addr_version (&gid_address_arp_ndp_ip (dst)) = AF_IP4;
3362               gid_address_arp_ndp_bd (dst) = ~0;
3363               return;
3364             }
3365
3366           gid_address_arp_bd (dst) = lisp_get_bd_from_buffer_eth (b);
3367           clib_memcpy (&gid_address_arp_ip4 (dst),
3368                        &ah->ip4_over_ethernet[1].ip4, 4);
3369         }
3370       else
3371         {
3372           if (clib_net_to_host_u16 (eh->type) == ETHERNET_TYPE_IP6)
3373             {
3374               ip6_header_t *ip;
3375               ip = (ip6_header_t *) (eh + 1);
3376
3377               if (IP_PROTOCOL_ICMP6 == ip->protocol)
3378                 {
3379                   icmp6_neighbor_solicitation_or_advertisement_header_t *ndh;
3380                   ndh = ip6_next_header (ip);
3381                   if (ndh->icmp.type == ICMP6_neighbor_solicitation)
3382                     {
3383                       gid_address_type (dst) = GID_ADDR_NDP;
3384
3385                       /* check that source link layer address option is present */
3386                       opt = (void *) (ndh + 1);
3387                       if ((opt->header.type !=
3388                            ICMP6_NEIGHBOR_DISCOVERY_OPTION_source_link_layer_address)
3389                           || (opt->header.n_data_u64s != 1))
3390                         {
3391                           clib_memset (&gid_address_arp_ndp_ip (dst), 0,
3392                                        sizeof (ip_address_t));
3393                           ip_addr_version (&gid_address_arp_ndp_ip (dst)) =
3394                             AF_IP6;
3395                           gid_address_arp_ndp_bd (dst) = ~0;
3396                           gid_address_type (src) = GID_ADDR_NO_ADDRESS;
3397                           return;
3398                         }
3399
3400                       gid_address_ndp_bd (dst) =
3401                         lisp_get_bd_from_buffer_eth (b);
3402                       ip_address_set (&gid_address_arp_ndp_ip (dst),
3403                                       &ndh->target_address, AF_IP6);
3404                       return;
3405                     }
3406                 }
3407             }
3408
3409           gid_address_type (src) = GID_ADDR_MAC;
3410           gid_address_type (dst) = GID_ADDR_MAC;
3411           mac_copy (&gid_address_mac (src), eh->src_address);
3412           mac_copy (&gid_address_mac (dst), eh->dst_address);
3413
3414           /* get vni */
3415           vni = lisp_get_vni_from_buffer_eth (lcm, b);
3416
3417           gid_address_vni (dst) = vni;
3418           gid_address_vni (src) = vni;
3419         }
3420     }
3421   else if (LISP_AFI_LCAF == type)
3422     {
3423       lisp_nsh_hdr_t *nh;
3424       eh = vlib_buffer_get_current (b);
3425
3426       if (clib_net_to_host_u16 (eh->type) == ETHERNET_TYPE_NSH)
3427         {
3428           nh = (lisp_nsh_hdr_t *) (((u8 *) eh) + sizeof (*eh));
3429           u32 spi = clib_net_to_host_u32 (nh->spi_si << 8);
3430           u8 si = (u8) clib_net_to_host_u32 (nh->spi_si);
3431           gid_address_nsh_spi (dst) = spi;
3432           gid_address_nsh_si (dst) = si;
3433
3434           gid_address_type (dst) = GID_ADDR_NSH;
3435           gid_address_type (src) = GID_ADDR_NSH;
3436         }
3437     }
3438 }
3439
3440 static uword
3441 lisp_cp_lookup_inline (vlib_main_t * vm,
3442                        vlib_node_runtime_t * node,
3443                        vlib_frame_t * from_frame, int overlay)
3444 {
3445   icmp6_neighbor_discovery_ethernet_link_layer_address_option_t *opt;
3446   u32 *from, *to_next, di, si;
3447   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3448   u32 next_index;
3449   uword n_left_from, n_left_to_next;
3450   vnet_main_t *vnm = vnet_get_main ();
3451
3452   from = vlib_frame_vector_args (from_frame);
3453   n_left_from = from_frame->n_vectors;
3454   next_index = node->cached_next_index;
3455
3456   while (n_left_from > 0)
3457     {
3458       vlib_get_next_frame (vm, node, next_index, to_next, n_left_to_next);
3459
3460       while (n_left_from > 0 && n_left_to_next > 0)
3461         {
3462           u32 pi0, sw_if_index0, next0;
3463           u64 mac0;
3464           vlib_buffer_t *b0;
3465           gid_address_t src, dst;
3466           ethernet_arp_header_t *arp0;
3467           ethernet_header_t *eth0;
3468           vnet_hw_interface_t *hw_if0;
3469           ethernet_header_t *eh0;
3470           icmp6_neighbor_solicitation_or_advertisement_header_t *ndh;
3471           ip6_header_t *ip0;
3472
3473           pi0 = from[0];
3474           from += 1;
3475           n_left_from -= 1;
3476           to_next[0] = pi0;
3477           to_next += 1;
3478           n_left_to_next -= 1;
3479
3480           b0 = vlib_get_buffer (vm, pi0);
3481
3482           /* src/dst eid pair */
3483           get_src_and_dst_eids_from_buffer (lcm, b0, &src, &dst, overlay);
3484
3485           if (gid_address_type (&dst) == GID_ADDR_ARP)
3486             {
3487               mac0 = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
3488               if (GID_LOOKUP_MISS_L2 == mac0)
3489                 goto drop;
3490
3491               /* send ARP reply */
3492               sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
3493               vnet_buffer (b0)->sw_if_index[VLIB_TX] = sw_if_index0;
3494
3495               hw_if0 = vnet_get_sup_hw_interface (vnm, sw_if_index0);
3496
3497               eth0 = vlib_buffer_get_current (b0);
3498               arp0 = (ethernet_arp_header_t *) (((u8 *) eth0)
3499                                                 + sizeof (*eth0));
3500               arp0->opcode = clib_host_to_net_u16 (ETHERNET_ARP_OPCODE_reply);
3501               arp0->ip4_over_ethernet[1] = arp0->ip4_over_ethernet[0];
3502               mac_address_from_u64 (&arp0->ip4_over_ethernet[0].mac, mac0);
3503               clib_memcpy (&arp0->ip4_over_ethernet[0].ip4,
3504                            &gid_address_arp_ip4 (&dst), 4);
3505
3506               /* Hardware must be ethernet-like. */
3507               ASSERT (vec_len (hw_if0->hw_address) == 6);
3508
3509               clib_memcpy (eth0->dst_address, eth0->src_address, 6);
3510               clib_memcpy (eth0->src_address, hw_if0->hw_address, 6);
3511
3512               b0->error = node->errors[LISP_CP_LOOKUP_ERROR_ARP_REPLY_TX];
3513               next0 = LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX;
3514               goto enqueue;
3515             }
3516           else if (gid_address_type (&dst) == GID_ADDR_NDP)
3517             {
3518               mac0 = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
3519               if (GID_LOOKUP_MISS_L2 == mac0)
3520                 goto drop;
3521
3522               sw_if_index0 = vnet_buffer (b0)->sw_if_index[VLIB_RX];
3523               vnet_buffer (b0)->sw_if_index[VLIB_TX] = sw_if_index0;
3524
3525               eh0 = vlib_buffer_get_current (b0);
3526               ip0 = (ip6_header_t *) (eh0 + 1);
3527               ndh = ip6_next_header (ip0);
3528               int bogus_length;
3529               ip0->dst_address = ip0->src_address;
3530               ip0->src_address = ndh->target_address;
3531               ip0->hop_limit = 255;
3532               opt = (void *) (ndh + 1);
3533               opt->header.type =
3534                 ICMP6_NEIGHBOR_DISCOVERY_OPTION_target_link_layer_address;
3535               clib_memcpy (opt->ethernet_address, (u8 *) & mac0, 6);
3536               ndh->icmp.type = ICMP6_neighbor_advertisement;
3537               ndh->advertisement_flags = clib_host_to_net_u32
3538                 (ICMP6_NEIGHBOR_ADVERTISEMENT_FLAG_SOLICITED |
3539                  ICMP6_NEIGHBOR_ADVERTISEMENT_FLAG_OVERRIDE);
3540               ndh->icmp.checksum = 0;
3541               ndh->icmp.checksum =
3542                 ip6_tcp_udp_icmp_compute_checksum (vm, b0, ip0,
3543                                                    &bogus_length);
3544               clib_memcpy (eh0->dst_address, eh0->src_address, 6);
3545               clib_memcpy (eh0->src_address, (u8 *) & mac0, 6);
3546               b0->error =
3547                 node->errors
3548                 [LISP_CP_LOOKUP_ERROR_NDP_NEIGHBOR_ADVERTISEMENT_TX];
3549               next0 = LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX;
3550               goto enqueue;
3551             }
3552
3553           /* if we have remote mapping for destination already in map-cache
3554              add forwarding tunnel directly. If not send a map-request */
3555           di = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid, &dst,
3556                                          &src);
3557           if (~0 != di)
3558             {
3559               mapping_t *m = vec_elt_at_index (lcm->mapping_pool, di);
3560               /* send a map-request also in case of negative mapping entry
3561                  with corresponding action */
3562               if (m->action == LISP_SEND_MAP_REQUEST)
3563                 {
3564                   /* send map-request */
3565                   queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
3566                                      0 /* is_resend */ );
3567                 }
3568               else
3569                 {
3570                   if (GID_ADDR_NSH != gid_address_type (&dst))
3571                     {
3572                       si = gid_dictionary_lookup (&lcm->mapping_index_by_gid,
3573                                                   &src);
3574                     }
3575                   else
3576                     si = lcm->nsh_map_index;
3577
3578                   if (~0 != si)
3579                     {
3580                       dp_add_fwd_entry_from_mt (si, di);
3581                     }
3582                 }
3583             }
3584           else
3585             {
3586               /* send map-request */
3587               queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
3588                                  0 /* is_resend */ );
3589             }
3590
3591         drop:
3592           b0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
3593           next0 = LISP_CP_LOOKUP_NEXT_DROP;
3594         enqueue:
3595           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
3596             {
3597               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, b0,
3598                                                            sizeof (*tr));
3599
3600               clib_memset (tr, 0, sizeof (*tr));
3601               gid_address_copy (&tr->dst_eid, &dst);
3602               ip_address_copy (&tr->map_resolver_ip,
3603                                &lcm->active_map_resolver);
3604             }
3605           gid_address_free (&dst);
3606           gid_address_free (&src);
3607           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
3608                                            to_next,
3609                                            n_left_to_next, pi0, next0);
3610         }
3611
3612       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
3613     }
3614   return from_frame->n_vectors;
3615 }
3616
3617 static uword
3618 lisp_cp_lookup_ip4 (vlib_main_t * vm,
3619                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3620 {
3621   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP));
3622 }
3623
3624 static uword
3625 lisp_cp_lookup_ip6 (vlib_main_t * vm,
3626                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3627 {
3628   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP6));
3629 }
3630
3631 static uword
3632 lisp_cp_lookup_l2 (vlib_main_t * vm,
3633                    vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3634 {
3635   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_MAC));
3636 }
3637
3638 static uword
3639 lisp_cp_lookup_nsh (vlib_main_t * vm,
3640                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
3641 {
3642   /* TODO decide if NSH should be propagated as LCAF or not */
3643   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_LCAF));
3644 }
3645
3646 /* *INDENT-OFF* */
3647 VLIB_REGISTER_NODE (lisp_cp_lookup_ip4_node) = {
3648   .function = lisp_cp_lookup_ip4,
3649   .name = "lisp-cp-lookup-ip4",
3650   .vector_size = sizeof (u32),
3651   .format_trace = format_lisp_cp_lookup_trace,
3652   .type = VLIB_NODE_TYPE_INTERNAL,
3653
3654   .n_errors = LISP_CP_LOOKUP_N_ERROR,
3655   .error_strings = lisp_cp_lookup_error_strings,
3656
3657   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
3658
3659   .next_nodes = {
3660       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
3661       [LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX] = "interface-output",
3662   },
3663 };
3664 /* *INDENT-ON* */
3665
3666 /* *INDENT-OFF* */
3667 VLIB_REGISTER_NODE (lisp_cp_lookup_ip6_node) = {
3668   .function = lisp_cp_lookup_ip6,
3669   .name = "lisp-cp-lookup-ip6",
3670   .vector_size = sizeof (u32),
3671   .format_trace = format_lisp_cp_lookup_trace,
3672   .type = VLIB_NODE_TYPE_INTERNAL,
3673
3674   .n_errors = LISP_CP_LOOKUP_N_ERROR,
3675   .error_strings = lisp_cp_lookup_error_strings,
3676
3677   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
3678
3679   .next_nodes = {
3680       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
3681       [LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX] = "interface-output",
3682   },
3683 };
3684 /* *INDENT-ON* */
3685
3686 /* *INDENT-OFF* */
3687 VLIB_REGISTER_NODE (lisp_cp_lookup_l2_node) = {
3688   .function = lisp_cp_lookup_l2,
3689   .name = "lisp-cp-lookup-l2",
3690   .vector_size = sizeof (u32),
3691   .format_trace = format_lisp_cp_lookup_trace,
3692   .type = VLIB_NODE_TYPE_INTERNAL,
3693
3694   .n_errors = LISP_CP_LOOKUP_N_ERROR,
3695   .error_strings = lisp_cp_lookup_error_strings,
3696
3697   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
3698
3699   .next_nodes = {
3700       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
3701       [LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX] = "interface-output",
3702   },
3703 };
3704 /* *INDENT-ON* */
3705
3706 /* *INDENT-OFF* */
3707 VLIB_REGISTER_NODE (lisp_cp_lookup_nsh_node) = {
3708   .function = lisp_cp_lookup_nsh,
3709   .name = "lisp-cp-lookup-nsh",
3710   .vector_size = sizeof (u32),
3711   .format_trace = format_lisp_cp_lookup_trace,
3712   .type = VLIB_NODE_TYPE_INTERNAL,
3713
3714   .n_errors = LISP_CP_LOOKUP_N_ERROR,
3715   .error_strings = lisp_cp_lookup_error_strings,
3716
3717   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
3718
3719   .next_nodes = {
3720       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
3721       [LISP_CP_LOOKUP_NEXT_ARP_NDP_REPLY_TX] = "interface-output",
3722   },
3723 };
3724 /* *INDENT-ON* */
3725
3726 /* lisp_cp_input statistics */
3727 #define foreach_lisp_cp_input_error                               \
3728 _(DROP, "drop")                                                   \
3729 _(RLOC_PROBE_REQ_RECEIVED, "rloc-probe requests received")        \
3730 _(RLOC_PROBE_REP_RECEIVED, "rloc-probe replies received")         \
3731 _(MAP_NOTIFIES_RECEIVED, "map-notifies received")                 \
3732 _(MAP_REPLIES_RECEIVED, "map-replies received")
3733
3734 static char *lisp_cp_input_error_strings[] = {
3735 #define _(sym,string) string,
3736   foreach_lisp_cp_input_error
3737 #undef _
3738 };
3739
3740 typedef enum
3741 {
3742 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
3743   foreach_lisp_cp_input_error
3744 #undef _
3745     LISP_CP_INPUT_N_ERROR,
3746 } lisp_cp_input_error_t;
3747
3748 typedef struct
3749 {
3750   gid_address_t dst_eid;
3751   ip4_address_t map_resolver_ip;
3752 } lisp_cp_input_trace_t;
3753
3754 u8 *
3755 format_lisp_cp_input_trace (u8 * s, va_list * args)
3756 {
3757   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
3758   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
3759   CLIB_UNUSED (lisp_cp_input_trace_t * t) =
3760     va_arg (*args, lisp_cp_input_trace_t *);
3761
3762   s = format (s, "LISP-CP-INPUT: TODO");
3763   return s;
3764 }
3765
3766 static void
3767 remove_expired_mapping (lisp_cp_main_t * lcm, u32 mi)
3768 {
3769   mapping_t *m;
3770   vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
3771   clib_memset (adj_args, 0, sizeof (adj_args[0]));
3772
3773   m = pool_elt_at_index (lcm->mapping_pool, mi);
3774
3775   gid_address_copy (&adj_args->reid, &m->eid);
3776   adj_args->is_add = 0;
3777   if (vnet_lisp_add_del_adjacency (adj_args))
3778     clib_warning ("failed to del adjacency!");
3779
3780   vnet_lisp_del_mapping (&m->eid, NULL);
3781   mapping_delete_timer (lcm, mi);
3782 }
3783
3784 static void
3785 mapping_start_expiration_timer (lisp_cp_main_t * lcm, u32 mi,
3786                                 f64 expiration_time)
3787 {
3788   mapping_t *m;
3789   u64 now = clib_cpu_time_now ();
3790   u64 cpu_cps = lcm->vlib_main->clib_time.clocks_per_second;
3791   u64 exp_clock_time = now + expiration_time * cpu_cps;
3792
3793   m = pool_elt_at_index (lcm->mapping_pool, mi);
3794
3795   m->timer_set = 1;
3796   timing_wheel_insert (&lcm->wheel, exp_clock_time, mi);
3797 }
3798
3799 static void
3800 process_expired_mapping (lisp_cp_main_t * lcm, u32 mi)
3801 {
3802   int rv;
3803   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
3804   mapping_t *m = pool_elt_at_index (lcm->mapping_pool, mi);
3805   uword *fei;
3806   fwd_entry_t *fe;
3807   vlib_counter_t c;
3808   u8 have_stats = 0;
3809
3810   if (m->delete_after_expiration)
3811     {
3812       remove_expired_mapping (lcm, mi);
3813       return;
3814     }
3815
3816   fei = hash_get (lcm->fwd_entry_by_mapping_index, mi);
3817   if (!fei)
3818     return;
3819
3820   fe = pool_elt_at_index (lcm->fwd_entry_pool, fei[0]);
3821
3822   clib_memset (a, 0, sizeof (*a));
3823   a->rmt_eid = fe->reid;
3824   if (fe->is_src_dst)
3825     a->lcl_eid = fe->leid;
3826   a->vni = gid_address_vni (&fe->reid);
3827
3828   rv = vnet_lisp_gpe_get_fwd_stats (a, &c);
3829   if (0 == rv)
3830     have_stats = 1;
3831
3832   if (m->almost_expired)
3833     {
3834       m->almost_expired = 0;    /* reset flag */
3835       if (have_stats)
3836         {
3837           if (m->packets != c.packets)
3838             {
3839               /* mapping is in use, re-fetch */
3840               map_request_args_t mr_args;
3841               clib_memset (&mr_args, 0, sizeof (mr_args));
3842               mr_args.seid = fe->leid;
3843               mr_args.deid = fe->reid;
3844
3845               send_map_request_thread_fn (&mr_args);
3846             }
3847           else
3848             remove_expired_mapping (lcm, mi);
3849         }
3850       else
3851         remove_expired_mapping (lcm, mi);
3852     }
3853   else
3854     {
3855       m->almost_expired = 1;
3856       mapping_start_expiration_timer (lcm, mi, TIME_UNTIL_REFETCH_OR_DELETE);
3857
3858       if (have_stats)
3859         /* save counter */
3860         m->packets = c.packets;
3861       else
3862         m->delete_after_expiration = 1;
3863     }
3864 }
3865
3866 static void
3867 map_records_arg_free (map_records_arg_t * a)
3868 {
3869   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3870   mapping_t *m;
3871   vec_foreach (m, a->mappings)
3872   {
3873     vec_free (m->locators);
3874     gid_address_free (&m->eid);
3875   }
3876   pool_put (lcm->map_records_args_pool[vlib_get_thread_index ()], a);
3877 }
3878
3879 void *
3880 process_map_reply (map_records_arg_t * a)
3881 {
3882   mapping_t *m;
3883   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3884   u32 dst_map_index = 0;
3885   pending_map_request_t *pmr;
3886   u64 *noncep;
3887   uword *pmr_index;
3888   u8 is_changed = 0;
3889
3890   if (a->is_rloc_probe)
3891     goto done;
3892
3893   /* Check pending requests table and nonce */
3894   pmr_index = hash_get (lcm->pending_map_requests_by_nonce, a->nonce);
3895   if (!pmr_index)
3896     {
3897       clib_warning ("No pending map-request entry with nonce %lu!", a->nonce);
3898       goto done;
3899     }
3900   pmr = pool_elt_at_index (lcm->pending_map_requests_pool, pmr_index[0]);
3901
3902   vec_foreach (m, a->mappings)
3903   {
3904     vnet_lisp_add_del_mapping_args_t _m_args, *m_args = &_m_args;
3905     clib_memset (m_args, 0, sizeof (m_args[0]));
3906     gid_address_copy (&m_args->eid, &m->eid);
3907     m_args->action = m->action;
3908     m_args->authoritative = m->authoritative;
3909     m_args->ttl = m->ttl;
3910     m_args->is_static = 0;
3911
3912     /* insert/update mappings cache */
3913     vnet_lisp_add_mapping (m_args, m->locators, &dst_map_index, &is_changed);
3914
3915     if (dst_map_index == (u32) ~ 0)
3916       continue;
3917
3918     if (is_changed)
3919       {
3920         /* try to program forwarding only if mapping saved or updated */
3921         vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
3922         clib_memset (adj_args, 0, sizeof (adj_args[0]));
3923
3924         gid_address_copy (&adj_args->leid, &pmr->src);
3925         gid_address_copy (&adj_args->reid, &m->eid);
3926         adj_args->is_add = 1;
3927
3928         if (vnet_lisp_add_del_adjacency (adj_args))
3929           clib_warning ("failed to add adjacency!");
3930       }
3931
3932     if ((u32) ~ 0 != m->ttl)
3933       mapping_start_expiration_timer (lcm, dst_map_index,
3934                                       (m->ttl == 0) ? 0 : MAPPING_TIMEOUT);
3935   }
3936
3937   /* remove pending map request entry */
3938
3939   /* *INDENT-OFF* */
3940   clib_fifo_foreach (noncep, pmr->nonces, ({
3941     hash_unset(lcm->pending_map_requests_by_nonce, noncep[0]);
3942   }));
3943   /* *INDENT-ON* */
3944
3945   clib_fifo_free (pmr->nonces);
3946   pool_put (lcm->pending_map_requests_pool, pmr);
3947
3948 done:
3949   a->is_free = 1;
3950   return 0;
3951 }
3952
3953 static int
3954 is_auth_data_valid (map_notify_hdr_t * h, u32 msg_len,
3955                     lisp_key_type_t key_id, u8 * key)
3956 {
3957   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3958   u8 *auth_data = 0;
3959   u16 auth_data_len;
3960   int result;
3961   vnet_crypto_op_t _op, *op = &_op;
3962   vnet_crypto_key_index_t ki;
3963   u8 out[EVP_MAX_MD_SIZE] = { 0, };
3964
3965   auth_data_len = auth_data_len_by_key_id (key_id);
3966   if ((u16) ~ 0 == auth_data_len)
3967     {
3968       clib_warning ("invalid length for key_id %d!", key_id);
3969       return 0;
3970     }
3971
3972   /* save auth data */
3973   vec_validate (auth_data, auth_data_len - 1);
3974   clib_memcpy (auth_data, MNOTIFY_DATA (h), auth_data_len);
3975
3976   /* clear auth data */
3977   clib_memset (MNOTIFY_DATA (h), 0, auth_data_len);
3978
3979   vnet_crypto_op_init (op, lisp_key_type_to_crypto_op (key_id));
3980   op->len = msg_len;
3981   op->digest = out;
3982   op->src = (u8 *) h;
3983   op->digest_len = 0;
3984   op->iv = 0;
3985
3986   ki = vnet_crypto_key_add (lcm->vlib_main,
3987                             lisp_key_type_to_crypto_alg (key_id), key,
3988                             vec_len (key));
3989
3990   op->key_index = ki;
3991
3992   vnet_crypto_process_ops (lcm->vlib_main, op, 1);
3993   vnet_crypto_key_del (lcm->vlib_main, ki);
3994
3995   result = memcmp (out, auth_data, auth_data_len);
3996
3997   vec_free (auth_data);
3998
3999   return !result;
4000 }
4001
4002 static void
4003 process_map_notify (map_records_arg_t * a)
4004 {
4005   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4006   uword *pmr_index;
4007
4008   pmr_index = hash_get (lcm->map_register_messages_by_nonce, a->nonce);
4009   if (!pmr_index)
4010     {
4011       clib_warning ("No pending map-register entry with nonce %lu!",
4012                     a->nonce);
4013       return;
4014     }
4015
4016   a->is_free = 1;
4017   pool_put_index (lcm->pending_map_registers_pool, pmr_index[0]);
4018   hash_unset (lcm->map_register_messages_by_nonce, a->nonce);
4019
4020   /* reset map-notify counter */
4021   lcm->expired_map_registers = 0;
4022 }
4023
4024 static mapping_t *
4025 get_mapping (lisp_cp_main_t * lcm, gid_address_t * e)
4026 {
4027   u32 mi;
4028
4029   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, e);
4030   if (~0 == mi)
4031     {
4032       clib_warning ("eid %U not found in map-cache!", unformat_gid_address,
4033                     e);
4034       return 0;
4035     }
4036   return pool_elt_at_index (lcm->mapping_pool, mi);
4037 }
4038
4039 /**
4040  * When map-notify is received it is necessary that all EIDs in the record
4041  * list share common key. The key is then used to verify authentication
4042  * data in map-notify message.
4043  */
4044 static int
4045 map_record_integrity_check (lisp_cp_main_t * lcm, mapping_t * maps,
4046                             u32 key_id, u8 ** key_out)
4047 {
4048   u32 i, len = vec_len (maps);
4049   mapping_t *m;
4050
4051   /* get key of the first mapping */
4052   m = get_mapping (lcm, &maps[0].eid);
4053   if (!m || !m->key)
4054     return -1;
4055
4056   key_out[0] = m->key;
4057
4058   for (i = 1; i < len; i++)
4059     {
4060       m = get_mapping (lcm, &maps[i].eid);
4061       if (!m || !m->key)
4062         return -1;
4063
4064       if (key_id != m->key_id || vec_cmp (m->key, key_out[0]))
4065         {
4066           clib_warning ("keys does not match! %v, %v", key_out[0], m->key);
4067           return -1;
4068         }
4069     }
4070   return 0;
4071 }
4072
4073 static int
4074 parse_map_records (vlib_buffer_t * b, map_records_arg_t * a, u8 count)
4075 {
4076   locator_t *locators = 0;
4077   u32 i, len;
4078   gid_address_t deid;
4079   mapping_t m;
4080   locator_t *loc;
4081
4082   clib_memset (&m, 0, sizeof (m));
4083
4084   /* parse record eid */
4085   for (i = 0; i < count; i++)
4086     {
4087       locators = 0;
4088       len = lisp_msg_parse_mapping_record (b, &deid, &locators, NULL);
4089       if (len == ~0)
4090         {
4091           clib_warning ("Failed to parse mapping record!");
4092           vec_foreach (loc, locators) locator_free (loc);
4093           vec_free (locators);
4094           return -1;
4095         }
4096
4097       m.locators = locators;
4098       gid_address_copy (&m.eid, &deid);
4099       vec_add1 (a->mappings, m);
4100     }
4101
4102   return 0;
4103 }
4104
4105 static map_records_arg_t *
4106 map_record_args_get ()
4107 {
4108   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4109   map_records_arg_t *rec;
4110
4111   /* Cleanup first */
4112   /* *INDENT-OFF* */
4113   pool_foreach (rec, lcm->map_records_args_pool[vlib_get_thread_index()], ({
4114     if (rec->is_free)
4115       map_records_arg_free (rec);
4116   }));
4117   /* *INDENT-ON* */
4118
4119   pool_get (lcm->map_records_args_pool[vlib_get_thread_index ()], rec);
4120   return rec;
4121 }
4122
4123 static map_records_arg_t *
4124 parse_map_notify (vlib_buffer_t * b)
4125 {
4126   int rc = 0;
4127   map_notify_hdr_t *mnotif_hdr;
4128   lisp_key_type_t key_id;
4129   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4130   u8 *key = 0;
4131   gid_address_t deid;
4132   u16 auth_data_len = 0;
4133   u8 record_count;
4134   map_records_arg_t *a;
4135
4136   a = map_record_args_get ();
4137   clib_memset (a, 0, sizeof (*a));
4138   mnotif_hdr = vlib_buffer_get_current (b);
4139   vlib_buffer_pull (b, sizeof (*mnotif_hdr));
4140   clib_memset (&deid, 0, sizeof (deid));
4141
4142   a->nonce = MNOTIFY_NONCE (mnotif_hdr);
4143   key_id = clib_net_to_host_u16 (MNOTIFY_KEY_ID (mnotif_hdr));
4144   auth_data_len = auth_data_len_by_key_id (key_id);
4145
4146   /* advance buffer by authentication data */
4147   vlib_buffer_pull (b, auth_data_len);
4148
4149   record_count = MNOTIFY_REC_COUNT (mnotif_hdr);
4150   rc = parse_map_records (b, a, record_count);
4151   if (rc != 0)
4152     {
4153       map_records_arg_free (a);
4154       return 0;
4155     }
4156
4157   rc = map_record_integrity_check (lcm, a->mappings, key_id, &key);
4158   if (rc != 0)
4159     {
4160       map_records_arg_free (a);
4161       return 0;
4162     }
4163
4164   /* verify authentication data */
4165   if (!is_auth_data_valid (mnotif_hdr, vlib_buffer_get_tail (b)
4166                            - (u8 *) mnotif_hdr, key_id, key))
4167     {
4168       clib_warning ("Map-notify auth data verification failed for nonce "
4169                     "0x%lx!", a->nonce);
4170       map_records_arg_free (a);
4171       return 0;
4172     }
4173   return a;
4174 }
4175
4176 static vlib_buffer_t *
4177 build_map_reply (lisp_cp_main_t * lcm, ip_address_t * sloc,
4178                  ip_address_t * dst, u64 nonce, u8 probe_bit,
4179                  mapping_t * records, u16 dst_port, u32 * bi_res)
4180 {
4181   vlib_buffer_t *b;
4182   u32 bi;
4183   vlib_main_t *vm = lcm->vlib_main;
4184
4185   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
4186     {
4187       clib_warning ("Can't allocate buffer for Map-Register!");
4188       return 0;
4189     }
4190
4191   b = vlib_get_buffer (vm, bi);
4192
4193   /* leave some space for the encap headers */
4194   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
4195
4196   lisp_msg_put_map_reply (b, records, nonce, probe_bit);
4197
4198   /* push outer ip header */
4199   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, dst_port, sloc, dst, 1);
4200
4201   bi_res[0] = bi;
4202   return b;
4203 }
4204
4205 static int
4206 send_map_reply (lisp_cp_main_t * lcm, u32 mi, ip_address_t * dst,
4207                 u8 probe_bit, u64 nonce, u16 dst_port,
4208                 ip_address_t * probed_loc)
4209 {
4210   ip_address_t src;
4211   u32 bi;
4212   vlib_buffer_t *b;
4213   vlib_frame_t *f;
4214   u32 next_index, *to_next;
4215   mapping_t *records = 0, *m;
4216
4217   m = pool_elt_at_index (lcm->mapping_pool, mi);
4218   if (!m)
4219     return -1;
4220
4221   vec_add1 (records, m[0]);
4222   add_locators (lcm, &records[0], m->locator_set_index, probed_loc);
4223   clib_memset (&src, 0, sizeof (src));
4224
4225   if (!ip_fib_get_first_egress_ip_for_dst (lcm, dst, &src))
4226     {
4227       clib_warning ("can't find interface address for %U", format_ip_address,
4228                     dst);
4229       return -1;
4230     }
4231
4232   b = build_map_reply (lcm, &src, dst, nonce, probe_bit, records, dst_port,
4233                        &bi);
4234   if (!b)
4235     return -1;
4236   free_map_register_records (records);
4237
4238   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
4239   next_index = (ip_addr_version (&lcm->active_map_resolver) == AF_IP4) ?
4240     ip4_lookup_node.index : ip6_lookup_node.index;
4241
4242   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
4243
4244   /* Enqueue the packet */
4245   to_next = vlib_frame_vector_args (f);
4246   to_next[0] = bi;
4247   f->n_vectors = 1;
4248   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
4249   return 0;
4250 }
4251
4252 static void
4253 find_ip_header (vlib_buffer_t * b, u8 ** ip_hdr)
4254 {
4255   const i32 start = vnet_buffer (b)->l3_hdr_offset;
4256   if (start < 0 && start < -sizeof (b->pre_data))
4257     {
4258       *ip_hdr = 0;
4259       return;
4260     }
4261
4262   *ip_hdr = b->data + start;
4263   if ((u8 *) * ip_hdr > (u8 *) vlib_buffer_get_current (b))
4264     *ip_hdr = 0;
4265 }
4266
4267 void
4268 process_map_request (vlib_main_t * vm, vlib_node_runtime_t * node,
4269                      lisp_cp_main_t * lcm, vlib_buffer_t * b)
4270 {
4271   u8 *ip_hdr = 0;
4272   ip_address_t *dst_loc = 0, probed_loc, src_loc;
4273   mapping_t m;
4274   map_request_hdr_t *mreq_hdr;
4275   gid_address_t src, dst;
4276   u64 nonce;
4277   u32 i, len = 0, rloc_probe_recv = 0;
4278   gid_address_t *itr_rlocs = 0;
4279
4280   mreq_hdr = vlib_buffer_get_current (b);
4281   if (!MREQ_SMR (mreq_hdr) && !MREQ_RLOC_PROBE (mreq_hdr))
4282     {
4283       clib_warning
4284         ("Only SMR Map-Requests and RLOC probe supported for now!");
4285       return;
4286     }
4287
4288   vlib_buffer_pull (b, sizeof (*mreq_hdr));
4289   nonce = MREQ_NONCE (mreq_hdr);
4290
4291   /* parse src eid */
4292   len = lisp_msg_parse_addr (b, &src);
4293   if (len == ~0)
4294     return;
4295
4296   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs,
4297                                   MREQ_ITR_RLOC_COUNT (mreq_hdr) + 1);
4298   if (len == ~0)
4299     goto done;
4300
4301   /* parse eid records and send SMR-invoked map-requests */
4302   for (i = 0; i < MREQ_REC_COUNT (mreq_hdr); i++)
4303     {
4304       clib_memset (&dst, 0, sizeof (dst));
4305       len = lisp_msg_parse_eid_rec (b, &dst);
4306       if (len == ~0)
4307         {
4308           clib_warning ("Can't parse map-request EID-record");
4309           goto done;
4310         }
4311
4312       if (MREQ_SMR (mreq_hdr))
4313         {
4314           /* send SMR-invoked map-requests */
4315           queue_map_request (&dst, &src, 1 /* invoked */ , 0 /* resend */ );
4316         }
4317       else if (MREQ_RLOC_PROBE (mreq_hdr))
4318         {
4319           find_ip_header (b, &ip_hdr);
4320           if (!ip_hdr)
4321             {
4322               clib_warning ("Cannot find the IP header!");
4323               goto done;
4324             }
4325           rloc_probe_recv++;
4326           clib_memset (&m, 0, sizeof (m));
4327           u32 mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
4328
4329           // TODO: select best locator; for now use the first one
4330           dst_loc = &gid_address_ip (&itr_rlocs[0]);
4331
4332           /* get src/dst IP addresses */
4333           get_src_and_dst_ip (ip_hdr, &src_loc, &probed_loc);
4334
4335           // TODO get source port from buffer
4336           u16 src_port = LISP_CONTROL_PORT;
4337
4338           send_map_reply (lcm, mi, dst_loc, 1 /* probe-bit */ , nonce,
4339                           src_port, &probed_loc);
4340         }
4341     }
4342
4343 done:
4344   vlib_node_increment_counter (vm, node->node_index,
4345                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REQ_RECEIVED,
4346                                rloc_probe_recv);
4347   vec_free (itr_rlocs);
4348 }
4349
4350 map_records_arg_t *
4351 parse_map_reply (vlib_buffer_t * b)
4352 {
4353   locator_t probed;
4354   gid_address_t deid;
4355   void *h;
4356   u32 i, len = 0;
4357   mapping_t m;
4358   map_reply_hdr_t *mrep_hdr;
4359   map_records_arg_t *a;
4360
4361   a = map_record_args_get ();
4362   clib_memset (a, 0, sizeof (*a));
4363
4364   locator_t *locators;
4365
4366   mrep_hdr = vlib_buffer_get_current (b);
4367   a->nonce = MREP_NONCE (mrep_hdr);
4368   a->is_rloc_probe = MREP_RLOC_PROBE (mrep_hdr);
4369   if (!vlib_buffer_has_space (b, sizeof (*mrep_hdr)))
4370     {
4371       map_records_arg_free (a);
4372       return 0;
4373     }
4374   vlib_buffer_pull (b, sizeof (*mrep_hdr));
4375
4376   for (i = 0; i < MREP_REC_COUNT (mrep_hdr); i++)
4377     {
4378       clib_memset (&m, 0, sizeof (m));
4379       locators = 0;
4380       h = vlib_buffer_get_current (b);
4381
4382       m.ttl = clib_net_to_host_u32 (MAP_REC_TTL (h));
4383       m.action = MAP_REC_ACTION (h);
4384       m.authoritative = MAP_REC_AUTH (h);
4385
4386       len = lisp_msg_parse_mapping_record (b, &deid, &locators, &probed);
4387       if (len == ~0)
4388         {
4389           clib_warning ("Failed to parse mapping record!");
4390           map_records_arg_free (a);
4391           return 0;
4392         }
4393
4394       m.locators = locators;
4395       gid_address_copy (&m.eid, &deid);
4396       vec_add1 (a->mappings, m);
4397     }
4398   return a;
4399 }
4400
4401 static void
4402 queue_map_reply_for_processing (map_records_arg_t * a)
4403 {
4404   vl_api_rpc_call_main_thread (process_map_reply, (u8 *) a, sizeof (*a));
4405 }
4406
4407 static void
4408 queue_map_notify_for_processing (map_records_arg_t * a)
4409 {
4410   vl_api_rpc_call_main_thread (process_map_notify, (u8 *) a, sizeof (a[0]));
4411 }
4412
4413 static uword
4414 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
4415                vlib_frame_t * from_frame)
4416 {
4417   u32 n_left_from, *from, *to_next_drop, rloc_probe_rep_recv = 0,
4418     map_notifies_recv = 0;
4419   lisp_msg_type_e type;
4420   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4421   map_records_arg_t *a;
4422
4423   from = vlib_frame_vector_args (from_frame);
4424   n_left_from = from_frame->n_vectors;
4425
4426
4427   while (n_left_from > 0)
4428     {
4429       u32 n_left_to_next_drop;
4430
4431       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
4432                            to_next_drop, n_left_to_next_drop);
4433       while (n_left_from > 0 && n_left_to_next_drop > 0)
4434         {
4435           u32 bi0;
4436           vlib_buffer_t *b0;
4437
4438           bi0 = from[0];
4439           from += 1;
4440           n_left_from -= 1;
4441           to_next_drop[0] = bi0;
4442           to_next_drop += 1;
4443           n_left_to_next_drop -= 1;
4444
4445           b0 = vlib_get_buffer (vm, bi0);
4446
4447           type = lisp_msg_type (vlib_buffer_get_current (b0));
4448           switch (type)
4449             {
4450             case LISP_MAP_REPLY:
4451               a = parse_map_reply (b0);
4452               if (a)
4453                 {
4454                   if (a->is_rloc_probe)
4455                     rloc_probe_rep_recv++;
4456                   queue_map_reply_for_processing (a);
4457                 }
4458               break;
4459             case LISP_MAP_REQUEST:
4460               process_map_request (vm, node, lcm, b0);
4461               break;
4462             case LISP_MAP_NOTIFY:
4463               a = parse_map_notify (b0);
4464               if (a)
4465                 {
4466                   map_notifies_recv++;
4467                   queue_map_notify_for_processing (a);
4468                 }
4469               break;
4470             default:
4471               clib_warning ("Unsupported LISP message type %d", type);
4472               break;
4473             }
4474
4475           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
4476
4477           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
4478             {
4479
4480             }
4481         }
4482
4483       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
4484                            n_left_to_next_drop);
4485     }
4486   vlib_node_increment_counter (vm, node->node_index,
4487                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REP_RECEIVED,
4488                                rloc_probe_rep_recv);
4489   vlib_node_increment_counter (vm, node->node_index,
4490                                LISP_CP_INPUT_ERROR_MAP_NOTIFIES_RECEIVED,
4491                                map_notifies_recv);
4492   return from_frame->n_vectors;
4493 }
4494
4495 /* *INDENT-OFF* */
4496 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
4497   .function = lisp_cp_input,
4498   .name = "lisp-cp-input",
4499   .vector_size = sizeof (u32),
4500   .format_trace = format_lisp_cp_input_trace,
4501   .type = VLIB_NODE_TYPE_INTERNAL,
4502
4503   .n_errors = LISP_CP_INPUT_N_ERROR,
4504   .error_strings = lisp_cp_input_error_strings,
4505
4506   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
4507
4508   .next_nodes = {
4509       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
4510   },
4511 };
4512 /* *INDENT-ON* */
4513
4514 clib_error_t *
4515 lisp_cp_init (vlib_main_t * vm)
4516 {
4517   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4518   clib_error_t *error = 0;
4519   vlib_thread_main_t *vtm = vlib_get_thread_main ();
4520   u32 num_threads;
4521
4522   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
4523     return error;
4524
4525   lcm->im4 = &ip4_main;
4526   lcm->im6 = &ip6_main;
4527   lcm->vlib_main = vm;
4528   lcm->vnet_main = vnet_get_main ();
4529   lcm->mreq_itr_rlocs = ~0;
4530   lcm->flags = 0;
4531   lcm->pitr_map_index = ~0;
4532   lcm->petr_map_index = ~0;
4533   clib_memset (&lcm->active_map_resolver, 0,
4534                sizeof (lcm->active_map_resolver));
4535   clib_memset (&lcm->active_map_server, 0, sizeof (lcm->active_map_server));
4536
4537   gid_dictionary_init (&lcm->mapping_index_by_gid);
4538   lcm->do_map_resolver_election = 1;
4539   lcm->do_map_server_election = 1;
4540   lcm->map_request_mode = MR_MODE_DST_ONLY;
4541
4542   num_threads = 1 /* main thread */  + vtm->n_threads;
4543   vec_validate (lcm->map_records_args_pool, num_threads - 1);
4544
4545   /* default vrf mapped to vni 0 */
4546   hash_set (lcm->table_id_by_vni, 0, 0);
4547   hash_set (lcm->vni_by_table_id, 0, 0);
4548
4549   u64 now = clib_cpu_time_now ();
4550   timing_wheel_init (&lcm->wheel, now, vm->clib_time.clocks_per_second);
4551   lcm->nsh_map_index = ~0;
4552   lcm->map_register_ttl = MAP_REGISTER_DEFAULT_TTL;
4553   lcm->max_expired_map_registers = MAX_EXPIRED_MAP_REGISTERS_DEFAULT;
4554   lcm->expired_map_registers = 0;
4555   lcm->transport_protocol = LISP_TRANSPORT_PROTOCOL_UDP;
4556   lcm->flags |= LISP_FLAG_XTR_MODE;
4557   return 0;
4558 }
4559
4560 static int
4561 lisp_stats_api_fill (lisp_cp_main_t * lcm, lisp_gpe_main_t * lgm,
4562                      lisp_api_stats_t * stat, lisp_stats_key_t * key,
4563                      u32 stats_index)
4564 {
4565   vlib_counter_t v;
4566   vlib_combined_counter_main_t *cm = &lgm->counters;
4567   lisp_gpe_fwd_entry_key_t fwd_key;
4568   const lisp_gpe_tunnel_t *lgt;
4569   fwd_entry_t *fe;
4570
4571   clib_memset (stat, 0, sizeof (*stat));
4572   clib_memset (&fwd_key, 0, sizeof (fwd_key));
4573
4574   fe = pool_elt_at_index (lcm->fwd_entry_pool, key->fwd_entry_index);
4575   ASSERT (fe != 0);
4576
4577   gid_to_dp_address (&fe->reid, &stat->deid);
4578   gid_to_dp_address (&fe->leid, &stat->seid);
4579   stat->vni = gid_address_vni (&fe->reid);
4580
4581   lgt = lisp_gpe_tunnel_get (key->tunnel_index);
4582   stat->loc_rloc = lgt->key->lcl;
4583   stat->rmt_rloc = lgt->key->rmt;
4584
4585   vlib_get_combined_counter (cm, stats_index, &v);
4586   stat->counters = v;
4587   return 1;
4588 }
4589
4590 lisp_api_stats_t *
4591 vnet_lisp_get_stats (void)
4592 {
4593   lisp_gpe_main_t *lgm = vnet_lisp_gpe_get_main ();
4594   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4595   lisp_api_stats_t *stats = 0, stat;
4596   lisp_stats_key_t *key;
4597   u32 index;
4598
4599   /* *INDENT-OFF* */
4600   hash_foreach_mem (key, index, lgm->lisp_stats_index_by_key,
4601   {
4602     if (lisp_stats_api_fill (lcm, lgm, &stat, key, index))
4603       vec_add1 (stats, stat);
4604   });
4605   /* *INDENT-ON* */
4606
4607   return stats;
4608 }
4609
4610 static void *
4611 send_map_request_thread_fn (void *arg)
4612 {
4613   map_request_args_t *a = arg;
4614   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4615
4616   if (a->is_resend)
4617     resend_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
4618   else
4619     send_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
4620
4621   return 0;
4622 }
4623
4624 static int
4625 queue_map_request (gid_address_t * seid, gid_address_t * deid,
4626                    u8 smr_invoked, u8 is_resend)
4627 {
4628   map_request_args_t a;
4629
4630   a.is_resend = is_resend;
4631   gid_address_copy (&a.seid, seid);
4632   gid_address_copy (&a.deid, deid);
4633   a.smr_invoked = smr_invoked;
4634
4635   vl_api_rpc_call_main_thread (send_map_request_thread_fn,
4636                                (u8 *) & a, sizeof (a));
4637   return 0;
4638 }
4639
4640 /**
4641  * Take an action with a pending map request depending on expiration time
4642  * and re-try counters.
4643  */
4644 static void
4645 update_pending_request (pending_map_request_t * r, f64 dt)
4646 {
4647   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4648   lisp_msmr_t *mr;
4649
4650   if (r->time_to_expire - dt < 0)
4651     /* it's time to decide what to do with this pending request */
4652     {
4653       if (r->retries_num >= NUMBER_OF_RETRIES)
4654         /* too many retries -> assume current map resolver is not available */
4655         {
4656           mr = get_map_resolver (&lcm->active_map_resolver);
4657           if (!mr)
4658             {
4659               clib_warning ("Map resolver %U not found - probably deleted "
4660                             "by the user recently.", format_ip_address,
4661                             &lcm->active_map_resolver);
4662             }
4663           else
4664             {
4665               clib_warning ("map resolver %U is unreachable, ignoring",
4666                             format_ip_address, &lcm->active_map_resolver);
4667
4668               /* mark current map resolver unavailable so it won't be
4669                * selected next time */
4670               mr->is_down = 1;
4671               mr->last_update = vlib_time_now (lcm->vlib_main);
4672             }
4673
4674           reset_pending_mr_counters (r);
4675           elect_map_resolver (lcm);
4676
4677           /* try to find a next eligible map resolver and re-send */
4678           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
4679                              1 /* resend */ );
4680         }
4681       else
4682         {
4683           /* try again */
4684           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
4685                              1 /* resend */ );
4686           r->retries_num++;
4687           r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
4688         }
4689     }
4690   else
4691     r->time_to_expire -= dt;
4692 }
4693
4694 static void
4695 remove_dead_pending_map_requests (lisp_cp_main_t * lcm)
4696 {
4697   u64 *nonce;
4698   pending_map_request_t *pmr;
4699   u32 *to_be_removed = 0, *pmr_index;
4700
4701   /* *INDENT-OFF* */
4702   pool_foreach (pmr, lcm->pending_map_requests_pool,
4703   ({
4704     if (pmr->to_be_removed)
4705       {
4706         clib_fifo_foreach (nonce, pmr->nonces, ({
4707           hash_unset (lcm->pending_map_requests_by_nonce, nonce[0]);
4708         }));
4709
4710         vec_add1 (to_be_removed, pmr - lcm->pending_map_requests_pool);
4711       }
4712   }));
4713   /* *INDENT-ON* */
4714
4715   vec_foreach (pmr_index, to_be_removed)
4716     pool_put_index (lcm->pending_map_requests_pool, pmr_index[0]);
4717
4718   vec_free (to_be_removed);
4719 }
4720
4721 static void
4722 update_rloc_probing (lisp_cp_main_t * lcm, f64 dt)
4723 {
4724   static f64 time_left = RLOC_PROBING_INTERVAL;
4725
4726   if (!lcm->is_enabled || !lcm->rloc_probing)
4727     return;
4728
4729   time_left -= dt;
4730   if (time_left <= 0)
4731     {
4732       time_left = RLOC_PROBING_INTERVAL;
4733       send_rloc_probes (lcm);
4734     }
4735 }
4736
4737 static int
4738 update_pending_map_register (pending_map_register_t * r, f64 dt, u8 * del_all)
4739 {
4740   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4741   lisp_msmr_t *ms;
4742   del_all[0] = 0;
4743
4744   r->time_to_expire -= dt;
4745
4746   if (r->time_to_expire < 0)
4747     {
4748       lcm->expired_map_registers++;
4749
4750       if (lcm->expired_map_registers >= lcm->max_expired_map_registers)
4751         {
4752           ms = get_map_server (&lcm->active_map_server);
4753           if (!ms)
4754             {
4755               clib_warning ("Map server %U not found - probably deleted "
4756                             "by the user recently.", format_ip_address,
4757                             &lcm->active_map_server);
4758             }
4759           else
4760             {
4761               clib_warning ("map server %U is unreachable, ignoring",
4762                             format_ip_address, &lcm->active_map_server);
4763
4764               /* mark current map server unavailable so it won't be
4765                * elected next time */
4766               ms->is_down = 1;
4767               ms->last_update = vlib_time_now (lcm->vlib_main);
4768             }
4769
4770           elect_map_server (lcm);
4771
4772           /* indication for deleting all pending map registers */
4773           del_all[0] = 1;
4774           lcm->expired_map_registers = 0;
4775           return 0;
4776         }
4777       else
4778         {
4779           /* delete pending map register */
4780           return 0;
4781         }
4782     }
4783   return 1;
4784 }
4785
4786 static void
4787 update_map_register (lisp_cp_main_t * lcm, f64 dt)
4788 {
4789   u32 *to_be_removed = 0, *pmr_index;
4790   static f64 time_left = QUICK_MAP_REGISTER_INTERVAL;
4791   static u64 mreg_sent_counter = 0;
4792
4793   pending_map_register_t *pmr;
4794   u8 del_all = 0;
4795
4796   if (!lcm->is_enabled || !lcm->map_registering)
4797     return;
4798
4799   /* *INDENT-OFF* */
4800   pool_foreach (pmr, lcm->pending_map_registers_pool,
4801   ({
4802     if (!update_pending_map_register (pmr, dt, &del_all))
4803     {
4804       if (del_all)
4805         break;
4806       vec_add1 (to_be_removed, pmr - lcm->pending_map_registers_pool);
4807     }
4808   }));
4809   /* *INDENT-ON* */
4810
4811   if (del_all)
4812     {
4813       /* delete all pending map register messages so they won't
4814        * trigger another map server election.. */
4815       pool_free (lcm->pending_map_registers_pool);
4816       hash_free (lcm->map_register_messages_by_nonce);
4817
4818       /* ..and trigger registration against next map server (if any) */
4819       time_left = 0;
4820     }
4821   else
4822     {
4823       vec_foreach (pmr_index, to_be_removed)
4824         pool_put_index (lcm->pending_map_registers_pool, pmr_index[0]);
4825     }
4826
4827   vec_free (to_be_removed);
4828
4829   time_left -= dt;
4830   if (time_left <= 0)
4831     {
4832       if (mreg_sent_counter >= QUICK_MAP_REGISTER_MSG_COUNT)
4833         time_left = MAP_REGISTER_INTERVAL;
4834       else
4835         {
4836           mreg_sent_counter++;
4837           time_left = QUICK_MAP_REGISTER_INTERVAL;
4838         }
4839       send_map_register (lcm, 1 /* want map notify */ );
4840     }
4841 }
4842
4843 static uword
4844 send_map_resolver_service (vlib_main_t * vm,
4845                            vlib_node_runtime_t * rt, vlib_frame_t * f)
4846 {
4847   u32 *expired = 0;
4848   f64 period = 2.0;
4849   pending_map_request_t *pmr;
4850   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4851
4852   while (1)
4853     {
4854       vlib_process_wait_for_event_or_clock (vm, period);
4855
4856       /* currently no signals are expected - just wait for clock */
4857       (void) vlib_process_get_events (vm, 0);
4858
4859       /* *INDENT-OFF* */
4860       pool_foreach (pmr, lcm->pending_map_requests_pool,
4861       ({
4862         if (!pmr->to_be_removed)
4863           update_pending_request (pmr, period);
4864       }));
4865       /* *INDENT-ON* */
4866
4867       remove_dead_pending_map_requests (lcm);
4868
4869       update_map_register (lcm, period);
4870       update_rloc_probing (lcm, period);
4871
4872       u64 now = clib_cpu_time_now ();
4873
4874       expired = timing_wheel_advance (&lcm->wheel, now, expired, 0);
4875       if (vec_len (expired) > 0)
4876         {
4877           u32 *mi = 0;
4878           vec_foreach (mi, expired)
4879           {
4880             process_expired_mapping (lcm, mi[0]);
4881           }
4882           _vec_len (expired) = 0;
4883         }
4884     }
4885
4886   /* unreachable */
4887   return 0;
4888 }
4889
4890 vnet_api_error_t
4891 vnet_lisp_stats_enable_disable (u8 enable)
4892 {
4893   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4894
4895   if (vnet_lisp_enable_disable_status () == 0)
4896     return VNET_API_ERROR_LISP_DISABLED;
4897
4898   if (enable)
4899     lcm->flags |= LISP_FLAG_STATS_ENABLED;
4900   else
4901     lcm->flags &= ~LISP_FLAG_STATS_ENABLED;
4902
4903   return 0;
4904 }
4905
4906 u8
4907 vnet_lisp_stats_enable_disable_state (void)
4908 {
4909   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4910
4911   if (vnet_lisp_enable_disable_status () == 0)
4912     return VNET_API_ERROR_LISP_DISABLED;
4913
4914   return lcm->flags & LISP_FLAG_STATS_ENABLED;
4915 }
4916
4917 void
4918 vnet_lisp_create_retry_process (lisp_cp_main_t * lcm)
4919 {
4920   if (lcm->retry_service_index)
4921     return;
4922
4923   lcm->retry_service_index = vlib_process_create (vlib_get_main (),
4924                                                   "lisp-retry-service",
4925                                                   send_map_resolver_service,
4926                                                   16 /* stack_bytes */ );
4927 }
4928
4929 u32
4930 vnet_lisp_set_transport_protocol (u8 protocol)
4931 {
4932   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4933
4934   if (protocol < LISP_TRANSPORT_PROTOCOL_UDP ||
4935       protocol > LISP_TRANSPORT_PROTOCOL_API)
4936     return VNET_API_ERROR_INVALID_ARGUMENT;
4937
4938   lcm->transport_protocol = protocol;
4939   return 0;
4940 }
4941
4942 lisp_transport_protocol_t
4943 vnet_lisp_get_transport_protocol (void)
4944 {
4945   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4946   return lcm->transport_protocol;
4947 }
4948
4949 int
4950 vnet_lisp_enable_disable_xtr_mode (u8 is_enabled)
4951 {
4952   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4953   u8 pitr_mode = lcm->flags & LISP_FLAG_PITR_MODE;
4954   u8 xtr_mode = lcm->flags & LISP_FLAG_XTR_MODE;
4955   u8 petr_mode = lcm->flags & LISP_FLAG_PETR_MODE;
4956
4957   if (pitr_mode && is_enabled)
4958     return VNET_API_ERROR_INVALID_ARGUMENT;
4959
4960   if (is_enabled && xtr_mode)
4961     return 0;
4962   if (!is_enabled && !xtr_mode)
4963     return 0;
4964
4965   if (is_enabled)
4966     {
4967       if (!petr_mode)
4968         {
4969           lisp_cp_register_dst_port (lcm->vlib_main);
4970         }
4971       lisp_cp_enable_l2_l3_ifaces (lcm, 1 /* with_default_route */ );
4972       lcm->flags |= LISP_FLAG_XTR_MODE;
4973     }
4974   else
4975     {
4976       if (!petr_mode)
4977         {
4978           lisp_cp_unregister_dst_port (lcm->vlib_main);
4979         }
4980       lisp_cp_disable_l2_l3_ifaces (lcm);
4981       lcm->flags &= ~LISP_FLAG_XTR_MODE;
4982     }
4983   return 0;
4984 }
4985
4986 int
4987 vnet_lisp_enable_disable_pitr_mode (u8 is_enabled)
4988 {
4989   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
4990   u8 xtr_mode = lcm->flags & LISP_FLAG_XTR_MODE;
4991   u8 pitr_mode = lcm->flags & LISP_FLAG_PITR_MODE;
4992
4993   if (xtr_mode && is_enabled)
4994     return VNET_API_ERROR_INVALID_VALUE;
4995
4996   if (is_enabled && pitr_mode)
4997     return 0;
4998   if (!is_enabled && !pitr_mode)
4999     return 0;
5000
5001   if (is_enabled)
5002     {
5003       /* create iface, no default route */
5004       lisp_cp_enable_l2_l3_ifaces (lcm, 0 /* with_default_route */ );
5005       lcm->flags |= LISP_FLAG_PITR_MODE;
5006     }
5007   else
5008     {
5009       lisp_cp_disable_l2_l3_ifaces (lcm);
5010       lcm->flags &= ~LISP_FLAG_PITR_MODE;
5011     }
5012   return 0;
5013 }
5014
5015 int
5016 vnet_lisp_enable_disable_petr_mode (u8 is_enabled)
5017 {
5018   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
5019   u8 xtr_mode = lcm->flags & LISP_FLAG_XTR_MODE;
5020   u8 petr_mode = lcm->flags & LISP_FLAG_PETR_MODE;
5021
5022   if (is_enabled && petr_mode)
5023     return 0;
5024   if (!is_enabled && !petr_mode)
5025     return 0;
5026
5027   if (is_enabled)
5028     {
5029       if (!xtr_mode)
5030         {
5031           lisp_cp_register_dst_port (lcm->vlib_main);
5032         }
5033       lcm->flags |= LISP_FLAG_PETR_MODE;
5034     }
5035   else
5036     {
5037       if (!xtr_mode)
5038         {
5039           lisp_cp_unregister_dst_port (lcm->vlib_main);
5040         }
5041       lcm->flags &= ~LISP_FLAG_PETR_MODE;
5042     }
5043   return 0;
5044 }
5045
5046 u8
5047 vnet_lisp_get_xtr_mode (void)
5048 {
5049   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
5050   return (lcm->flags & LISP_FLAG_XTR_MODE);
5051 }
5052
5053 u8
5054 vnet_lisp_get_pitr_mode (void)
5055 {
5056   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
5057   return (lcm->flags & LISP_FLAG_PITR_MODE);
5058 }
5059
5060 u8
5061 vnet_lisp_get_petr_mode (void)
5062 {
5063   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
5064   return (lcm->flags & LISP_FLAG_PETR_MODE);
5065 }
5066
5067 VLIB_INIT_FUNCTION (lisp_cp_init);
5068
5069 /*
5070  * fd.io coding-style-patch-verification: ON
5071  *
5072  * Local Variables:
5073  * eval: (c-set-style "gnu")
5074  * End:
5075  */