47badeb916325c2822f234ec43bd13be1eea2fbd
[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
26 #include <openssl/evp.h>
27 #include <openssl/hmac.h>
28
29 lisp_cp_main_t lisp_control_main;
30
31 u8 *format_lisp_cp_input_trace (u8 * s, va_list * args);
32
33 typedef enum
34 {
35   LISP_CP_INPUT_NEXT_DROP,
36   LISP_CP_INPUT_N_NEXT,
37 } lisp_cp_input_next_t;
38
39 typedef struct
40 {
41   u8 is_resend;
42   gid_address_t seid;
43   gid_address_t deid;
44   u8 smr_invoked;
45 } map_request_args_t;
46
47 typedef struct
48 {
49   u64 nonce;
50   u8 is_rloc_probe;
51   mapping_t *mappings;
52 } map_records_arg_t;
53
54 u8
55 vnet_lisp_get_map_request_mode (void)
56 {
57   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
58   return lcm->map_request_mode;
59 }
60
61 static u16
62 auth_data_len_by_key_id (lisp_key_type_t key_id)
63 {
64   switch (key_id)
65     {
66     case HMAC_SHA_1_96:
67       return SHA1_AUTH_DATA_LEN;
68     case HMAC_SHA_256_128:
69       return SHA256_AUTH_DATA_LEN;
70     default:
71       clib_warning ("unsupported key type: %d!", key_id);
72       return (u16) ~ 0;
73     }
74   return (u16) ~ 0;
75 }
76
77 static const EVP_MD *
78 get_encrypt_fcn (lisp_key_type_t key_id)
79 {
80   switch (key_id)
81     {
82     case HMAC_SHA_1_96:
83       return EVP_sha1 ();
84     case HMAC_SHA_256_128:
85       return EVP_sha256 ();
86     default:
87       clib_warning ("unsupported encryption key type: %d!", key_id);
88       break;
89     }
90   return 0;
91 }
92
93 static int
94 queue_map_request (gid_address_t * seid, gid_address_t * deid,
95                    u8 smr_invoked, u8 is_resend);
96
97 ip_interface_address_t *
98 ip_interface_get_first_interface_address (ip_lookup_main_t * lm,
99                                           u32 sw_if_index, u8 loop)
100 {
101   vnet_main_t *vnm = vnet_get_main ();
102   vnet_sw_interface_t *swif = vnet_get_sw_interface (vnm, sw_if_index);
103   if (loop && swif->flags & VNET_SW_INTERFACE_FLAG_UNNUMBERED)
104     sw_if_index = swif->unnumbered_sw_if_index;
105   u32 ia =
106     (vec_len ((lm)->if_address_pool_index_by_sw_if_index) > (sw_if_index)) ?
107     vec_elt ((lm)->if_address_pool_index_by_sw_if_index, (sw_if_index)) :
108     (u32) ~ 0;
109   return pool_elt_at_index ((lm)->if_address_pool, ia);
110 }
111
112 void *
113 ip_interface_get_first_address (ip_lookup_main_t * lm, u32 sw_if_index,
114                                 u8 version)
115 {
116   ip_interface_address_t *ia;
117
118   ia = ip_interface_get_first_interface_address (lm, sw_if_index, 1);
119   if (!ia)
120     return 0;
121   return ip_interface_address_get_address (lm, ia);
122 }
123
124 int
125 ip_interface_get_first_ip_address (lisp_cp_main_t * lcm, u32 sw_if_index,
126                                    u8 version, ip_address_t * result)
127 {
128   ip_lookup_main_t *lm;
129   void *addr;
130
131   lm = (version == IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
132   addr = ip_interface_get_first_address (lm, sw_if_index, version);
133   if (!addr)
134     return 0;
135
136   ip_address_set (result, addr, version);
137   return 1;
138 }
139
140 /**
141  * convert from a LISP address to a FIB prefix
142  */
143 void
144 ip_address_to_fib_prefix (const ip_address_t * addr, fib_prefix_t * prefix)
145 {
146   if (addr->version == IP4)
147     {
148       prefix->fp_len = 32;
149       prefix->fp_proto = FIB_PROTOCOL_IP4;
150       memset (&prefix->fp_addr.pad, 0, sizeof (prefix->fp_addr.pad));
151       memcpy (&prefix->fp_addr.ip4, &addr->ip, sizeof (prefix->fp_addr.ip4));
152     }
153   else
154     {
155       prefix->fp_len = 128;
156       prefix->fp_proto = FIB_PROTOCOL_IP6;
157       memcpy (&prefix->fp_addr.ip6, &addr->ip, sizeof (prefix->fp_addr.ip6));
158     }
159 }
160
161 /**
162  * convert from a LISP to a FIB prefix
163  */
164 void
165 ip_prefix_to_fib_prefix (const ip_prefix_t * ip_prefix,
166                          fib_prefix_t * fib_prefix)
167 {
168   ip_address_to_fib_prefix (&ip_prefix->addr, fib_prefix);
169   fib_prefix->fp_len = ip_prefix->len;
170 }
171
172 /**
173  * Find the sw_if_index of the interface that would be used to egress towards
174  * dst.
175  */
176 u32
177 ip_fib_get_egress_iface_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst)
178 {
179   fib_node_index_t fei;
180   fib_prefix_t prefix;
181
182   ip_address_to_fib_prefix (dst, &prefix);
183
184   fei = fib_table_lookup (0, &prefix);
185
186   return (fib_entry_get_resolving_interface (fei));
187 }
188
189 /**
190  * Find first IP of the interface that would be used to egress towards dst.
191  * Returns 1 if the address is found 0 otherwise.
192  */
193 int
194 ip_fib_get_first_egress_ip_for_dst (lisp_cp_main_t * lcm, ip_address_t * dst,
195                                     ip_address_t * result)
196 {
197   u32 si;
198   ip_lookup_main_t *lm;
199   void *addr = 0;
200   u8 ipver;
201
202   ASSERT (result != 0);
203
204   ipver = ip_addr_version (dst);
205
206   lm = (ipver == IP4) ? &lcm->im4->lookup_main : &lcm->im6->lookup_main;
207   si = ip_fib_get_egress_iface_for_dst (lcm, dst);
208
209   if ((u32) ~ 0 == si)
210     return 0;
211
212   /* find the first ip address */
213   addr = ip_interface_get_first_address (lm, si, ipver);
214   if (0 == addr)
215     return 0;
216
217   ip_address_set (result, addr, ipver);
218   return 1;
219 }
220
221 static int
222 dp_add_del_iface (lisp_cp_main_t * lcm, u32 vni, u8 is_l2, u8 is_add)
223 {
224   uword *dp_table;
225
226   if (!is_l2)
227     {
228       dp_table = hash_get (lcm->table_id_by_vni, vni);
229
230       if (!dp_table)
231         {
232           clib_warning ("vni %d not associated to a vrf!", vni);
233           return VNET_API_ERROR_INVALID_VALUE;
234         }
235     }
236   else
237     {
238       dp_table = hash_get (lcm->bd_id_by_vni, vni);
239       if (!dp_table)
240         {
241           clib_warning ("vni %d not associated to a bridge domain!", vni);
242           return VNET_API_ERROR_INVALID_VALUE;
243         }
244     }
245
246   /* enable/disable data-plane interface */
247   if (is_add)
248     {
249       if (is_l2)
250         lisp_gpe_tenant_l2_iface_add_or_lock (vni, dp_table[0]);
251       else
252         lisp_gpe_tenant_l3_iface_add_or_lock (vni, dp_table[0]);
253     }
254   else
255     {
256       if (is_l2)
257         lisp_gpe_tenant_l2_iface_unlock (vni);
258       else
259         lisp_gpe_tenant_l3_iface_unlock (vni);
260     }
261
262   return 0;
263 }
264
265 static void
266 dp_del_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index)
267 {
268   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
269   fwd_entry_t *fe = 0;
270   uword *feip = 0;
271   memset (a, 0, sizeof (*a));
272
273   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
274   if (!feip)
275     return;
276
277   fe = pool_elt_at_index (lcm->fwd_entry_pool, feip[0]);
278
279   /* delete dp fwd entry */
280   u32 sw_if_index;
281   a->is_add = 0;
282   a->locator_pairs = fe->locator_pairs;
283   a->vni = gid_address_vni (&fe->reid);
284   gid_address_copy (&a->rmt_eid, &fe->reid);
285   if (fe->is_src_dst)
286     gid_address_copy (&a->lcl_eid, &fe->leid);
287
288   vnet_lisp_del_fwd_stats (a, feip[0]);
289   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
290
291   /* delete entry in fwd table */
292   hash_unset (lcm->fwd_entry_by_mapping_index, dst_map_index);
293   vec_free (fe->locator_pairs);
294   pool_put (lcm->fwd_entry_pool, fe);
295 }
296
297 /**
298  * Finds first remote locator with best (lowest) priority that has a local
299  * peer locator with an underlying route to it.
300  *
301  */
302 static u32
303 get_locator_pairs (lisp_cp_main_t * lcm, mapping_t * lcl_map,
304                    mapping_t * rmt_map, locator_pair_t ** locator_pairs)
305 {
306   u32 i, limitp = 0, li, found = 0, esi;
307   locator_set_t *rmt_ls, *lcl_ls;
308   ip_address_t _lcl_addr, *lcl_addr = &_lcl_addr;
309   locator_t *lp, *rmt = 0;
310   uword *checked = 0;
311   locator_pair_t pair;
312
313   rmt_ls =
314     pool_elt_at_index (lcm->locator_set_pool, rmt_map->locator_set_index);
315   lcl_ls =
316     pool_elt_at_index (lcm->locator_set_pool, lcl_map->locator_set_index);
317
318   if (!rmt_ls || vec_len (rmt_ls->locator_indices) == 0)
319     return 0;
320
321   while (1)
322     {
323       rmt = 0;
324
325       /* find unvisited remote locator with best priority */
326       for (i = 0; i < vec_len (rmt_ls->locator_indices); i++)
327         {
328           if (0 != hash_get (checked, i))
329             continue;
330
331           li = vec_elt (rmt_ls->locator_indices, i);
332           lp = pool_elt_at_index (lcm->locator_pool, li);
333
334           /* we don't support non-IP locators for now */
335           if (gid_address_type (&lp->address) != GID_ADDR_IP_PREFIX)
336             continue;
337
338           if ((found && lp->priority == limitp)
339               || (!found && lp->priority >= limitp))
340             {
341               rmt = lp;
342
343               /* don't search for locators with lower priority and don't
344                * check this locator again*/
345               limitp = lp->priority;
346               hash_set (checked, i, 1);
347               break;
348             }
349         }
350       /* check if a local locator with a route to remote locator exists */
351       if (rmt != 0)
352         {
353           /* find egress sw_if_index for rmt locator */
354           esi =
355             ip_fib_get_egress_iface_for_dst (lcm,
356                                              &gid_address_ip (&rmt->address));
357           if ((u32) ~ 0 == esi)
358             continue;
359
360           for (i = 0; i < vec_len (lcl_ls->locator_indices); i++)
361             {
362               li = vec_elt (lcl_ls->locator_indices, i);
363               locator_t *sl = pool_elt_at_index (lcm->locator_pool, li);
364
365               /* found local locator with the needed sw_if_index */
366               if (sl->sw_if_index == esi)
367                 {
368                   /* and it has an address */
369                   if (0 == ip_interface_get_first_ip_address (lcm,
370                                                               sl->sw_if_index,
371                                                               gid_address_ip_version
372                                                               (&rmt->address),
373                                                               lcl_addr))
374                     continue;
375
376                   memset (&pair, 0, sizeof (pair));
377                   ip_address_copy (&pair.rmt_loc,
378                                    &gid_address_ip (&rmt->address));
379                   ip_address_copy (&pair.lcl_loc, lcl_addr);
380                   pair.weight = rmt->weight;
381                   pair.priority = rmt->priority;
382                   vec_add1 (locator_pairs[0], pair);
383                   found = 1;
384                 }
385             }
386         }
387       else
388         break;
389     }
390
391   hash_free (checked);
392   return found;
393 }
394
395 static void
396 gid_address_sd_to_flat (gid_address_t * dst, gid_address_t * src,
397                         fid_address_t * fid)
398 {
399   ASSERT (GID_ADDR_SRC_DST == gid_address_type (src));
400
401   dst[0] = src[0];
402
403   switch (fid_addr_type (fid))
404     {
405     case FID_ADDR_IP_PREF:
406       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
407       gid_address_ippref (dst) = fid_addr_ippref (fid);
408       break;
409     case FID_ADDR_MAC:
410       gid_address_type (dst) = GID_ADDR_MAC;
411       mac_copy (gid_address_mac (dst), fid_addr_mac (fid));
412       break;
413     default:
414       clib_warning ("Unsupported fid type %d!", fid_addr_type (fid));
415       break;
416     }
417 }
418
419 u8
420 vnet_lisp_map_register_state_get (void)
421 {
422   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
423   return lcm->map_registering;
424 }
425
426 u8
427 vnet_lisp_rloc_probe_state_get (void)
428 {
429   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
430   return lcm->rloc_probing;
431 }
432
433 static void
434 dp_add_fwd_entry (lisp_cp_main_t * lcm, u32 src_map_index, u32 dst_map_index)
435 {
436   vnet_lisp_gpe_add_del_fwd_entry_args_t _a, *a = &_a;
437   gid_address_t *rmt_eid, *lcl_eid;
438   mapping_t *lcl_map, *rmt_map;
439   u32 sw_if_index;
440   uword *feip = 0, *dpid;
441   fwd_entry_t *fe;
442   u8 type, is_src_dst = 0;
443   int rv;
444
445   memset (a, 0, sizeof (*a));
446
447   /* remove entry if it already exists */
448   feip = hash_get (lcm->fwd_entry_by_mapping_index, dst_map_index);
449   if (feip)
450     dp_del_fwd_entry (lcm, src_map_index, dst_map_index);
451
452   /*
453    * Determine local mapping and eid
454    */
455   if (lcm->lisp_pitr)
456     lcl_map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
457   else
458     lcl_map = pool_elt_at_index (lcm->mapping_pool, src_map_index);
459   lcl_eid = &lcl_map->eid;
460
461   /*
462    * Determine remote mapping and eid
463    */
464   rmt_map = pool_elt_at_index (lcm->mapping_pool, dst_map_index);
465   rmt_eid = &rmt_map->eid;
466
467   /*
468    * Build and insert data plane forwarding entry
469    */
470   a->is_add = 1;
471
472   if (MR_MODE_SRC_DST == lcm->map_request_mode)
473     {
474       if (GID_ADDR_SRC_DST == gid_address_type (rmt_eid))
475         {
476           gid_address_sd_to_flat (&a->rmt_eid, rmt_eid,
477                                   &gid_address_sd_dst (rmt_eid));
478           gid_address_sd_to_flat (&a->lcl_eid, rmt_eid,
479                                   &gid_address_sd_src (rmt_eid));
480         }
481       else
482         {
483           gid_address_copy (&a->rmt_eid, rmt_eid);
484           gid_address_copy (&a->lcl_eid, lcl_eid);
485         }
486       is_src_dst = 1;
487     }
488   else
489     gid_address_copy (&a->rmt_eid, rmt_eid);
490
491   a->vni = gid_address_vni (&a->rmt_eid);
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   vnet_lisp_gpe_add_del_fwd_entry (a, &sw_if_index);
535
536   /* add tunnel to fwd entry table XXX check return value from DP insertion */
537   pool_get (lcm->fwd_entry_pool, fe);
538   fe->locator_pairs = a->locator_pairs;
539   gid_address_copy (&fe->reid, &a->rmt_eid);
540
541   if (is_src_dst)
542     gid_address_copy (&fe->leid, &a->lcl_eid);
543   else
544     gid_address_copy (&fe->leid, lcl_eid);
545
546   fe->is_src_dst = is_src_dst;
547   hash_set (lcm->fwd_entry_by_mapping_index, dst_map_index,
548             fe - lcm->fwd_entry_pool);
549 }
550
551 typedef struct
552 {
553   u32 si;
554   u32 di;
555 } fwd_entry_mt_arg_t;
556
557 static void *
558 dp_add_fwd_entry_thread_fn (void *arg)
559 {
560   fwd_entry_mt_arg_t *a = arg;
561   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
562   dp_add_fwd_entry (lcm, a->si, a->di);
563   return 0;
564 }
565
566 static int
567 dp_add_fwd_entry_from_mt (u32 si, u32 di)
568 {
569   fwd_entry_mt_arg_t a;
570
571   memset (&a, 0, sizeof (a));
572   a.si = si;
573   a.di = di;
574
575   vl_api_rpc_call_main_thread (dp_add_fwd_entry_thread_fn,
576                                (u8 *) & a, sizeof (a));
577   return 0;
578 }
579
580 /**
581  * Returns vector of adjacencies.
582  *
583  * The caller must free the vector returned by this function.
584  *
585  * @param vni virtual network identifier
586  * @return vector of adjacencies
587  */
588 lisp_adjacency_t *
589 vnet_lisp_adjacencies_get_by_vni (u32 vni)
590 {
591   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
592   fwd_entry_t *fwd;
593   lisp_adjacency_t *adjs = 0, adj;
594
595   /* *INDENT-OFF* */
596   pool_foreach(fwd, lcm->fwd_entry_pool,
597   ({
598     if (gid_address_vni (&fwd->reid) != vni)
599       continue;
600
601     gid_address_copy (&adj.reid, &fwd->reid);
602     gid_address_copy (&adj.leid, &fwd->leid);
603     vec_add1 (adjs, adj);
604   }));
605   /* *INDENT-ON* */
606
607   return adjs;
608 }
609
610 static lisp_msmr_t *
611 get_map_server (ip_address_t * a)
612 {
613   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
614   lisp_msmr_t *m;
615
616   vec_foreach (m, lcm->map_servers)
617   {
618     if (!ip_address_cmp (&m->address, a))
619       {
620         return m;
621       }
622   }
623   return 0;
624 }
625
626 static lisp_msmr_t *
627 get_map_resolver (ip_address_t * a)
628 {
629   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
630   lisp_msmr_t *m;
631
632   vec_foreach (m, lcm->map_resolvers)
633   {
634     if (!ip_address_cmp (&m->address, a))
635       {
636         return m;
637       }
638   }
639   return 0;
640 }
641
642 int
643 vnet_lisp_add_del_map_server (ip_address_t * addr, u8 is_add)
644 {
645   u32 i;
646   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
647   lisp_msmr_t _ms, *ms = &_ms;
648
649   if (vnet_lisp_enable_disable_status () == 0)
650     {
651       clib_warning ("LISP is disabled!");
652       return VNET_API_ERROR_LISP_DISABLED;
653     }
654
655   if (is_add)
656     {
657       if (get_map_server (addr))
658         {
659           clib_warning ("map-server %U already exists!", format_ip_address,
660                         addr);
661           return -1;
662         }
663
664       memset (ms, 0, sizeof (*ms));
665       ip_address_copy (&ms->address, addr);
666       vec_add1 (lcm->map_servers, ms[0]);
667     }
668   else
669     {
670       for (i = 0; i < vec_len (lcm->map_servers); i++)
671         {
672           ms = vec_elt_at_index (lcm->map_servers, i);
673           if (!ip_address_cmp (&ms->address, addr))
674             {
675               vec_del1 (lcm->map_servers, i);
676               break;
677             }
678         }
679     }
680
681   return 0;
682 }
683
684 /**
685  * Add/remove mapping to/from map-cache. Overwriting not allowed.
686  */
687 int
688 vnet_lisp_map_cache_add_del (vnet_lisp_add_del_mapping_args_t * a,
689                              u32 * map_index_result)
690 {
691   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
692   u32 mi, *map_indexp, map_index, i;
693   mapping_t *m, *old_map;
694   u32 **eid_indexes;
695
696   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->eid);
697   old_map = mi != ~0 ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
698   if (a->is_add)
699     {
700       /* TODO check if overwriting and take appropriate actions */
701       if (mi != GID_LOOKUP_MISS && !gid_address_cmp (&old_map->eid, &a->eid))
702         {
703           clib_warning ("eid %U found in the eid-table", format_gid_address,
704                         &a->eid);
705           return VNET_API_ERROR_VALUE_EXIST;
706         }
707
708       pool_get (lcm->mapping_pool, m);
709       gid_address_copy (&m->eid, &a->eid);
710       m->locator_set_index = a->locator_set_index;
711       m->ttl = a->ttl;
712       m->action = a->action;
713       m->local = a->local;
714       m->is_static = a->is_static;
715       m->key = vec_dup (a->key);
716       m->key_id = a->key_id;
717
718       map_index = m - lcm->mapping_pool;
719       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, map_index,
720                               1);
721
722       if (pool_is_free_index (lcm->locator_set_pool, a->locator_set_index))
723         {
724           clib_warning ("Locator set with index %d doesn't exist",
725                         a->locator_set_index);
726           return VNET_API_ERROR_INVALID_VALUE;
727         }
728
729       /* add eid to list of eids supported by locator-set */
730       vec_validate (lcm->locator_set_to_eids, a->locator_set_index);
731       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
732                                       a->locator_set_index);
733       vec_add1 (eid_indexes[0], map_index);
734
735       if (a->local)
736         {
737           /* mark as local */
738           vec_add1 (lcm->local_mappings_indexes, map_index);
739         }
740       map_index_result[0] = map_index;
741     }
742   else
743     {
744       if (mi == GID_LOOKUP_MISS)
745         {
746           clib_warning ("eid %U not found in the eid-table",
747                         format_gid_address, &a->eid);
748           return VNET_API_ERROR_INVALID_VALUE;
749         }
750
751       /* clear locator-set to eids binding */
752       eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids,
753                                       a->locator_set_index);
754       for (i = 0; i < vec_len (eid_indexes[0]); i++)
755         {
756           map_indexp = vec_elt_at_index (eid_indexes[0], i);
757           if (map_indexp[0] == mi)
758             break;
759         }
760       vec_del1 (eid_indexes[0], i);
761
762       /* remove local mark if needed */
763       m = pool_elt_at_index (lcm->mapping_pool, mi);
764       if (m->local)
765         {
766           u32 k, *lm_indexp;
767           for (k = 0; k < vec_len (lcm->local_mappings_indexes); k++)
768             {
769               lm_indexp = vec_elt_at_index (lcm->local_mappings_indexes, k);
770               if (lm_indexp[0] == mi)
771                 break;
772             }
773           vec_del1 (lcm->local_mappings_indexes, k);
774         }
775
776       /* remove mapping from dictionary */
777       gid_dictionary_add_del (&lcm->mapping_index_by_gid, &a->eid, 0, 0);
778       gid_address_free (&m->eid);
779       pool_put_index (lcm->mapping_pool, mi);
780     }
781
782   return 0;
783 }
784
785 /**
786  *  Add/update/delete mapping to/in/from map-cache.
787  */
788 int
789 vnet_lisp_add_del_local_mapping (vnet_lisp_add_del_mapping_args_t * a,
790                                  u32 * map_index_result)
791 {
792   uword *dp_table = 0;
793   u32 vni;
794   u8 type;
795
796   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
797
798   if (vnet_lisp_enable_disable_status () == 0)
799     {
800       clib_warning ("LISP is disabled!");
801       return VNET_API_ERROR_LISP_DISABLED;
802     }
803
804   vni = gid_address_vni (&a->eid);
805   type = gid_address_type (&a->eid);
806   if (GID_ADDR_IP_PREFIX == type)
807     dp_table = hash_get (lcm->table_id_by_vni, vni);
808   else if (GID_ADDR_MAC == type)
809     dp_table = hash_get (lcm->bd_id_by_vni, vni);
810
811   if (!dp_table)
812     {
813       clib_warning ("vni %d not associated to a %s!", vni,
814                     GID_ADDR_IP_PREFIX == type ? "vrf" : "bd");
815       return VNET_API_ERROR_INVALID_VALUE;
816     }
817
818   /* store/remove mapping from map-cache */
819   return vnet_lisp_map_cache_add_del (a, map_index_result);
820 }
821
822 int
823 vnet_lisp_eid_table_map (u32 vni, u32 dp_id, u8 is_l2, u8 is_add)
824 {
825   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
826   uword *dp_idp, *vnip, **dp_table_by_vni, **vni_by_dp_table;
827
828   if (vnet_lisp_enable_disable_status () == 0)
829     {
830       clib_warning ("LISP is disabled!");
831       return -1;
832     }
833
834   dp_table_by_vni = is_l2 ? &lcm->bd_id_by_vni : &lcm->table_id_by_vni;
835   vni_by_dp_table = is_l2 ? &lcm->vni_by_bd_id : &lcm->vni_by_table_id;
836
837   if (!is_l2 && (vni == 0 || dp_id == 0))
838     {
839       clib_warning ("can't add/del default vni-vrf mapping!");
840       return -1;
841     }
842
843   dp_idp = hash_get (dp_table_by_vni[0], vni);
844   vnip = hash_get (vni_by_dp_table[0], dp_id);
845
846   if (is_add)
847     {
848       if (dp_idp || vnip)
849         {
850           clib_warning ("vni %d or vrf %d already used in vrf/vni "
851                         "mapping!", vni, dp_id);
852           return -1;
853         }
854       hash_set (dp_table_by_vni[0], vni, dp_id);
855       hash_set (vni_by_dp_table[0], dp_id, vni);
856
857       /* create dp iface */
858       dp_add_del_iface (lcm, vni, is_l2, 1);
859     }
860   else
861     {
862       if (!dp_idp || !vnip)
863         {
864           clib_warning ("vni %d or vrf %d not used in any vrf/vni! "
865                         "mapping!", vni, dp_id);
866           return -1;
867         }
868       hash_unset (dp_table_by_vni[0], vni);
869       hash_unset (vni_by_dp_table[0], dp_id);
870
871       /* remove dp iface */
872       dp_add_del_iface (lcm, vni, is_l2, 0);
873     }
874   return 0;
875
876 }
877
878 /* return 0 if the two locator sets are identical 1 otherwise */
879 static u8
880 compare_locators (lisp_cp_main_t * lcm, u32 * old_ls_indexes,
881                   locator_t * new_locators)
882 {
883   u32 i, old_li;
884   locator_t *old_loc, *new_loc;
885
886   if (vec_len (old_ls_indexes) != vec_len (new_locators))
887     return 1;
888
889   for (i = 0; i < vec_len (new_locators); i++)
890     {
891       old_li = vec_elt (old_ls_indexes, i);
892       old_loc = pool_elt_at_index (lcm->locator_pool, old_li);
893
894       new_loc = vec_elt_at_index (new_locators, i);
895
896       if (locator_cmp (old_loc, new_loc))
897         return 1;
898     }
899   return 0;
900 }
901
902 typedef struct
903 {
904   u8 is_negative;
905   void *lcm;
906   gid_address_t *eids_to_be_deleted;
907 } remove_mapping_args_t;
908
909 /**
910  * Callback invoked when a sub-prefix is found
911  */
912 static void
913 remove_mapping_if_needed (u32 mi, void *arg)
914 {
915   u8 delete = 0;
916   remove_mapping_args_t *a = arg;
917   lisp_cp_main_t *lcm = a->lcm;
918   mapping_t *m;
919   locator_set_t *ls;
920
921   m = pool_elt_at_index (lcm->mapping_pool, mi);
922   if (!m)
923     return;
924
925   ls = pool_elt_at_index (lcm->locator_set_pool, m->locator_set_index);
926
927   if (a->is_negative)
928     {
929       if (0 != vec_len (ls->locator_indices))
930         delete = 1;
931     }
932   else
933     {
934       if (0 == vec_len (ls->locator_indices))
935         delete = 1;
936     }
937
938   if (delete)
939     vec_add1 (a->eids_to_be_deleted, m->eid);
940 }
941
942 /**
943  * This function searches map cache and looks for IP prefixes that are subset
944  * of the provided one. If such prefix is found depending on 'is_negative'
945  * it does follows:
946  *
947  * 1) if is_negative is true and found prefix points to positive mapping,
948  *    then the mapping is removed
949  * 2) if is_negative is false and found prefix points to negative mapping,
950  *    then the mapping is removed
951  */
952 static void
953 remove_overlapping_sub_prefixes (lisp_cp_main_t * lcm, gid_address_t * eid,
954                                  u8 is_negative)
955 {
956   gid_address_t *e;
957   remove_mapping_args_t a;
958
959   memset (&a, 0, sizeof (a));
960
961   /* do this only in src/dst mode ... */
962   if (MR_MODE_SRC_DST != lcm->map_request_mode)
963     return;
964
965   /* ... and  only for IP prefix */
966   if (GID_ADDR_SRC_DST != gid_address_type (eid)
967       || (FID_ADDR_IP_PREF != gid_address_sd_dst_type (eid)))
968     return;
969
970   a.is_negative = is_negative;
971   a.lcm = lcm;
972
973   gid_dict_foreach_subprefix (&lcm->mapping_index_by_gid, eid,
974                               remove_mapping_if_needed, &a);
975
976   vec_foreach (e, a.eids_to_be_deleted)
977   {
978     vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
979
980     memset (adj_args, 0, sizeof (adj_args[0]));
981     gid_address_copy (&adj_args->reid, e);
982     adj_args->is_add = 0;
983     if (vnet_lisp_add_del_adjacency (adj_args))
984       clib_warning ("failed to del adjacency!");
985
986     vnet_lisp_add_del_mapping (e, 0, 0, 0, 0, 0 /* is add */ , 0, 0);
987   }
988
989   vec_free (a.eids_to_be_deleted);
990 }
991
992 static void
993 mapping_delete_timer (lisp_cp_main_t * lcm, u32 mi)
994 {
995   timing_wheel_delete (&lcm->wheel, mi);
996 }
997
998 static int
999 is_local_ip (lisp_cp_main_t * lcm, ip_address_t * addr)
1000 {
1001   fib_node_index_t fei;
1002   fib_prefix_t prefix;
1003   fib_entry_flag_t flags;
1004
1005   ip_address_to_fib_prefix (addr, &prefix);
1006
1007   fei = fib_table_lookup (0, &prefix);
1008   flags = fib_entry_get_flags (fei);
1009   return (FIB_ENTRY_FLAG_LOCAL & flags);
1010 }
1011
1012 /**
1013  * Adds/removes/updates mapping. Does not program forwarding.
1014  *
1015  * @param eid end-host identifier
1016  * @param rlocs vector of remote locators
1017  * @param action action for negative map-reply
1018  * @param is_add add mapping if non-zero, delete otherwise
1019  * @param res_map_index the map-index that was created/updated/removed. It is
1020  *                      set to ~0 if no action is taken.
1021  * @param is_static used for distinguishing between statically learned
1022                     remote mappings and mappings obtained from MR
1023  * @return return code
1024  */
1025 int
1026 vnet_lisp_add_del_mapping (gid_address_t * eid, locator_t * rlocs, u8 action,
1027                            u8 authoritative, u32 ttl, u8 is_add, u8 is_static,
1028                            u32 * res_map_index)
1029 {
1030   vnet_lisp_add_del_mapping_args_t _m_args, *m_args = &_m_args;
1031   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1032   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1033   u32 mi, ls_index = 0, dst_map_index;
1034   mapping_t *old_map;
1035   locator_t *loc;
1036
1037   if (vnet_lisp_enable_disable_status () == 0)
1038     {
1039       clib_warning ("LISP is disabled!");
1040       return VNET_API_ERROR_LISP_DISABLED;
1041     }
1042
1043   if (res_map_index)
1044     res_map_index[0] = ~0;
1045
1046   memset (m_args, 0, sizeof (m_args[0]));
1047   memset (ls_args, 0, sizeof (ls_args[0]));
1048
1049   ls_args->locators = rlocs;
1050
1051   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, eid);
1052   old_map = ((u32) ~ 0 != mi) ? pool_elt_at_index (lcm->mapping_pool, mi) : 0;
1053
1054   if (is_add)
1055     {
1056       /* check if none of the locators match localy configured address */
1057       vec_foreach (loc, rlocs)
1058       {
1059         ip_prefix_t *p = &gid_address_ippref (&loc->address);
1060         if (is_local_ip (lcm, &ip_prefix_addr (p)))
1061           {
1062             clib_warning ("RLOC %U matches a local address!",
1063                           format_gid_address, &loc->address);
1064             return VNET_API_ERROR_LISP_RLOC_LOCAL;
1065           }
1066       }
1067
1068       /* overwrite: if mapping already exists, decide if locators should be
1069        * updated and be done */
1070       if (old_map && gid_address_cmp (&old_map->eid, eid) == 0)
1071         {
1072           if (!is_static && (old_map->is_static || old_map->local))
1073             {
1074               /* do not overwrite local or static remote mappings */
1075               clib_warning ("mapping %U rejected due to collision with local "
1076                             "or static remote mapping!", format_gid_address,
1077                             eid);
1078               return 0;
1079             }
1080
1081           locator_set_t *old_ls;
1082
1083           /* update mapping attributes */
1084           old_map->action = action;
1085           old_map->authoritative = authoritative;
1086           old_map->ttl = ttl;
1087
1088           old_ls = pool_elt_at_index (lcm->locator_set_pool,
1089                                       old_map->locator_set_index);
1090           if (compare_locators (lcm, old_ls->locator_indices,
1091                                 ls_args->locators))
1092             {
1093               /* set locator-set index to overwrite */
1094               ls_args->is_add = 1;
1095               ls_args->index = old_map->locator_set_index;
1096               vnet_lisp_add_del_locator_set (ls_args, 0);
1097               if (res_map_index)
1098                 res_map_index[0] = mi;
1099             }
1100         }
1101       /* new mapping */
1102       else
1103         {
1104           remove_overlapping_sub_prefixes (lcm, eid, 0 == ls_args->locators);
1105
1106           ls_args->is_add = 1;
1107           ls_args->index = ~0;
1108
1109           vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1110
1111           /* add mapping */
1112           gid_address_copy (&m_args->eid, eid);
1113           m_args->is_add = 1;
1114           m_args->action = action;
1115           m_args->locator_set_index = ls_index;
1116           m_args->is_static = is_static;
1117           m_args->ttl = ttl;
1118           vnet_lisp_map_cache_add_del (m_args, &dst_map_index);
1119
1120           if (res_map_index)
1121             res_map_index[0] = dst_map_index;
1122         }
1123     }
1124   else
1125     {
1126       if (old_map == 0 || gid_address_cmp (&old_map->eid, eid) != 0)
1127         {
1128           clib_warning ("cannot delete mapping for eid %U",
1129                         format_gid_address, eid);
1130           return -1;
1131         }
1132
1133       m_args->is_add = 0;
1134       gid_address_copy (&m_args->eid, eid);
1135       m_args->locator_set_index = old_map->locator_set_index;
1136
1137       /* delete mapping associated from map-cache */
1138       vnet_lisp_map_cache_add_del (m_args, 0);
1139
1140       ls_args->is_add = 0;
1141       ls_args->index = old_map->locator_set_index;
1142       /* delete locator set */
1143       vnet_lisp_add_del_locator_set (ls_args, 0);
1144
1145       /* delete timer associated to the mapping if any */
1146       if (old_map->timer_set)
1147         mapping_delete_timer (lcm, mi);
1148
1149       /* return old mapping index */
1150       if (res_map_index)
1151         res_map_index[0] = mi;
1152     }
1153
1154   /* success */
1155   return 0;
1156 }
1157
1158 int
1159 vnet_lisp_clear_all_remote_adjacencies (void)
1160 {
1161   int rv = 0;
1162   u32 mi, *map_indices = 0, *map_indexp;
1163   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1164   vnet_lisp_add_del_mapping_args_t _dm_args, *dm_args = &_dm_args;
1165   vnet_lisp_add_del_locator_set_args_t _ls, *ls = &_ls;
1166
1167   /* *INDENT-OFF* */
1168   pool_foreach_index (mi, lcm->mapping_pool,
1169   ({
1170     vec_add1 (map_indices, mi);
1171   }));
1172   /* *INDENT-ON* */
1173
1174   vec_foreach (map_indexp, map_indices)
1175   {
1176     mapping_t *map = pool_elt_at_index (lcm->mapping_pool, map_indexp[0]);
1177     if (!map->local)
1178       {
1179         dp_del_fwd_entry (lcm, 0, map_indexp[0]);
1180
1181         dm_args->is_add = 0;
1182         gid_address_copy (&dm_args->eid, &map->eid);
1183         dm_args->locator_set_index = map->locator_set_index;
1184
1185         /* delete mapping associated to fwd entry */
1186         vnet_lisp_map_cache_add_del (dm_args, 0);
1187
1188         ls->is_add = 0;
1189         ls->local = 0;
1190         ls->index = map->locator_set_index;
1191         /* delete locator set */
1192         rv = vnet_lisp_add_del_locator_set (ls, 0);
1193         if (rv != 0)
1194           goto cleanup;
1195       }
1196   }
1197
1198 cleanup:
1199   if (map_indices)
1200     vec_free (map_indices);
1201   return rv;
1202 }
1203
1204 /**
1205  * Adds adjacency or removes forwarding entry associated to remote mapping.
1206  * Note that adjacencies are not stored, they only result in forwarding entries
1207  * being created.
1208  */
1209 int
1210 vnet_lisp_add_del_adjacency (vnet_lisp_add_del_adjacency_args_t * a)
1211 {
1212   lisp_cp_main_t *lcm = &lisp_control_main;
1213   u32 local_mi, remote_mi = ~0;
1214
1215   if (vnet_lisp_enable_disable_status () == 0)
1216     {
1217       clib_warning ("LISP is disabled!");
1218       return VNET_API_ERROR_LISP_DISABLED;
1219     }
1220
1221   remote_mi = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid,
1222                                         &a->reid, &a->leid);
1223   if (GID_LOOKUP_MISS == remote_mi)
1224     {
1225       clib_warning ("Remote eid %U not found. Cannot add adjacency!",
1226                     format_gid_address, &a->reid);
1227
1228       return -1;
1229     }
1230
1231   if (a->is_add)
1232     {
1233       /* check if source eid has an associated mapping. If pitr mode is on,
1234        * just use the pitr's mapping */
1235       local_mi = lcm->lisp_pitr ? lcm->pitr_map_index :
1236         gid_dictionary_lookup (&lcm->mapping_index_by_gid, &a->leid);
1237
1238       if (GID_LOOKUP_MISS == local_mi)
1239         {
1240           clib_warning ("Local eid %U not found. Cannot add adjacency!",
1241                         format_gid_address, &a->leid);
1242
1243           return -1;
1244         }
1245
1246       /* update forwarding */
1247       dp_add_fwd_entry (lcm, local_mi, remote_mi);
1248     }
1249   else
1250     dp_del_fwd_entry (lcm, 0, remote_mi);
1251
1252   return 0;
1253 }
1254
1255 int
1256 vnet_lisp_set_map_request_mode (u8 mode)
1257 {
1258   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1259
1260   if (vnet_lisp_enable_disable_status () == 0)
1261     {
1262       clib_warning ("LISP is disabled!");
1263       return VNET_API_ERROR_LISP_DISABLED;
1264     }
1265
1266   if (mode >= _MR_MODE_MAX)
1267     {
1268       clib_warning ("Invalid LISP map request mode %d!", mode);
1269       return VNET_API_ERROR_INVALID_ARGUMENT;
1270     }
1271
1272   lcm->map_request_mode = mode;
1273   return 0;
1274 }
1275
1276 int
1277 vnet_lisp_pitr_set_locator_set (u8 * locator_set_name, u8 is_add)
1278 {
1279   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1280   u32 locator_set_index = ~0;
1281   mapping_t *m;
1282   uword *p;
1283
1284   if (vnet_lisp_enable_disable_status () == 0)
1285     {
1286       clib_warning ("LISP is disabled!");
1287       return VNET_API_ERROR_LISP_DISABLED;
1288     }
1289
1290   p = hash_get_mem (lcm->locator_set_index_by_name, locator_set_name);
1291   if (!p)
1292     {
1293       clib_warning ("locator-set %v doesn't exist", locator_set_name);
1294       return -1;
1295     }
1296   locator_set_index = p[0];
1297
1298   if (is_add)
1299     {
1300       pool_get (lcm->mapping_pool, m);
1301       m->locator_set_index = locator_set_index;
1302       m->local = 1;
1303       m->pitr_set = 1;
1304       lcm->pitr_map_index = m - lcm->mapping_pool;
1305
1306       /* enable pitr mode */
1307       lcm->lisp_pitr = 1;
1308     }
1309   else
1310     {
1311       /* remove pitr mapping */
1312       pool_put_index (lcm->mapping_pool, lcm->pitr_map_index);
1313
1314       /* disable pitr mode */
1315       lcm->lisp_pitr = 0;
1316     }
1317   return 0;
1318 }
1319
1320 /**
1321  * Configure Proxy-ETR
1322  *
1323  * @param ip PETR's IP address
1324  * @param is_add Flag that indicates if this is an addition or removal
1325  *
1326  * return 0 on success
1327  */
1328 int
1329 vnet_lisp_use_petr (ip_address_t * ip, u8 is_add)
1330 {
1331   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1332   u32 ls_index = ~0;
1333   mapping_t *m;
1334   vnet_lisp_add_del_locator_set_args_t _ls_args, *ls_args = &_ls_args;
1335   locator_t loc;
1336
1337   if (vnet_lisp_enable_disable_status () == 0)
1338     {
1339       clib_warning ("LISP is disabled!");
1340       return VNET_API_ERROR_LISP_DISABLED;
1341     }
1342
1343   memset (ls_args, 0, sizeof (*ls_args));
1344
1345   if (is_add)
1346     {
1347       /* Create dummy petr locator-set */
1348       memset (&loc, 0, sizeof (loc));
1349       gid_address_from_ip (&loc.address, ip);
1350       loc.priority = 1;
1351       loc.state = loc.weight = 1;
1352       loc.local = 0;
1353
1354       ls_args->is_add = 1;
1355       ls_args->index = ~0;
1356       vec_add1 (ls_args->locators, loc);
1357       vnet_lisp_add_del_locator_set (ls_args, &ls_index);
1358
1359       /* Add petr mapping */
1360       pool_get (lcm->mapping_pool, m);
1361       m->locator_set_index = ls_index;
1362       lcm->petr_map_index = m - lcm->mapping_pool;
1363
1364       /* Enable use-petr */
1365       lcm->flags |= LISP_FLAG_USE_PETR;
1366     }
1367   else
1368     {
1369       m = pool_elt_at_index (lcm->mapping_pool, lcm->petr_map_index);
1370
1371       /* Remove petr locator */
1372       ls_args->is_add = 0;
1373       ls_args->index = m->locator_set_index;
1374       vnet_lisp_add_del_locator_set (ls_args, 0);
1375
1376       /* Remove petr mapping */
1377       pool_put_index (lcm->mapping_pool, lcm->petr_map_index);
1378
1379       /* Disable use-petr */
1380       lcm->flags &= ~LISP_FLAG_USE_PETR;
1381     }
1382   return 0;
1383 }
1384
1385 /* cleans locator to locator-set data and removes locators not part of
1386  * any locator-set */
1387 static void
1388 clean_locator_to_locator_set (lisp_cp_main_t * lcm, u32 lsi)
1389 {
1390   u32 i, j, *loc_indexp, *ls_indexp, **ls_indexes, *to_be_deleted = 0;
1391   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool, lsi);
1392   for (i = 0; i < vec_len (ls->locator_indices); i++)
1393     {
1394       loc_indexp = vec_elt_at_index (ls->locator_indices, i);
1395       ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1396                                      loc_indexp[0]);
1397       for (j = 0; j < vec_len (ls_indexes[0]); j++)
1398         {
1399           ls_indexp = vec_elt_at_index (ls_indexes[0], j);
1400           if (ls_indexp[0] == lsi)
1401             break;
1402         }
1403
1404       /* delete index for removed locator-set */
1405       vec_del1 (ls_indexes[0], j);
1406
1407       /* delete locator if it's part of no locator-set */
1408       if (vec_len (ls_indexes[0]) == 0)
1409         {
1410           pool_put_index (lcm->locator_pool, loc_indexp[0]);
1411           vec_add1 (to_be_deleted, i);
1412         }
1413     }
1414
1415   if (to_be_deleted)
1416     {
1417       for (i = 0; i < vec_len (to_be_deleted); i++)
1418         {
1419           loc_indexp = vec_elt_at_index (to_be_deleted, i);
1420           vec_del1 (ls->locator_indices, loc_indexp[0]);
1421         }
1422       vec_free (to_be_deleted);
1423     }
1424 }
1425
1426 static inline uword *
1427 get_locator_set_index (vnet_lisp_add_del_locator_set_args_t * a, uword * p)
1428 {
1429   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1430
1431   ASSERT (a != NULL);
1432   ASSERT (p != NULL);
1433
1434   /* find locator-set */
1435   if (a->local)
1436     {
1437       p = hash_get_mem (lcm->locator_set_index_by_name, a->name);
1438     }
1439   else
1440     {
1441       *p = a->index;
1442     }
1443
1444   return p;
1445 }
1446
1447 static inline int
1448 is_locator_in_locator_set (lisp_cp_main_t * lcm, locator_set_t * ls,
1449                            locator_t * loc)
1450 {
1451   locator_t *itloc;
1452   u32 *locit;
1453
1454   ASSERT (ls != NULL);
1455   ASSERT (loc != NULL);
1456
1457   vec_foreach (locit, ls->locator_indices)
1458   {
1459     itloc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1460     if ((ls->local && itloc->sw_if_index == loc->sw_if_index) ||
1461         (!ls->local && !gid_address_cmp (&itloc->address, &loc->address)))
1462       {
1463         clib_warning ("Duplicate locator");
1464         return VNET_API_ERROR_VALUE_EXIST;
1465       }
1466   }
1467
1468   return 0;
1469 }
1470
1471 static inline void
1472 remove_locator_from_locator_set (locator_set_t * ls, u32 * locit,
1473                                  u32 ls_index, u32 loc_id)
1474 {
1475   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1476   u32 **ls_indexes = NULL;
1477
1478   ASSERT (ls != NULL);
1479   ASSERT (locit != NULL);
1480
1481   ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets, locit[0]);
1482   pool_put_index (lcm->locator_pool, locit[0]);
1483   vec_del1 (ls->locator_indices, loc_id);
1484   vec_del1 (ls_indexes[0], ls_index);
1485 }
1486
1487 int
1488 vnet_lisp_add_del_locator (vnet_lisp_add_del_locator_set_args_t * a,
1489                            locator_set_t * ls, u32 * ls_result)
1490 {
1491   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1492   locator_t *loc = NULL, *itloc = NULL;
1493   uword _p = (u32) ~ 0, *p = &_p;
1494   u32 loc_index = ~0, ls_index = ~0, *locit = NULL, **ls_indexes = NULL;
1495   u32 loc_id = ~0;
1496   int ret = 0;
1497
1498   ASSERT (a != NULL);
1499
1500   if (vnet_lisp_enable_disable_status () == 0)
1501     {
1502       clib_warning ("LISP is disabled!");
1503       return VNET_API_ERROR_LISP_DISABLED;
1504     }
1505
1506   p = get_locator_set_index (a, p);
1507   if (!p)
1508     {
1509       clib_warning ("locator-set %v doesn't exist", a->name);
1510       return VNET_API_ERROR_INVALID_ARGUMENT;
1511     }
1512
1513   if (ls == 0)
1514     {
1515       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1516       if (!ls)
1517         {
1518           clib_warning ("locator-set %d to be overwritten doesn't exist!",
1519                         p[0]);
1520           return VNET_API_ERROR_INVALID_ARGUMENT;
1521         }
1522     }
1523
1524   if (a->is_add)
1525     {
1526       if (ls_result)
1527         ls_result[0] = p[0];
1528
1529       /* allocate locators */
1530       vec_foreach (itloc, a->locators)
1531       {
1532         ret = is_locator_in_locator_set (lcm, ls, itloc);
1533         if (0 != ret)
1534           {
1535             return ret;
1536           }
1537
1538         pool_get (lcm->locator_pool, loc);
1539         loc[0] = itloc[0];
1540         loc_index = loc - lcm->locator_pool;
1541
1542         vec_add1 (ls->locator_indices, loc_index);
1543
1544         vec_validate (lcm->locator_to_locator_sets, loc_index);
1545         ls_indexes = vec_elt_at_index (lcm->locator_to_locator_sets,
1546                                        loc_index);
1547         vec_add1 (ls_indexes[0], p[0]);
1548       }
1549     }
1550   else
1551     {
1552       ls_index = p[0];
1553
1554       itloc = a->locators;
1555       loc_id = 0;
1556       vec_foreach (locit, ls->locator_indices)
1557       {
1558         loc = pool_elt_at_index (lcm->locator_pool, locit[0]);
1559
1560         if (loc->local && loc->sw_if_index == itloc->sw_if_index)
1561           {
1562             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
1563           }
1564         if (0 == loc->local &&
1565             !gid_address_cmp (&loc->address, &itloc->address))
1566           {
1567             remove_locator_from_locator_set (ls, locit, ls_index, loc_id);
1568           }
1569
1570         loc_id++;
1571       }
1572     }
1573
1574   return 0;
1575 }
1576
1577 int
1578 vnet_lisp_add_del_locator_set (vnet_lisp_add_del_locator_set_args_t * a,
1579                                u32 * ls_result)
1580 {
1581   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1582   locator_set_t *ls;
1583   uword _p = (u32) ~ 0, *p = &_p;
1584   u32 ls_index;
1585   u32 **eid_indexes;
1586   int ret = 0;
1587
1588   if (vnet_lisp_enable_disable_status () == 0)
1589     {
1590       clib_warning ("LISP is disabled!");
1591       return VNET_API_ERROR_LISP_DISABLED;
1592     }
1593
1594   if (a->is_add)
1595     {
1596       p = get_locator_set_index (a, p);
1597
1598       /* overwrite */
1599       if (p && p[0] != (u32) ~ 0)
1600         {
1601           ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1602           if (!ls)
1603             {
1604               clib_warning ("locator-set %d to be overwritten doesn't exist!",
1605                             p[0]);
1606               return -1;
1607             }
1608
1609           /* clean locator to locator-set vectors and remove locators if
1610            * they're not part of another locator-set */
1611           clean_locator_to_locator_set (lcm, p[0]);
1612
1613           /* remove locator indices from locator set */
1614           vec_free (ls->locator_indices);
1615
1616           ls_index = p[0];
1617
1618           if (ls_result)
1619             ls_result[0] = p[0];
1620         }
1621       /* new locator-set */
1622       else
1623         {
1624           pool_get (lcm->locator_set_pool, ls);
1625           memset (ls, 0, sizeof (*ls));
1626           ls_index = ls - lcm->locator_set_pool;
1627
1628           if (a->local)
1629             {
1630               ls->name = vec_dup (a->name);
1631
1632               if (!lcm->locator_set_index_by_name)
1633                 lcm->locator_set_index_by_name = hash_create_vec (
1634                                                                    /* size */
1635                                                                    0,
1636                                                                    sizeof
1637                                                                    (ls->name
1638                                                                     [0]),
1639                                                                    sizeof
1640                                                                    (uword));
1641               hash_set_mem (lcm->locator_set_index_by_name, ls->name,
1642                             ls_index);
1643
1644               /* mark as local locator-set */
1645               vec_add1 (lcm->local_locator_set_indexes, ls_index);
1646             }
1647           ls->local = a->local;
1648           if (ls_result)
1649             ls_result[0] = ls_index;
1650         }
1651
1652       ret = vnet_lisp_add_del_locator (a, ls, NULL);
1653       if (0 != ret)
1654         {
1655           return ret;
1656         }
1657     }
1658   else
1659     {
1660       p = get_locator_set_index (a, p);
1661       if (!p)
1662         {
1663           clib_warning ("locator-set %v doesn't exists", a->name);
1664           return -1;
1665         }
1666
1667       ls = pool_elt_at_index (lcm->locator_set_pool, p[0]);
1668       if (!ls)
1669         {
1670           clib_warning ("locator-set with index %d doesn't exists", p[0]);
1671           return -1;
1672         }
1673
1674       if (lcm->mreq_itr_rlocs == p[0])
1675         {
1676           clib_warning ("Can't delete the locator-set used to constrain "
1677                         "the itr-rlocs in map-requests!");
1678           return -1;
1679         }
1680
1681       if (vec_len (lcm->locator_set_to_eids) != 0)
1682         {
1683           eid_indexes = vec_elt_at_index (lcm->locator_set_to_eids, p[0]);
1684           if (vec_len (eid_indexes[0]) != 0)
1685             {
1686               clib_warning
1687                 ("Can't delete a locator that supports a mapping!");
1688               return -1;
1689             }
1690         }
1691
1692       /* clean locator to locator-sets data */
1693       clean_locator_to_locator_set (lcm, p[0]);
1694
1695       if (ls->local)
1696         {
1697           u32 it, lsi;
1698
1699           vec_foreach_index (it, lcm->local_locator_set_indexes)
1700           {
1701             lsi = vec_elt (lcm->local_locator_set_indexes, it);
1702             if (lsi == p[0])
1703               {
1704                 vec_del1 (lcm->local_locator_set_indexes, it);
1705                 break;
1706               }
1707           }
1708           hash_unset_mem (lcm->locator_set_index_by_name, ls->name);
1709         }
1710       vec_free (ls->name);
1711       vec_free (ls->locator_indices);
1712       pool_put (lcm->locator_set_pool, ls);
1713     }
1714   return 0;
1715 }
1716
1717 int
1718 vnet_lisp_rloc_probe_enable_disable (u8 is_enable)
1719 {
1720   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1721
1722   lcm->rloc_probing = is_enable;
1723   return 0;
1724 }
1725
1726 int
1727 vnet_lisp_map_register_enable_disable (u8 is_enable)
1728 {
1729   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1730
1731   lcm->map_registering = is_enable;
1732   return 0;
1733 }
1734
1735 clib_error_t *
1736 vnet_lisp_enable_disable (u8 is_enable)
1737 {
1738   u32 vni, dp_table;
1739   clib_error_t *error = 0;
1740   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1741   vnet_lisp_gpe_enable_disable_args_t _a, *a = &_a;
1742
1743   a->is_en = is_enable;
1744   error = vnet_lisp_gpe_enable_disable (a);
1745   if (error)
1746     {
1747       return clib_error_return (0, "failed to %s data-plane!",
1748                                 a->is_en ? "enable" : "disable");
1749     }
1750
1751   if (is_enable)
1752     {
1753       /* enable all l2 and l3 ifaces */
1754
1755       /* *INDENT-OFF* */
1756       hash_foreach(vni, dp_table, lcm->table_id_by_vni, ({
1757         dp_add_del_iface(lcm, vni, 0, 1);
1758       }));
1759       hash_foreach(vni, dp_table, lcm->bd_id_by_vni, ({
1760         dp_add_del_iface(lcm, vni, /* is_l2 */ 1, 1);
1761       }));
1762       /* *INDENT-ON* */
1763     }
1764   else
1765     {
1766       /* clear interface table */
1767       hash_free (lcm->fwd_entry_by_mapping_index);
1768       pool_free (lcm->fwd_entry_pool);
1769     }
1770
1771   /* update global flag */
1772   lcm->is_enabled = is_enable;
1773
1774   return 0;
1775 }
1776
1777 u8
1778 vnet_lisp_enable_disable_status (void)
1779 {
1780   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1781   return lcm->is_enabled;
1782 }
1783
1784 int
1785 vnet_lisp_add_del_map_resolver (vnet_lisp_add_del_map_resolver_args_t * a)
1786 {
1787   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1788   u32 i;
1789   lisp_msmr_t _mr, *mr = &_mr;
1790
1791   if (vnet_lisp_enable_disable_status () == 0)
1792     {
1793       clib_warning ("LISP is disabled!");
1794       return VNET_API_ERROR_LISP_DISABLED;
1795     }
1796
1797   if (a->is_add)
1798     {
1799
1800       if (get_map_resolver (&a->address))
1801         {
1802           clib_warning ("map-resolver %U already exists!", format_ip_address,
1803                         &a->address);
1804           return -1;
1805         }
1806
1807       memset (mr, 0, sizeof (*mr));
1808       ip_address_copy (&mr->address, &a->address);
1809       vec_add1 (lcm->map_resolvers, *mr);
1810
1811       if (vec_len (lcm->map_resolvers) == 1)
1812         lcm->do_map_resolver_election = 1;
1813     }
1814   else
1815     {
1816       for (i = 0; i < vec_len (lcm->map_resolvers); i++)
1817         {
1818           mr = vec_elt_at_index (lcm->map_resolvers, i);
1819           if (!ip_address_cmp (&mr->address, &a->address))
1820             {
1821               if (!ip_address_cmp (&mr->address, &lcm->active_map_resolver))
1822                 lcm->do_map_resolver_election = 1;
1823
1824               vec_del1 (lcm->map_resolvers, i);
1825               break;
1826             }
1827         }
1828     }
1829   return 0;
1830 }
1831
1832 int
1833 vnet_lisp_add_del_mreq_itr_rlocs (vnet_lisp_add_del_mreq_itr_rloc_args_t * a)
1834 {
1835   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
1836   uword *p = 0;
1837
1838   if (vnet_lisp_enable_disable_status () == 0)
1839     {
1840       clib_warning ("LISP is disabled!");
1841       return VNET_API_ERROR_LISP_DISABLED;
1842     }
1843
1844   if (a->is_add)
1845     {
1846       p = hash_get_mem (lcm->locator_set_index_by_name, a->locator_set_name);
1847       if (!p)
1848         {
1849           clib_warning ("locator-set %v doesn't exist", a->locator_set_name);
1850           return VNET_API_ERROR_INVALID_ARGUMENT;
1851         }
1852
1853       lcm->mreq_itr_rlocs = p[0];
1854     }
1855   else
1856     {
1857       lcm->mreq_itr_rlocs = ~0;
1858     }
1859
1860   return 0;
1861 }
1862
1863 /* Statistics (not really errors) */
1864 #define foreach_lisp_cp_lookup_error           \
1865 _(DROP, "drop")                                \
1866 _(MAP_REQUESTS_SENT, "map-request sent")
1867
1868 static char *lisp_cp_lookup_error_strings[] = {
1869 #define _(sym,string) string,
1870   foreach_lisp_cp_lookup_error
1871 #undef _
1872 };
1873
1874 typedef enum
1875 {
1876 #define _(sym,str) LISP_CP_LOOKUP_ERROR_##sym,
1877   foreach_lisp_cp_lookup_error
1878 #undef _
1879     LISP_CP_LOOKUP_N_ERROR,
1880 } lisp_cp_lookup_error_t;
1881
1882 typedef enum
1883 {
1884   LISP_CP_LOOKUP_NEXT_DROP,
1885   LISP_CP_LOOKUP_N_NEXT,
1886 } lisp_cp_lookup_next_t;
1887
1888 typedef struct
1889 {
1890   gid_address_t dst_eid;
1891   ip_address_t map_resolver_ip;
1892 } lisp_cp_lookup_trace_t;
1893
1894 u8 *
1895 format_lisp_cp_lookup_trace (u8 * s, va_list * args)
1896 {
1897   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
1898   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
1899   lisp_cp_lookup_trace_t *t = va_arg (*args, lisp_cp_lookup_trace_t *);
1900
1901   s = format (s, "LISP-CP-LOOKUP: map-resolver: %U destination eid %U",
1902               format_ip_address, &t->map_resolver_ip, format_gid_address,
1903               &t->dst_eid);
1904   return s;
1905 }
1906
1907 int
1908 get_mr_and_local_iface_ip (lisp_cp_main_t * lcm, ip_address_t * mr_ip,
1909                            ip_address_t * sloc)
1910 {
1911   lisp_msmr_t *mrit;
1912   ip_address_t *a;
1913
1914   if (vec_len (lcm->map_resolvers) == 0)
1915     {
1916       clib_warning ("No map-resolver configured");
1917       return 0;
1918     }
1919
1920   /* find the first mr ip we have a route to and the ip of the
1921    * iface that has a route to it */
1922   vec_foreach (mrit, lcm->map_resolvers)
1923   {
1924     a = &mrit->address;
1925     if (0 != ip_fib_get_first_egress_ip_for_dst (lcm, a, sloc))
1926       {
1927         ip_address_copy (mr_ip, a);
1928
1929         /* also update globals */
1930         return 1;
1931       }
1932   }
1933
1934   clib_warning ("Can't find map-resolver and local interface ip!");
1935   return 0;
1936 }
1937
1938 static gid_address_t *
1939 build_itr_rloc_list (lisp_cp_main_t * lcm, locator_set_t * loc_set)
1940 {
1941   void *addr;
1942   u32 i;
1943   locator_t *loc;
1944   u32 *loc_indexp;
1945   ip_interface_address_t *ia = 0;
1946   gid_address_t gid_data, *gid = &gid_data;
1947   gid_address_t *rlocs = 0;
1948   ip_prefix_t *ippref = &gid_address_ippref (gid);
1949   ip_address_t *rloc = &ip_prefix_addr (ippref);
1950
1951   memset (gid, 0, sizeof (gid[0]));
1952   gid_address_type (gid) = GID_ADDR_IP_PREFIX;
1953   for (i = 0; i < vec_len (loc_set->locator_indices); i++)
1954     {
1955       loc_indexp = vec_elt_at_index (loc_set->locator_indices, i);
1956       loc = pool_elt_at_index (lcm->locator_pool, loc_indexp[0]);
1957
1958       /* Add ipv4 locators first TODO sort them */
1959
1960       /* *INDENT-OFF* */
1961       foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
1962                                     loc->sw_if_index, 1 /* unnumbered */,
1963       ({
1964         addr = ip_interface_address_get_address (&lcm->im4->lookup_main, ia);
1965         ip_address_set (rloc, addr, IP4);
1966         ip_prefix_len (ippref) = 32;
1967         ip_prefix_normalize (ippref);
1968         vec_add1 (rlocs, gid[0]);
1969       }));
1970
1971       /* Add ipv6 locators */
1972       foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
1973                                     loc->sw_if_index, 1 /* unnumbered */,
1974       ({
1975         addr = ip_interface_address_get_address (&lcm->im6->lookup_main, ia);
1976         ip_address_set (rloc, addr, IP6);
1977         ip_prefix_len (ippref) = 128;
1978         ip_prefix_normalize (ippref);
1979         vec_add1 (rlocs, gid[0]);
1980       }));
1981       /* *INDENT-ON* */
1982
1983     }
1984   return rlocs;
1985 }
1986
1987 static vlib_buffer_t *
1988 build_map_request (lisp_cp_main_t * lcm, gid_address_t * deid,
1989                    ip_address_t * sloc, ip_address_t * rloc,
1990                    gid_address_t * itr_rlocs, u64 * nonce_res, u32 * bi_res)
1991 {
1992   vlib_buffer_t *b;
1993   u32 bi;
1994   vlib_main_t *vm = lcm->vlib_main;
1995
1996   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
1997     {
1998       clib_warning ("Can't allocate buffer for Map-Request!");
1999       return 0;
2000     }
2001
2002   b = vlib_get_buffer (vm, bi);
2003
2004   /* leave some space for the encap headers */
2005   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2006
2007   /* put lisp msg */
2008   lisp_msg_put_mreq (lcm, b, NULL, deid, itr_rlocs, 0 /* smr invoked */ ,
2009                      1 /* rloc probe */ , nonce_res);
2010
2011   /* push outer ip header */
2012   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2013                        rloc);
2014
2015   bi_res[0] = bi;
2016
2017   return b;
2018 }
2019
2020 static vlib_buffer_t *
2021 build_encapsulated_map_request (lisp_cp_main_t * lcm,
2022                                 gid_address_t * seid, gid_address_t * deid,
2023                                 locator_set_t * loc_set, ip_address_t * mr_ip,
2024                                 ip_address_t * sloc, u8 is_smr_invoked,
2025                                 u64 * nonce_res, u32 * bi_res)
2026 {
2027   vlib_buffer_t *b;
2028   u32 bi;
2029   gid_address_t *rlocs = 0;
2030   vlib_main_t *vm = lcm->vlib_main;
2031
2032   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2033     {
2034       clib_warning ("Can't allocate buffer for Map-Request!");
2035       return 0;
2036     }
2037
2038   b = vlib_get_buffer (vm, bi);
2039
2040   /* leave some space for the encap headers */
2041   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2042
2043   /* get rlocs */
2044   rlocs = build_itr_rloc_list (lcm, loc_set);
2045
2046   if (MR_MODE_SRC_DST == lcm->map_request_mode
2047       && GID_ADDR_SRC_DST != gid_address_type (deid))
2048     {
2049       gid_address_t sd;
2050       memset (&sd, 0, sizeof (sd));
2051       build_src_dst (&sd, seid, deid);
2052       lisp_msg_put_mreq (lcm, b, seid, &sd, rlocs, is_smr_invoked,
2053                          0 /* rloc probe */ , nonce_res);
2054     }
2055   else
2056     {
2057       /* put lisp msg */
2058       lisp_msg_put_mreq (lcm, b, seid, deid, rlocs, is_smr_invoked,
2059                          0 /* rloc probe */ , nonce_res);
2060     }
2061
2062   /* push ecm: udp-ip-lisp */
2063   lisp_msg_push_ecm (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, seid, deid);
2064
2065   /* push outer ip header */
2066   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2067                        mr_ip);
2068
2069   bi_res[0] = bi;
2070
2071   vec_free (rlocs);
2072   return b;
2073 }
2074
2075 static void
2076 reset_pending_mr_counters (pending_map_request_t * r)
2077 {
2078   r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
2079   r->retries_num = 0;
2080 }
2081
2082 static int
2083 elect_map_resolver (lisp_cp_main_t * lcm)
2084 {
2085   lisp_msmr_t *mr;
2086
2087   vec_foreach (mr, lcm->map_resolvers)
2088   {
2089     if (!mr->is_down)
2090       {
2091         ip_address_copy (&lcm->active_map_resolver, &mr->address);
2092         lcm->do_map_resolver_election = 0;
2093         return 1;
2094       }
2095   }
2096   return 0;
2097 }
2098
2099 static void
2100 free_map_register_records (mapping_t * maps)
2101 {
2102   mapping_t *map;
2103   vec_foreach (map, maps) vec_free (map->locators);
2104
2105   vec_free (maps);
2106 }
2107
2108 static void
2109 add_locators (lisp_cp_main_t * lcm, mapping_t * m, u32 locator_set_index,
2110               ip_address_t * probed_loc)
2111 {
2112   u32 *li;
2113   locator_t *loc, new;
2114   ip_interface_address_t *ia = 0;
2115   void *addr;
2116   ip_address_t *new_ip = &gid_address_ip (&new.address);
2117
2118   m->locators = 0;
2119   locator_set_t *ls = pool_elt_at_index (lcm->locator_set_pool,
2120                                          locator_set_index);
2121   vec_foreach (li, ls->locator_indices)
2122   {
2123     loc = pool_elt_at_index (lcm->locator_pool, li[0]);
2124     new = loc[0];
2125     if (loc->local)
2126       {
2127           /* *INDENT-OFF* */
2128           foreach_ip_interface_address (&lcm->im4->lookup_main, ia,
2129                                         loc->sw_if_index, 1 /* unnumbered */,
2130           ({
2131             addr = ip_interface_address_get_address (&lcm->im4->lookup_main,
2132                                                      ia);
2133             ip_address_set (new_ip, addr, IP4);
2134           }));
2135
2136           /* Add ipv6 locators */
2137           foreach_ip_interface_address (&lcm->im6->lookup_main, ia,
2138                                         loc->sw_if_index, 1 /* unnumbered */,
2139           ({
2140             addr = ip_interface_address_get_address (&lcm->im6->lookup_main,
2141                                                      ia);
2142             ip_address_set (new_ip, addr, IP6);
2143           }));
2144           /* *INDENT-ON* */
2145
2146         if (probed_loc && ip_address_cmp (probed_loc, new_ip) == 0)
2147           new.probed = 1;
2148       }
2149     vec_add1 (m->locators, new);
2150   }
2151 }
2152
2153 static mapping_t *
2154 build_map_register_record_list (lisp_cp_main_t * lcm)
2155 {
2156   mapping_t *recs = 0, rec, *m;
2157
2158   /* *INDENT-OFF* */
2159   pool_foreach(m, lcm->mapping_pool,
2160   {
2161     /* for now build only local mappings */
2162     if (!m->local)
2163       continue;
2164
2165     rec = m[0];
2166     add_locators (lcm, &rec, m->locator_set_index, NULL);
2167     vec_add1 (recs, rec);
2168   });
2169   /* *INDENT-ON* */
2170
2171   return recs;
2172 }
2173
2174 static int
2175 update_map_register_auth_data (map_register_hdr_t * map_reg_hdr,
2176                                lisp_key_type_t key_id, u8 * key,
2177                                u16 auth_data_len, u32 msg_len)
2178 {
2179   MREG_KEY_ID (map_reg_hdr) = clib_host_to_net_u16 (key_id);
2180   MREG_AUTH_DATA_LEN (map_reg_hdr) = clib_host_to_net_u16 (auth_data_len);
2181
2182   unsigned char *result = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
2183                                 (unsigned char *) map_reg_hdr, msg_len, NULL,
2184                                 NULL);
2185   clib_memcpy (MREG_DATA (map_reg_hdr), result, auth_data_len);
2186
2187   return 0;
2188 }
2189
2190 static vlib_buffer_t *
2191 build_map_register (lisp_cp_main_t * lcm, ip_address_t * sloc,
2192                     ip_address_t * ms_ip, u64 * nonce_res, u8 want_map_notif,
2193                     mapping_t * records, lisp_key_type_t key_id, u8 * key,
2194                     u32 * bi_res)
2195 {
2196   void *map_reg_hdr;
2197   vlib_buffer_t *b;
2198   u32 bi, auth_data_len = 0, msg_len = 0;
2199   vlib_main_t *vm = lcm->vlib_main;
2200
2201   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
2202     {
2203       clib_warning ("Can't allocate buffer for Map-Register!");
2204       return 0;
2205     }
2206
2207   b = vlib_get_buffer (vm, bi);
2208
2209   /* leave some space for the encap headers */
2210   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
2211
2212   auth_data_len = auth_data_len_by_key_id (key_id);
2213   map_reg_hdr = lisp_msg_put_map_register (b, records, want_map_notif,
2214                                            auth_data_len, nonce_res,
2215                                            &msg_len);
2216
2217   update_map_register_auth_data (map_reg_hdr, key_id, key, auth_data_len,
2218                                  msg_len);
2219
2220   /* push outer ip header */
2221   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, LISP_CONTROL_PORT, sloc,
2222                        ms_ip);
2223
2224   bi_res[0] = bi;
2225   return b;
2226 }
2227
2228 static int
2229 get_egress_map_resolver_ip (lisp_cp_main_t * lcm, ip_address_t * ip)
2230 {
2231   lisp_msmr_t *mr;
2232   while (lcm->do_map_resolver_election
2233          | (0 == ip_fib_get_first_egress_ip_for_dst (lcm,
2234                                                      &lcm->active_map_resolver,
2235                                                      ip)))
2236     {
2237       if (0 == elect_map_resolver (lcm))
2238         /* all map resolvers are down */
2239         {
2240           /* restart MR checking by marking all of them up */
2241           vec_foreach (mr, lcm->map_resolvers) mr->is_down = 0;
2242           return -1;
2243         }
2244     }
2245   return 0;
2246 }
2247
2248 /* CP output statistics */
2249 #define foreach_lisp_cp_output_error                  \
2250 _(MAP_REGISTERS_SENT, "map-registers sent")           \
2251 _(RLOC_PROBES_SENT, "rloc-probes sent")
2252
2253 static char *lisp_cp_output_error_strings[] = {
2254 #define _(sym,string) string,
2255   foreach_lisp_cp_output_error
2256 #undef _
2257 };
2258
2259 typedef enum
2260 {
2261 #define _(sym,str) LISP_CP_OUTPUT_ERROR_##sym,
2262   foreach_lisp_cp_output_error
2263 #undef _
2264     LISP_CP_OUTPUT_N_ERROR,
2265 } lisp_cp_output_error_t;
2266
2267 static uword
2268 lisp_cp_output (vlib_main_t * vm, vlib_node_runtime_t * node,
2269                 vlib_frame_t * from_frame)
2270 {
2271   return 0;
2272 }
2273
2274 /* dummy node used only for statistics */
2275 /* *INDENT-OFF* */
2276 VLIB_REGISTER_NODE (lisp_cp_output_node) = {
2277   .function = lisp_cp_output,
2278   .name = "lisp-cp-output",
2279   .vector_size = sizeof (u32),
2280   .format_trace = format_lisp_cp_input_trace,
2281   .type = VLIB_NODE_TYPE_INTERNAL,
2282
2283   .n_errors = LISP_CP_OUTPUT_N_ERROR,
2284   .error_strings = lisp_cp_output_error_strings,
2285
2286   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
2287
2288   .next_nodes = {
2289       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
2290   },
2291 };
2292 /* *INDENT-ON* */
2293
2294 static int
2295 send_rloc_probe (lisp_cp_main_t * lcm, gid_address_t * deid,
2296                  u32 local_locator_set_index, ip_address_t * sloc,
2297                  ip_address_t * rloc)
2298 {
2299   locator_set_t *ls;
2300   u32 bi;
2301   vlib_buffer_t *b;
2302   vlib_frame_t *f;
2303   u64 nonce = 0;
2304   u32 next_index, *to_next;
2305   gid_address_t *itr_rlocs;
2306
2307   ls = pool_elt_at_index (lcm->locator_set_pool, local_locator_set_index);
2308   itr_rlocs = build_itr_rloc_list (lcm, ls);
2309
2310   b = build_map_request (lcm, deid, sloc, rloc, itr_rlocs, &nonce, &bi);
2311   vec_free (itr_rlocs);
2312   if (!b)
2313     return -1;
2314
2315   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2316
2317   next_index = (ip_addr_version (rloc) == IP4) ?
2318     ip4_lookup_node.index : ip6_lookup_node.index;
2319
2320   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2321
2322   /* Enqueue the packet */
2323   to_next = vlib_frame_vector_args (f);
2324   to_next[0] = bi;
2325   f->n_vectors = 1;
2326   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2327
2328   hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
2329   return 0;
2330 }
2331
2332 static int
2333 send_rloc_probes (lisp_cp_main_t * lcm)
2334 {
2335   u8 lprio = 0;
2336   mapping_t *lm;
2337   fwd_entry_t *e;
2338   locator_pair_t *lp;
2339   u32 si, rloc_probes_sent = 0;
2340
2341   /* *INDENT-OFF* */
2342   pool_foreach (e, lcm->fwd_entry_pool,
2343   {
2344     if (vec_len (e->locator_pairs) == 0)
2345       continue;
2346
2347     si = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &e->leid);
2348     if (~0 == si)
2349       {
2350         clib_warning ("internal error: cannot find local eid %U in "
2351                       "map-cache!", format_gid_address, &e->leid);
2352         continue;
2353       }
2354     lm = pool_elt_at_index (lcm->mapping_pool, si);
2355
2356     /* get the best (lowest) priority */
2357     lprio = e->locator_pairs[0].priority;
2358
2359     /* send rloc-probe for pair(s) with the best remote locator priority */
2360     vec_foreach (lp, e->locator_pairs)
2361       {
2362         if (lp->priority != lprio)
2363           break;
2364
2365         /* get first remote locator */
2366         send_rloc_probe (lcm, &e->reid, lm->locator_set_index, &lp->lcl_loc,
2367                          &lp->rmt_loc);
2368         rloc_probes_sent++;
2369       }
2370   });
2371   /* *INDENT-ON* */
2372
2373   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
2374                                LISP_CP_OUTPUT_ERROR_RLOC_PROBES_SENT,
2375                                rloc_probes_sent);
2376   return 0;
2377 }
2378
2379 static int
2380 send_map_register (lisp_cp_main_t * lcm, u8 want_map_notif)
2381 {
2382   u32 bi, map_registers_sent = 0;
2383   vlib_buffer_t *b;
2384   ip_address_t sloc;
2385   vlib_frame_t *f;
2386   u64 nonce = 0;
2387   u32 next_index, *to_next;
2388   ip_address_t *ms = 0;
2389   mapping_t *records, *r, *g;
2390
2391   // TODO: support multiple map servers and do election
2392   if (0 == vec_len (lcm->map_servers))
2393     return -1;
2394
2395   ms = &lcm->map_servers[0].address;
2396
2397   if (0 == ip_fib_get_first_egress_ip_for_dst (lcm, ms, &sloc))
2398     {
2399       clib_warning ("no eligible interface address found for %U!",
2400                     format_ip_address, &lcm->map_servers[0]);
2401       return -1;
2402     }
2403
2404   records = build_map_register_record_list (lcm);
2405   if (!records)
2406     return -1;
2407
2408   vec_foreach (r, records)
2409   {
2410     u8 *key = r->key;
2411     u8 key_id = r->key_id;
2412
2413     if (!key)
2414       continue;                 /* no secret key -> map-register cannot be sent */
2415
2416     g = 0;
2417     // TODO: group mappings that share common key
2418     vec_add1 (g, r[0]);
2419     b = build_map_register (lcm, &sloc, ms, &nonce, want_map_notif, g,
2420                             key_id, key, &bi);
2421     vec_free (g);
2422     if (!b)
2423       continue;
2424
2425     vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2426
2427     next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
2428       ip4_lookup_node.index : ip6_lookup_node.index;
2429
2430     f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2431
2432     /* Enqueue the packet */
2433     to_next = vlib_frame_vector_args (f);
2434     to_next[0] = bi;
2435     f->n_vectors = 1;
2436     vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2437     map_registers_sent++;
2438
2439     hash_set (lcm->map_register_messages_by_nonce, nonce, 0);
2440   }
2441   free_map_register_records (records);
2442
2443   vlib_node_increment_counter (vlib_get_main (), lisp_cp_output_node.index,
2444                                LISP_CP_OUTPUT_ERROR_MAP_REGISTERS_SENT,
2445                                map_registers_sent);
2446
2447   return 0;
2448 }
2449
2450 #define send_encapsulated_map_request(lcm, seid, deid, smr) \
2451   _send_encapsulated_map_request(lcm, seid, deid, smr, 0)
2452
2453 #define resend_encapsulated_map_request(lcm, seid, deid, smr) \
2454   _send_encapsulated_map_request(lcm, seid, deid, smr, 1)
2455
2456 static int
2457 _send_encapsulated_map_request (lisp_cp_main_t * lcm,
2458                                 gid_address_t * seid, gid_address_t * deid,
2459                                 u8 is_smr_invoked, u8 is_resend)
2460 {
2461   u32 next_index, bi = 0, *to_next, map_index;
2462   vlib_buffer_t *b;
2463   vlib_frame_t *f;
2464   u64 nonce = 0;
2465   locator_set_t *loc_set;
2466   mapping_t *map;
2467   pending_map_request_t *pmr, *duplicate_pmr = 0;
2468   ip_address_t sloc;
2469   u32 ls_index;
2470
2471   /* if there is already a pending request remember it */
2472
2473   /* *INDENT-OFF* */
2474   pool_foreach(pmr, lcm->pending_map_requests_pool,
2475   ({
2476     if (!gid_address_cmp (&pmr->src, seid)
2477         && !gid_address_cmp (&pmr->dst, deid))
2478       {
2479         duplicate_pmr = pmr;
2480         break;
2481       }
2482   }));
2483   /* *INDENT-ON* */
2484
2485   if (!is_resend && duplicate_pmr)
2486     {
2487       /* don't send the request if there is a pending map request already */
2488       return 0;
2489     }
2490
2491   /* get locator-set for seid */
2492   if (!lcm->lisp_pitr)
2493     {
2494       map_index = gid_dictionary_lookup (&lcm->mapping_index_by_gid, seid);
2495       if (map_index == ~0)
2496         {
2497           clib_warning ("No local mapping found in eid-table for %U!",
2498                         format_gid_address, seid);
2499           return -1;
2500         }
2501
2502       map = pool_elt_at_index (lcm->mapping_pool, map_index);
2503
2504       if (!map->local)
2505         {
2506           clib_warning
2507             ("Mapping found for src eid %U is not marked as local!",
2508              format_gid_address, seid);
2509           return -1;
2510         }
2511       ls_index = map->locator_set_index;
2512     }
2513   else
2514     {
2515       map_index = lcm->pitr_map_index;
2516       map = pool_elt_at_index (lcm->mapping_pool, lcm->pitr_map_index);
2517       ls_index = map->locator_set_index;
2518     }
2519
2520   /* overwrite locator set if map-request itr-rlocs configured */
2521   if (~0 != lcm->mreq_itr_rlocs)
2522     {
2523       ls_index = lcm->mreq_itr_rlocs;
2524     }
2525
2526   loc_set = pool_elt_at_index (lcm->locator_set_pool, ls_index);
2527
2528   if (get_egress_map_resolver_ip (lcm, &sloc) < 0)
2529     {
2530       if (duplicate_pmr)
2531         duplicate_pmr->to_be_removed = 1;
2532       return -1;
2533     }
2534
2535   /* build the encapsulated map request */
2536   b = build_encapsulated_map_request (lcm, seid, deid, loc_set,
2537                                       &lcm->active_map_resolver,
2538                                       &sloc, is_smr_invoked, &nonce, &bi);
2539
2540   if (!b)
2541     return -1;
2542
2543   /* set fib index to default and lookup node */
2544   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
2545   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
2546     ip4_lookup_node.index : ip6_lookup_node.index;
2547
2548   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
2549
2550   /* Enqueue the packet */
2551   to_next = vlib_frame_vector_args (f);
2552   to_next[0] = bi;
2553   f->n_vectors = 1;
2554   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
2555
2556   if (duplicate_pmr)
2557     /* if there is a pending request already update it */
2558     {
2559       if (clib_fifo_elts (duplicate_pmr->nonces) >= PENDING_MREQ_QUEUE_LEN)
2560         {
2561           /* remove the oldest nonce */
2562           u64 CLIB_UNUSED (tmp), *nonce_del;
2563           nonce_del = clib_fifo_head (duplicate_pmr->nonces);
2564           hash_unset (lcm->pending_map_requests_by_nonce, nonce_del[0]);
2565           clib_fifo_sub1 (duplicate_pmr->nonces, tmp);
2566         }
2567
2568       clib_fifo_add1 (duplicate_pmr->nonces, nonce);
2569       hash_set (lcm->pending_map_requests_by_nonce, nonce,
2570                 duplicate_pmr - lcm->pending_map_requests_pool);
2571     }
2572   else
2573     {
2574       /* add map-request to pending requests table */
2575       pool_get (lcm->pending_map_requests_pool, pmr);
2576       memset (pmr, 0, sizeof (*pmr));
2577       gid_address_copy (&pmr->src, seid);
2578       gid_address_copy (&pmr->dst, deid);
2579       clib_fifo_add1 (pmr->nonces, nonce);
2580       pmr->is_smr_invoked = is_smr_invoked;
2581       reset_pending_mr_counters (pmr);
2582       hash_set (lcm->pending_map_requests_by_nonce, nonce,
2583                 pmr - lcm->pending_map_requests_pool);
2584     }
2585
2586   return 0;
2587 }
2588
2589 static void
2590 get_src_and_dst_ip (void *hdr, ip_address_t * src, ip_address_t * dst)
2591 {
2592   ip4_header_t *ip4 = hdr;
2593   ip6_header_t *ip6;
2594
2595   if ((ip4->ip_version_and_header_length & 0xF0) == 0x40)
2596     {
2597       ip_address_set (src, &ip4->src_address, IP4);
2598       ip_address_set (dst, &ip4->dst_address, IP4);
2599     }
2600   else
2601     {
2602       ip6 = hdr;
2603       ip_address_set (src, &ip6->src_address, IP6);
2604       ip_address_set (dst, &ip6->dst_address, IP6);
2605     }
2606 }
2607
2608 static u32
2609 lisp_get_vni_from_buffer_ip (lisp_cp_main_t * lcm, vlib_buffer_t * b,
2610                              u8 version)
2611 {
2612   uword *vnip;
2613   u32 vni = ~0, table_id = ~0;
2614
2615   table_id = fib_table_get_table_id_for_sw_if_index ((version ==
2616                                                       IP4 ? FIB_PROTOCOL_IP4 :
2617                                                       FIB_PROTOCOL_IP6),
2618                                                      vnet_buffer
2619                                                      (b)->sw_if_index
2620                                                      [VLIB_RX]);
2621
2622   vnip = hash_get (lcm->vni_by_table_id, table_id);
2623   if (vnip)
2624     vni = vnip[0];
2625   else
2626     clib_warning ("vrf %d is not mapped to any vni!", table_id);
2627
2628   return vni;
2629 }
2630
2631 always_inline u32
2632 lisp_get_vni_from_buffer_eth (lisp_cp_main_t * lcm, vlib_buffer_t * b)
2633 {
2634   uword *vnip;
2635   u32 vni = ~0;
2636   u32 sw_if_index0;
2637
2638   l2input_main_t *l2im = &l2input_main;
2639   l2_input_config_t *config;
2640   l2_bridge_domain_t *bd_config;
2641
2642   sw_if_index0 = vnet_buffer (b)->sw_if_index[VLIB_RX];
2643   config = vec_elt_at_index (l2im->configs, sw_if_index0);
2644   bd_config = vec_elt_at_index (l2im->bd_configs, config->bd_index);
2645
2646   vnip = hash_get (lcm->vni_by_bd_id, bd_config->bd_id);
2647   if (vnip)
2648     vni = vnip[0];
2649   else
2650     clib_warning ("bridge domain %d is not mapped to any vni!",
2651                   config->bd_index);
2652
2653   return vni;
2654 }
2655
2656 void
2657 get_src_and_dst_eids_from_buffer (lisp_cp_main_t * lcm, vlib_buffer_t * b,
2658                                   gid_address_t * src, gid_address_t * dst,
2659                                   u16 type)
2660 {
2661   u32 vni = 0;
2662
2663   memset (src, 0, sizeof (*src));
2664   memset (dst, 0, sizeof (*dst));
2665
2666   if (LISP_AFI_IP == type || LISP_AFI_IP6 == type)
2667     {
2668       ip4_header_t *ip;
2669       u8 version, preflen;
2670
2671       gid_address_type (src) = GID_ADDR_IP_PREFIX;
2672       gid_address_type (dst) = GID_ADDR_IP_PREFIX;
2673
2674       ip = vlib_buffer_get_current (b);
2675       get_src_and_dst_ip (ip, &gid_address_ip (src), &gid_address_ip (dst));
2676
2677       version = gid_address_ip_version (src);
2678       preflen = ip_address_max_len (version);
2679       gid_address_ippref_len (src) = preflen;
2680       gid_address_ippref_len (dst) = preflen;
2681
2682       vni = lisp_get_vni_from_buffer_ip (lcm, b, version);
2683       gid_address_vni (dst) = vni;
2684       gid_address_vni (src) = vni;
2685     }
2686   else if (LISP_AFI_MAC == type)
2687     {
2688       ethernet_header_t *eh;
2689
2690       eh = vlib_buffer_get_current (b);
2691
2692       gid_address_type (src) = GID_ADDR_MAC;
2693       gid_address_type (dst) = GID_ADDR_MAC;
2694       mac_copy (&gid_address_mac (src), eh->src_address);
2695       mac_copy (&gid_address_mac (dst), eh->dst_address);
2696
2697       /* get vni */
2698       vni = lisp_get_vni_from_buffer_eth (lcm, b);
2699
2700       gid_address_vni (dst) = vni;
2701       gid_address_vni (src) = vni;
2702     }
2703   else if (LISP_AFI_LCAF == type)
2704     {
2705       /* Eventually extend this to support NSH and other */
2706       ASSERT (0);
2707     }
2708 }
2709
2710 static uword
2711 lisp_cp_lookup_inline (vlib_main_t * vm,
2712                        vlib_node_runtime_t * node,
2713                        vlib_frame_t * from_frame, int overlay)
2714 {
2715   u32 *from, *to_next_drop, di, si;
2716   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
2717   u32 pkts_mapped = 0;
2718   uword n_left_from, n_left_to_next_drop;
2719
2720   from = vlib_frame_vector_args (from_frame);
2721   n_left_from = from_frame->n_vectors;
2722
2723   while (n_left_from > 0)
2724     {
2725       vlib_get_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
2726                            to_next_drop, n_left_to_next_drop);
2727
2728       while (n_left_from > 0 && n_left_to_next_drop > 0)
2729         {
2730           u32 pi0;
2731           vlib_buffer_t *b0;
2732           gid_address_t src, dst;
2733
2734           pi0 = from[0];
2735           from += 1;
2736           n_left_from -= 1;
2737           to_next_drop[0] = pi0;
2738           to_next_drop += 1;
2739           n_left_to_next_drop -= 1;
2740
2741           b0 = vlib_get_buffer (vm, pi0);
2742           b0->error = node->errors[LISP_CP_LOOKUP_ERROR_DROP];
2743
2744           /* src/dst eid pair */
2745           get_src_and_dst_eids_from_buffer (lcm, b0, &src, &dst, overlay);
2746
2747           /* if we have remote mapping for destination already in map-chache
2748              add forwarding tunnel directly. If not send a map-request */
2749           di = gid_dictionary_sd_lookup (&lcm->mapping_index_by_gid, &dst,
2750                                          &src);
2751           if (~0 != di)
2752             {
2753               mapping_t *m = vec_elt_at_index (lcm->mapping_pool, di);
2754               /* send a map-request also in case of negative mapping entry
2755                  with corresponding action */
2756               if (m->action == LISP_SEND_MAP_REQUEST)
2757                 {
2758                   /* send map-request */
2759                   queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
2760                                      0 /* is_resend */ );
2761                   pkts_mapped++;
2762                 }
2763               else
2764                 {
2765                   si = gid_dictionary_lookup (&lcm->mapping_index_by_gid,
2766                                               &src);
2767                   if (~0 != si)
2768                     {
2769                       dp_add_fwd_entry_from_mt (si, di);
2770                     }
2771                 }
2772             }
2773           else
2774             {
2775               /* send map-request */
2776               queue_map_request (&src, &dst, 0 /* smr_invoked */ ,
2777                                  0 /* is_resend */ );
2778               pkts_mapped++;
2779             }
2780
2781           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
2782             {
2783               lisp_cp_lookup_trace_t *tr = vlib_add_trace (vm, node, b0,
2784                                                            sizeof (*tr));
2785
2786               memset (tr, 0, sizeof (*tr));
2787               gid_address_copy (&tr->dst_eid, &dst);
2788               ip_address_copy (&tr->map_resolver_ip,
2789                                &lcm->active_map_resolver);
2790             }
2791           gid_address_free (&dst);
2792           gid_address_free (&src);
2793         }
2794
2795       vlib_put_next_frame (vm, node, LISP_CP_LOOKUP_NEXT_DROP,
2796                            n_left_to_next_drop);
2797     }
2798   vlib_node_increment_counter (vm, node->node_index,
2799                                LISP_CP_LOOKUP_ERROR_MAP_REQUESTS_SENT,
2800                                pkts_mapped);
2801   return from_frame->n_vectors;
2802 }
2803
2804 static uword
2805 lisp_cp_lookup_ip4 (vlib_main_t * vm,
2806                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2807 {
2808   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP));
2809 }
2810
2811 static uword
2812 lisp_cp_lookup_ip6 (vlib_main_t * vm,
2813                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2814 {
2815   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_IP6));
2816 }
2817
2818 static uword
2819 lisp_cp_lookup_l2 (vlib_main_t * vm,
2820                    vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2821 {
2822   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_MAC));
2823 }
2824
2825 static uword
2826 lisp_cp_lookup_nsh (vlib_main_t * vm,
2827                     vlib_node_runtime_t * node, vlib_frame_t * from_frame)
2828 {
2829   /* TODO decide if NSH should be propagated as LCAF or not */
2830   return (lisp_cp_lookup_inline (vm, node, from_frame, LISP_AFI_LCAF));
2831 }
2832
2833 /* *INDENT-OFF* */
2834 VLIB_REGISTER_NODE (lisp_cp_lookup_ip4_node) = {
2835   .function = lisp_cp_lookup_ip4,
2836   .name = "lisp-cp-lookup-ip4",
2837   .vector_size = sizeof (u32),
2838   .format_trace = format_lisp_cp_lookup_trace,
2839   .type = VLIB_NODE_TYPE_INTERNAL,
2840
2841   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2842   .error_strings = lisp_cp_lookup_error_strings,
2843
2844   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2845
2846   .next_nodes = {
2847       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2848   },
2849 };
2850 /* *INDENT-ON* */
2851
2852 /* *INDENT-OFF* */
2853 VLIB_REGISTER_NODE (lisp_cp_lookup_ip6_node) = {
2854   .function = lisp_cp_lookup_ip6,
2855   .name = "lisp-cp-lookup-ip6",
2856   .vector_size = sizeof (u32),
2857   .format_trace = format_lisp_cp_lookup_trace,
2858   .type = VLIB_NODE_TYPE_INTERNAL,
2859
2860   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2861   .error_strings = lisp_cp_lookup_error_strings,
2862
2863   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2864
2865   .next_nodes = {
2866       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2867   },
2868 };
2869 /* *INDENT-ON* */
2870
2871 /* *INDENT-OFF* */
2872 VLIB_REGISTER_NODE (lisp_cp_lookup_l2_node) = {
2873   .function = lisp_cp_lookup_l2,
2874   .name = "lisp-cp-lookup-l2",
2875   .vector_size = sizeof (u32),
2876   .format_trace = format_lisp_cp_lookup_trace,
2877   .type = VLIB_NODE_TYPE_INTERNAL,
2878
2879   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2880   .error_strings = lisp_cp_lookup_error_strings,
2881
2882   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2883
2884   .next_nodes = {
2885       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2886   },
2887 };
2888 /* *INDENT-ON* */
2889
2890 /* *INDENT-OFF* */
2891 VLIB_REGISTER_NODE (lisp_cp_lookup_nsh_node) = {
2892   .function = lisp_cp_lookup_nsh,
2893   .name = "lisp-cp-lookup-nsh",
2894   .vector_size = sizeof (u32),
2895   .format_trace = format_lisp_cp_lookup_trace,
2896   .type = VLIB_NODE_TYPE_INTERNAL,
2897
2898   .n_errors = LISP_CP_LOOKUP_N_ERROR,
2899   .error_strings = lisp_cp_lookup_error_strings,
2900
2901   .n_next_nodes = LISP_CP_LOOKUP_N_NEXT,
2902
2903   .next_nodes = {
2904       [LISP_CP_LOOKUP_NEXT_DROP] = "error-drop",
2905   },
2906 };
2907 /* *INDENT-ON* */
2908
2909 /* lisp_cp_input statistics */
2910 #define foreach_lisp_cp_input_error                               \
2911 _(DROP, "drop")                                                   \
2912 _(RLOC_PROBE_REQ_RECEIVED, "rloc-probe requests received")        \
2913 _(RLOC_PROBE_REP_RECEIVED, "rloc-probe replies received")         \
2914 _(MAP_NOTIFIES_RECEIVED, "map-notifies received")                 \
2915 _(MAP_REPLIES_RECEIVED, "map-replies received")
2916
2917 static char *lisp_cp_input_error_strings[] = {
2918 #define _(sym,string) string,
2919   foreach_lisp_cp_input_error
2920 #undef _
2921 };
2922
2923 typedef enum
2924 {
2925 #define _(sym,str) LISP_CP_INPUT_ERROR_##sym,
2926   foreach_lisp_cp_input_error
2927 #undef _
2928     LISP_CP_INPUT_N_ERROR,
2929 } lisp_cp_input_error_t;
2930
2931 typedef struct
2932 {
2933   gid_address_t dst_eid;
2934   ip4_address_t map_resolver_ip;
2935 } lisp_cp_input_trace_t;
2936
2937 u8 *
2938 format_lisp_cp_input_trace (u8 * s, va_list * args)
2939 {
2940   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
2941   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
2942   CLIB_UNUSED (lisp_cp_input_trace_t * t) =
2943     va_arg (*args, lisp_cp_input_trace_t *);
2944
2945   s = format (s, "LISP-CP-INPUT: TODO");
2946   return s;
2947 }
2948
2949 static void
2950 remove_expired_mapping (lisp_cp_main_t * lcm, u32 mi)
2951 {
2952   mapping_t *m;
2953   vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
2954   memset (adj_args, 0, sizeof (adj_args[0]));
2955
2956   m = pool_elt_at_index (lcm->mapping_pool, mi);
2957
2958   gid_address_copy (&adj_args->reid, &m->eid);
2959   adj_args->is_add = 0;
2960   if (vnet_lisp_add_del_adjacency (adj_args))
2961     clib_warning ("failed to del adjacency!");
2962
2963   vnet_lisp_add_del_mapping (&m->eid, 0, 0, 0, ~0, 0 /* is_add */ ,
2964                              0 /* is_static */ , 0);
2965   mapping_delete_timer (lcm, mi);
2966 }
2967
2968 static void
2969 mapping_start_expiration_timer (lisp_cp_main_t * lcm, u32 mi,
2970                                 f64 expiration_time)
2971 {
2972   mapping_t *m;
2973   u64 now = clib_cpu_time_now ();
2974   u64 cpu_cps = lcm->vlib_main->clib_time.clocks_per_second;
2975   u64 exp_clock_time = now + expiration_time * cpu_cps;
2976
2977   m = pool_elt_at_index (lcm->mapping_pool, mi);
2978
2979   m->timer_set = 1;
2980   timing_wheel_insert (&lcm->wheel, exp_clock_time, mi);
2981 }
2982
2983 static void
2984 map_records_arg_free (map_records_arg_t * a)
2985 {
2986   mapping_t *m;
2987   vec_foreach (m, a->mappings)
2988   {
2989     vec_free (m->locators);
2990     gid_address_free (&m->eid);
2991   }
2992
2993   clib_mem_free (a);
2994 }
2995
2996 void *
2997 process_map_reply (map_records_arg_t * a)
2998 {
2999   mapping_t *m;
3000   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3001   u32 dst_map_index = 0;
3002   pending_map_request_t *pmr;
3003   u64 *noncep;
3004   uword *pmr_index;
3005
3006   if (a->is_rloc_probe)
3007     goto done;
3008
3009   /* Check pending requests table and nonce */
3010   pmr_index = hash_get (lcm->pending_map_requests_by_nonce, a->nonce);
3011   if (!pmr_index)
3012     {
3013       clib_warning ("No pending map-request entry with nonce %lu!", a->nonce);
3014       goto done;
3015     }
3016   pmr = pool_elt_at_index (lcm->pending_map_requests_pool, pmr_index[0]);
3017
3018   vec_foreach (m, a->mappings)
3019   {
3020     /* insert/update mappings cache */
3021     vnet_lisp_add_del_mapping (&m->eid, m->locators, m->action,
3022                                m->authoritative, m->ttl,
3023                                1, 0 /* is_static */ , &dst_map_index);
3024
3025     if (dst_map_index == (u32) ~ 0)
3026       continue;
3027
3028     /* try to program forwarding only if mapping saved or updated */
3029     vnet_lisp_add_del_adjacency_args_t _adj_args, *adj_args = &_adj_args;
3030     memset (adj_args, 0, sizeof (adj_args[0]));
3031
3032     gid_address_copy (&adj_args->leid, &pmr->src);
3033     gid_address_copy (&adj_args->reid, &m->eid);
3034     adj_args->is_add = 1;
3035     if (vnet_lisp_add_del_adjacency (adj_args))
3036       clib_warning ("failed to add adjacency!");
3037
3038     if ((u32) ~ 0 != m->ttl)
3039       mapping_start_expiration_timer (lcm, dst_map_index, m->ttl * 60);
3040   }
3041
3042   /* remove pending map request entry */
3043
3044   /* *INDENT-OFF* */
3045   clib_fifo_foreach (noncep, pmr->nonces, ({
3046     hash_unset(lcm->pending_map_requests_by_nonce, noncep[0]);
3047   }));
3048   /* *INDENT-ON* */
3049
3050   clib_fifo_free (pmr->nonces);
3051   pool_put (lcm->pending_map_requests_pool, pmr);
3052
3053 done:
3054   map_records_arg_free (a);
3055   return 0;
3056 }
3057
3058 static int
3059 is_auth_data_valid (map_notify_hdr_t * h, u32 msg_len,
3060                     lisp_key_type_t key_id, u8 * key)
3061 {
3062   u8 *auth_data = 0;
3063   u16 auth_data_len;
3064   int result;
3065
3066   auth_data_len = auth_data_len_by_key_id (key_id);
3067   if ((u16) ~ 0 == auth_data_len)
3068     {
3069       clib_warning ("invalid length for key_id %d!", key_id);
3070       return 0;
3071     }
3072
3073   /* save auth data */
3074   vec_validate (auth_data, auth_data_len - 1);
3075   clib_memcpy (auth_data, MNOTIFY_DATA (h), auth_data_len);
3076
3077   /* clear auth data */
3078   memset (MNOTIFY_DATA (h), 0, auth_data_len);
3079
3080   /* get hash of the message */
3081   unsigned char *code = HMAC (get_encrypt_fcn (key_id), key, vec_len (key),
3082                               (unsigned char *) h, msg_len, NULL, NULL);
3083
3084   result = memcmp (code, auth_data, auth_data_len);
3085
3086   vec_free (auth_data);
3087
3088   return !result;
3089 }
3090
3091 static void
3092 process_map_notify (map_records_arg_t * a)
3093 {
3094   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3095   uword *pmr_index;
3096
3097   pmr_index = hash_get (lcm->map_register_messages_by_nonce, a->nonce);
3098   if (!pmr_index)
3099     {
3100       clib_warning ("No pending map-register entry with nonce %lu!",
3101                     a->nonce);
3102       return;
3103     }
3104
3105   map_records_arg_free (a);
3106   hash_unset (lcm->map_register_messages_by_nonce, a->nonce);
3107 }
3108
3109 static mapping_t *
3110 get_mapping (lisp_cp_main_t * lcm, gid_address_t * e)
3111 {
3112   u32 mi;
3113
3114   mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, e);
3115   if (~0 == mi)
3116     {
3117       clib_warning ("eid %U not found in map-cache!", unformat_gid_address,
3118                     e);
3119       return 0;
3120     }
3121   return pool_elt_at_index (lcm->mapping_pool, mi);
3122 }
3123
3124 /**
3125  * When map-notify is received it is necessary that all EIDs in the record
3126  * list share common key. The key is then used to verify authentication
3127  * data in map-notify message.
3128  */
3129 static int
3130 map_record_integrity_check (lisp_cp_main_t * lcm, mapping_t * maps,
3131                             u32 key_id, u8 ** key_out)
3132 {
3133   u32 i, len = vec_len (maps);
3134   mapping_t *m;
3135
3136   /* get key of the first mapping */
3137   m = get_mapping (lcm, &maps[0].eid);
3138   if (!m || !m->key)
3139     return -1;
3140
3141   key_out[0] = m->key;
3142
3143   for (i = 1; i < len; i++)
3144     {
3145       m = get_mapping (lcm, &maps[i].eid);
3146       if (!m || !m->key)
3147         return -1;
3148
3149       if (key_id != m->key_id || vec_cmp (m->key, key_out[0]))
3150         {
3151           clib_warning ("keys does not match! %v, %v", key_out[0], m->key);
3152           return -1;
3153         }
3154     }
3155   return 0;
3156 }
3157
3158 static int
3159 parse_map_records (vlib_buffer_t * b, map_records_arg_t * a, u8 count)
3160 {
3161   locator_t *locators = 0;
3162   u32 i, len;
3163   gid_address_t deid;
3164   mapping_t m;
3165   locator_t *loc;
3166
3167   /* parse record eid */
3168   for (i = 0; i < count; i++)
3169     {
3170       len = lisp_msg_parse_mapping_record (b, &deid, &locators, NULL);
3171       if (len == ~0)
3172         {
3173           clib_warning ("Failed to parse mapping record!");
3174           vec_foreach (loc, locators) locator_free (loc);
3175           vec_free (locators);
3176           return -1;
3177         }
3178
3179       m.locators = locators;
3180       gid_address_copy (&m.eid, &deid);
3181       vec_add1 (a->mappings, m);
3182     }
3183
3184   return 0;
3185 }
3186
3187 static map_records_arg_t *
3188 parse_map_notify (vlib_buffer_t * b)
3189 {
3190   int rc = 0;
3191   map_notify_hdr_t *mnotif_hdr;
3192   lisp_key_type_t key_id;
3193   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3194   u8 *key = 0;
3195   gid_address_t deid;
3196   u16 auth_data_len = 0;
3197   u8 record_count;
3198   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
3199
3200   memset (a, 0, sizeof (*a));
3201   mnotif_hdr = vlib_buffer_get_current (b);
3202   vlib_buffer_pull (b, sizeof (*mnotif_hdr));
3203   memset (&deid, 0, sizeof (deid));
3204
3205   a->nonce = MNOTIFY_NONCE (mnotif_hdr);
3206   key_id = clib_net_to_host_u16 (MNOTIFY_KEY_ID (mnotif_hdr));
3207   auth_data_len = auth_data_len_by_key_id (key_id);
3208
3209   /* advance buffer by authentication data */
3210   vlib_buffer_pull (b, auth_data_len);
3211
3212   record_count = MNOTIFY_REC_COUNT (mnotif_hdr);
3213   rc = parse_map_records (b, a, record_count);
3214   if (rc != 0)
3215     {
3216       map_records_arg_free (a);
3217       return 0;
3218     }
3219
3220   rc = map_record_integrity_check (lcm, a->mappings, key_id, &key);
3221   if (rc != 0)
3222     {
3223       map_records_arg_free (a);
3224       return 0;
3225     }
3226
3227   /* verify authentication data */
3228   if (!is_auth_data_valid (mnotif_hdr, vlib_buffer_get_tail (b)
3229                            - (u8 *) mnotif_hdr, key_id, key))
3230     {
3231       clib_warning ("Map-notify auth data verification failed for nonce %lu!",
3232                     a->nonce);
3233       map_records_arg_free (a);
3234       return 0;
3235     }
3236   return a;
3237 }
3238
3239 static vlib_buffer_t *
3240 build_map_reply (lisp_cp_main_t * lcm, ip_address_t * sloc,
3241                  ip_address_t * dst, u64 nonce, u8 probe_bit,
3242                  mapping_t * records, u16 dst_port, u32 * bi_res)
3243 {
3244   vlib_buffer_t *b;
3245   u32 bi;
3246   vlib_main_t *vm = lcm->vlib_main;
3247
3248   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
3249     {
3250       clib_warning ("Can't allocate buffer for Map-Register!");
3251       return 0;
3252     }
3253
3254   b = vlib_get_buffer (vm, bi);
3255
3256   /* leave some space for the encap headers */
3257   vlib_buffer_make_headroom (b, MAX_LISP_MSG_ENCAP_LEN);
3258
3259   lisp_msg_put_map_reply (b, records, nonce, probe_bit);
3260
3261   /* push outer ip header */
3262   pkt_push_udp_and_ip (vm, b, LISP_CONTROL_PORT, dst_port, sloc, dst);
3263
3264   bi_res[0] = bi;
3265   return b;
3266 }
3267
3268 static int
3269 send_map_reply (lisp_cp_main_t * lcm, u32 mi, ip_address_t * dst,
3270                 u8 probe_bit, u64 nonce, u16 dst_port,
3271                 ip_address_t * probed_loc)
3272 {
3273   ip_address_t src;
3274   u32 bi;
3275   vlib_buffer_t *b;
3276   vlib_frame_t *f;
3277   u32 next_index, *to_next;
3278   mapping_t *records = 0, *m;
3279
3280   m = pool_elt_at_index (lcm->mapping_pool, mi);
3281   if (!m)
3282     return -1;
3283
3284   vec_add1 (records, m[0]);
3285   add_locators (lcm, &records[0], m->locator_set_index, probed_loc);
3286   memset (&src, 0, sizeof (src));
3287
3288   if (!ip_fib_get_first_egress_ip_for_dst (lcm, dst, &src))
3289     {
3290       clib_warning ("can't find inteface address for %U", format_ip_address,
3291                     dst);
3292       return -1;
3293     }
3294
3295   b = build_map_reply (lcm, &src, dst, nonce, probe_bit, records, dst_port,
3296                        &bi);
3297   if (!b)
3298     return -1;
3299   free_map_register_records (records);
3300
3301   vnet_buffer (b)->sw_if_index[VLIB_TX] = 0;
3302   next_index = (ip_addr_version (&lcm->active_map_resolver) == IP4) ?
3303     ip4_lookup_node.index : ip6_lookup_node.index;
3304
3305   f = vlib_get_frame_to_node (lcm->vlib_main, next_index);
3306
3307   /* Enqueue the packet */
3308   to_next = vlib_frame_vector_args (f);
3309   to_next[0] = bi;
3310   f->n_vectors = 1;
3311   vlib_put_frame_to_node (lcm->vlib_main, next_index, f);
3312   return 0;
3313 }
3314
3315 static void
3316 find_ip_header (vlib_buffer_t * b, u8 ** ip_hdr)
3317 {
3318   const i32 start = vnet_buffer (b)->ip.start_of_ip_header;
3319   if (start < 0 && start < -sizeof (b->pre_data))
3320     {
3321       *ip_hdr = 0;
3322       return;
3323     }
3324
3325   *ip_hdr = b->data + start;
3326   if ((u8 *) * ip_hdr > (u8 *) vlib_buffer_get_current (b))
3327     *ip_hdr = 0;
3328 }
3329
3330 void
3331 process_map_request (vlib_main_t * vm, vlib_node_runtime_t * node,
3332                      lisp_cp_main_t * lcm, vlib_buffer_t * b)
3333 {
3334   u8 *ip_hdr = 0;
3335   ip_address_t *dst_loc = 0, probed_loc, src_loc;
3336   mapping_t m;
3337   map_request_hdr_t *mreq_hdr;
3338   gid_address_t src, dst;
3339   u64 nonce;
3340   u32 i, len = 0, rloc_probe_recv = 0;
3341   gid_address_t *itr_rlocs = 0;
3342
3343   mreq_hdr = vlib_buffer_get_current (b);
3344   if (!MREQ_SMR (mreq_hdr) && !MREQ_RLOC_PROBE (mreq_hdr))
3345     {
3346       clib_warning
3347         ("Only SMR Map-Requests and RLOC probe supported for now!");
3348       return;
3349     }
3350
3351   vlib_buffer_pull (b, sizeof (*mreq_hdr));
3352   nonce = MREQ_NONCE (mreq_hdr);
3353
3354   /* parse src eid */
3355   len = lisp_msg_parse_addr (b, &src);
3356   if (len == ~0)
3357     return;
3358
3359   len = lisp_msg_parse_itr_rlocs (b, &itr_rlocs,
3360                                   MREQ_ITR_RLOC_COUNT (mreq_hdr) + 1);
3361   if (len == ~0)
3362     goto done;
3363
3364   /* parse eid records and send SMR-invoked map-requests */
3365   for (i = 0; i < MREQ_REC_COUNT (mreq_hdr); i++)
3366     {
3367       memset (&dst, 0, sizeof (dst));
3368       len = lisp_msg_parse_eid_rec (b, &dst);
3369       if (len == ~0)
3370         {
3371           clib_warning ("Can't parse map-request EID-record");
3372           goto done;
3373         }
3374
3375       if (MREQ_SMR (mreq_hdr))
3376         {
3377           /* send SMR-invoked map-requests */
3378           queue_map_request (&dst, &src, 1 /* invoked */ , 0 /* resend */ );
3379         }
3380       else if (MREQ_RLOC_PROBE (mreq_hdr))
3381         {
3382           find_ip_header (b, &ip_hdr);
3383           if (!ip_hdr)
3384             {
3385               clib_warning ("Cannot find the IP header!");
3386               goto done;
3387             }
3388           rloc_probe_recv++;
3389           memset (&m, 0, sizeof (m));
3390           u32 mi = gid_dictionary_lookup (&lcm->mapping_index_by_gid, &dst);
3391
3392           // TODO: select best locator; for now use the first one
3393           dst_loc = &gid_address_ip (&itr_rlocs[0]);
3394
3395           /* get src/dst IP addresses */
3396           get_src_and_dst_ip (ip_hdr, &src_loc, &probed_loc);
3397
3398           // TODO get source port from buffer
3399           u16 src_port = LISP_CONTROL_PORT;
3400
3401           send_map_reply (lcm, mi, dst_loc, 1 /* probe-bit */ , nonce,
3402                           src_port, &probed_loc);
3403         }
3404     }
3405
3406 done:
3407   vlib_node_increment_counter (vm, node->node_index,
3408                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REQ_RECEIVED,
3409                                rloc_probe_recv);
3410   vec_free (itr_rlocs);
3411 }
3412
3413 static map_records_arg_t *
3414 parse_map_reply (vlib_buffer_t * b)
3415 {
3416   locator_t probed;
3417   gid_address_t deid;
3418   void *h;
3419   u32 i, len = 0;
3420   mapping_t m;
3421   map_reply_hdr_t *mrep_hdr;
3422   map_records_arg_t *a = clib_mem_alloc (sizeof (*a));
3423   memset (a, 0, sizeof (*a));
3424   locator_t *locators;
3425
3426   mrep_hdr = vlib_buffer_get_current (b);
3427   a->nonce = MREP_NONCE (mrep_hdr);
3428   a->is_rloc_probe = MREP_RLOC_PROBE (mrep_hdr);
3429   vlib_buffer_pull (b, sizeof (*mrep_hdr));
3430
3431   for (i = 0; i < MREP_REC_COUNT (mrep_hdr); i++)
3432     {
3433       memset (&m, 0, sizeof (m));
3434       locators = 0;
3435       h = vlib_buffer_get_current (b);
3436
3437       m.ttl = clib_net_to_host_u32 (MAP_REC_TTL (h));
3438       m.action = MAP_REC_ACTION (h);
3439       m.authoritative = MAP_REC_AUTH (h);
3440
3441       len = lisp_msg_parse_mapping_record (b, &deid, &locators, &probed);
3442       if (len == ~0)
3443         {
3444           clib_warning ("Failed to parse mapping record!");
3445           map_records_arg_free (a);
3446           return 0;
3447         }
3448
3449       m.locators = locators;
3450       gid_address_copy (&m.eid, &deid);
3451       vec_add1 (a->mappings, m);
3452     }
3453   return a;
3454 }
3455
3456 static void
3457 queue_map_reply_for_processing (map_records_arg_t * a)
3458 {
3459   vl_api_rpc_call_main_thread (process_map_reply, (u8 *) a, sizeof (*a));
3460 }
3461
3462 static void
3463 queue_map_notify_for_processing (map_records_arg_t * a)
3464 {
3465   vl_api_rpc_call_main_thread (process_map_notify, (u8 *) a, sizeof (a[0]));
3466 }
3467
3468 static uword
3469 lisp_cp_input (vlib_main_t * vm, vlib_node_runtime_t * node,
3470                vlib_frame_t * from_frame)
3471 {
3472   u32 n_left_from, *from, *to_next_drop, rloc_probe_rep_recv = 0,
3473     map_notifies_recv = 0;
3474   lisp_msg_type_e type;
3475   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3476   map_records_arg_t *a;
3477
3478   from = vlib_frame_vector_args (from_frame);
3479   n_left_from = from_frame->n_vectors;
3480
3481
3482   while (n_left_from > 0)
3483     {
3484       u32 n_left_to_next_drop;
3485
3486       vlib_get_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
3487                            to_next_drop, n_left_to_next_drop);
3488       while (n_left_from > 0 && n_left_to_next_drop > 0)
3489         {
3490           u32 bi0;
3491           vlib_buffer_t *b0;
3492
3493           bi0 = from[0];
3494           from += 1;
3495           n_left_from -= 1;
3496           to_next_drop[0] = bi0;
3497           to_next_drop += 1;
3498           n_left_to_next_drop -= 1;
3499
3500           b0 = vlib_get_buffer (vm, bi0);
3501
3502           type = lisp_msg_type (vlib_buffer_get_current (b0));
3503           switch (type)
3504             {
3505             case LISP_MAP_REPLY:
3506               a = parse_map_reply (b0);
3507               if (a)
3508                 {
3509                   if (a->is_rloc_probe)
3510                     rloc_probe_rep_recv++;
3511                   queue_map_reply_for_processing (a);
3512                 }
3513               break;
3514             case LISP_MAP_REQUEST:
3515               process_map_request (vm, node, lcm, b0);
3516               break;
3517             case LISP_MAP_NOTIFY:
3518               a = parse_map_notify (b0);
3519               if (a)
3520                 {
3521                   map_notifies_recv++;
3522                   queue_map_notify_for_processing (a);
3523                 }
3524               break;
3525             default:
3526               clib_warning ("Unsupported LISP message type %d", type);
3527               break;
3528             }
3529
3530           b0->error = node->errors[LISP_CP_INPUT_ERROR_DROP];
3531
3532           if (PREDICT_FALSE (b0->flags & VLIB_BUFFER_IS_TRACED))
3533             {
3534
3535             }
3536         }
3537
3538       vlib_put_next_frame (vm, node, LISP_CP_INPUT_NEXT_DROP,
3539                            n_left_to_next_drop);
3540     }
3541   vlib_node_increment_counter (vm, node->node_index,
3542                                LISP_CP_INPUT_ERROR_RLOC_PROBE_REP_RECEIVED,
3543                                rloc_probe_rep_recv);
3544   vlib_node_increment_counter (vm, node->node_index,
3545                                LISP_CP_INPUT_ERROR_MAP_NOTIFIES_RECEIVED,
3546                                map_notifies_recv);
3547   return from_frame->n_vectors;
3548 }
3549
3550 /* *INDENT-OFF* */
3551 VLIB_REGISTER_NODE (lisp_cp_input_node) = {
3552   .function = lisp_cp_input,
3553   .name = "lisp-cp-input",
3554   .vector_size = sizeof (u32),
3555   .format_trace = format_lisp_cp_input_trace,
3556   .type = VLIB_NODE_TYPE_INTERNAL,
3557
3558   .n_errors = LISP_CP_INPUT_N_ERROR,
3559   .error_strings = lisp_cp_input_error_strings,
3560
3561   .n_next_nodes = LISP_CP_INPUT_N_NEXT,
3562
3563   .next_nodes = {
3564       [LISP_CP_INPUT_NEXT_DROP] = "error-drop",
3565   },
3566 };
3567 /* *INDENT-ON* */
3568
3569 clib_error_t *
3570 lisp_cp_init (vlib_main_t * vm)
3571 {
3572   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3573   clib_error_t *error = 0;
3574
3575   if ((error = vlib_call_init_function (vm, lisp_gpe_init)))
3576     return error;
3577
3578   lcm->im4 = &ip4_main;
3579   lcm->im6 = &ip6_main;
3580   lcm->vlib_main = vm;
3581   lcm->vnet_main = vnet_get_main ();
3582   lcm->mreq_itr_rlocs = ~0;
3583   lcm->lisp_pitr = 0;
3584   lcm->flags = 0;
3585   memset (&lcm->active_map_resolver, 0, sizeof (lcm->active_map_resolver));
3586
3587   gid_dictionary_init (&lcm->mapping_index_by_gid);
3588   lcm->do_map_resolver_election = 1;
3589   lcm->map_request_mode = MR_MODE_DST_ONLY;
3590
3591   /* default vrf mapped to vni 0 */
3592   hash_set (lcm->table_id_by_vni, 0, 0);
3593   hash_set (lcm->vni_by_table_id, 0, 0);
3594
3595   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp,
3596                          lisp_cp_input_node.index, 1 /* is_ip4 */ );
3597   udp_register_dst_port (vm, UDP_DST_PORT_lisp_cp6,
3598                          lisp_cp_input_node.index, 0 /* is_ip4 */ );
3599
3600   u64 now = clib_cpu_time_now ();
3601   timing_wheel_init (&lcm->wheel, now, vm->clib_time.clocks_per_second);
3602   return 0;
3603 }
3604
3605 static int
3606 lisp_stats_api_fill (lisp_cp_main_t * lcm, lisp_gpe_main_t * lgm,
3607                      lisp_api_stats_t * stat, lisp_stats_key_t * key,
3608                      u32 stats_index)
3609 {
3610   lisp_stats_t *s;
3611   lisp_gpe_fwd_entry_key_t fwd_key;
3612   const lisp_gpe_tunnel_t *lgt;
3613   fwd_entry_t *fe;
3614
3615   memset (stat, 0, sizeof (*stat));
3616   memset (&fwd_key, 0, sizeof (fwd_key));
3617
3618   fe = pool_elt_at_index (lcm->fwd_entry_pool, key->fwd_entry_index);
3619   ASSERT (fe != 0);
3620
3621   gid_to_dp_address (&fe->reid, &stat->deid);
3622   gid_to_dp_address (&fe->leid, &stat->seid);
3623   stat->vni = gid_address_vni (&fe->reid);
3624
3625   lgt = lisp_gpe_tunnel_get (key->tunnel_index);
3626   stat->loc_rloc = lgt->key->lcl;
3627   stat->rmt_rloc = lgt->key->rmt;
3628
3629   s = pool_elt_at_index (lgm->lisp_stats_pool, stats_index);
3630   stat->stats = *s;
3631   return 1;
3632 }
3633
3634 lisp_api_stats_t *
3635 vnet_lisp_get_stats (void)
3636 {
3637   lisp_gpe_main_t *lgm = vnet_lisp_gpe_get_main ();
3638   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3639   lisp_api_stats_t *stats = 0, stat;
3640   lisp_stats_key_t *key;
3641   u32 index;
3642
3643   /* *INDENT-OFF* */
3644   hash_foreach_mem (key, index, lgm->lisp_stats_index_by_key,
3645   {
3646     if (lisp_stats_api_fill (lcm, lgm, &stat, key, index))
3647       vec_add1 (stats, stat);
3648   });
3649   /* *INDENT-ON* */
3650
3651   return stats;
3652 }
3653
3654 static void *
3655 send_map_request_thread_fn (void *arg)
3656 {
3657   map_request_args_t *a = arg;
3658   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3659
3660   if (a->is_resend)
3661     resend_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
3662   else
3663     send_encapsulated_map_request (lcm, &a->seid, &a->deid, a->smr_invoked);
3664
3665   return 0;
3666 }
3667
3668 static int
3669 queue_map_request (gid_address_t * seid, gid_address_t * deid,
3670                    u8 smr_invoked, u8 is_resend)
3671 {
3672   map_request_args_t a;
3673
3674   a.is_resend = is_resend;
3675   gid_address_copy (&a.seid, seid);
3676   gid_address_copy (&a.deid, deid);
3677   a.smr_invoked = smr_invoked;
3678
3679   vl_api_rpc_call_main_thread (send_map_request_thread_fn,
3680                                (u8 *) & a, sizeof (a));
3681   return 0;
3682 }
3683
3684 /**
3685  * Take an action with a pending map request depending on expiration time
3686  * and re-try counters.
3687  */
3688 static void
3689 update_pending_request (pending_map_request_t * r, f64 dt)
3690 {
3691   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3692   lisp_msmr_t *mr;
3693
3694   if (r->time_to_expire - dt < 0)
3695     /* it's time to decide what to do with this pending request */
3696     {
3697       if (r->retries_num >= NUMBER_OF_RETRIES)
3698         /* too many retries -> assume current map resolver is not available */
3699         {
3700           mr = get_map_resolver (&lcm->active_map_resolver);
3701           if (!mr)
3702             {
3703               clib_warning ("Map resolver %U not found - probably deleted "
3704                             "by the user recently.", format_ip_address,
3705                             &lcm->active_map_resolver);
3706             }
3707           else
3708             {
3709               clib_warning ("map resolver %U is unreachable, ignoring",
3710                             format_ip_address, &lcm->active_map_resolver);
3711
3712               /* mark current map resolver unavailable so it won't be
3713                * selected next time */
3714               mr->is_down = 1;
3715               mr->last_update = vlib_time_now (lcm->vlib_main);
3716             }
3717
3718           reset_pending_mr_counters (r);
3719           elect_map_resolver (lcm);
3720
3721           /* try to find a next eligible map resolver and re-send */
3722           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
3723                              1 /* resend */ );
3724         }
3725       else
3726         {
3727           /* try again */
3728           queue_map_request (&r->src, &r->dst, r->is_smr_invoked,
3729                              1 /* resend */ );
3730           r->retries_num++;
3731           r->time_to_expire = PENDING_MREQ_EXPIRATION_TIME;
3732         }
3733     }
3734   else
3735     r->time_to_expire -= dt;
3736 }
3737
3738 static void
3739 remove_dead_pending_map_requests (lisp_cp_main_t * lcm)
3740 {
3741   u64 *nonce;
3742   pending_map_request_t *pmr;
3743   u32 *to_be_removed = 0, *pmr_index;
3744
3745   /* *INDENT-OFF* */
3746   pool_foreach (pmr, lcm->pending_map_requests_pool,
3747   ({
3748     if (pmr->to_be_removed)
3749       {
3750         clib_fifo_foreach (nonce, pmr->nonces, ({
3751           hash_unset (lcm->pending_map_requests_by_nonce, nonce[0]);
3752         }));
3753
3754         vec_add1 (to_be_removed, pmr - lcm->pending_map_requests_pool);
3755       }
3756   }));
3757   /* *INDENT-ON* */
3758
3759   vec_foreach (pmr_index, to_be_removed)
3760     pool_put_index (lcm->pending_map_requests_by_nonce, pmr_index[0]);
3761
3762   vec_free (to_be_removed);
3763 }
3764
3765 static void
3766 update_rloc_probing (lisp_cp_main_t * lcm, f64 dt)
3767 {
3768   static f64 time_left = RLOC_PROBING_INTERVAL;
3769
3770   if (!lcm->is_enabled || !lcm->rloc_probing)
3771     return;
3772
3773   time_left -= dt;
3774   if (time_left <= 0)
3775     {
3776       time_left = RLOC_PROBING_INTERVAL;
3777       send_rloc_probes (lcm);
3778     }
3779 }
3780
3781 static void
3782 update_map_register (lisp_cp_main_t * lcm, f64 dt)
3783 {
3784   static f64 time_left = QUICK_MAP_REGISTER_INTERVAL;
3785   static u64 mreg_sent_counter = 0;
3786
3787   if (!lcm->is_enabled || !lcm->map_registering)
3788     return;
3789
3790   time_left -= dt;
3791   if (time_left <= 0)
3792     {
3793       if (mreg_sent_counter >= QUICK_MAP_REGISTER_MSG_COUNT)
3794         time_left = MAP_REGISTER_INTERVAL;
3795       else
3796         {
3797           mreg_sent_counter++;
3798           time_left = QUICK_MAP_REGISTER_INTERVAL;
3799         }
3800       send_map_register (lcm, 1 /* want map notify */ );
3801     }
3802 }
3803
3804 static uword
3805 send_map_resolver_service (vlib_main_t * vm,
3806                            vlib_node_runtime_t * rt, vlib_frame_t * f)
3807 {
3808   u32 *expired = 0;
3809   f64 period = 2.0;
3810   pending_map_request_t *pmr;
3811   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3812
3813   while (1)
3814     {
3815       vlib_process_wait_for_event_or_clock (vm, period);
3816
3817       /* currently no signals are expected - just wait for clock */
3818       (void) vlib_process_get_events (vm, 0);
3819
3820       /* *INDENT-OFF* */
3821       pool_foreach (pmr, lcm->pending_map_requests_pool,
3822       ({
3823         if (!pmr->to_be_removed)
3824           update_pending_request (pmr, period);
3825       }));
3826       /* *INDENT-ON* */
3827
3828       remove_dead_pending_map_requests (lcm);
3829
3830       update_map_register (lcm, period);
3831       update_rloc_probing (lcm, period);
3832
3833       u64 now = clib_cpu_time_now ();
3834
3835       expired = timing_wheel_advance (&lcm->wheel, now, expired, 0);
3836       if (vec_len (expired) > 0)
3837         {
3838           u32 *mi = 0;
3839           vec_foreach (mi, expired)
3840           {
3841             remove_expired_mapping (lcm, mi[0]);
3842           }
3843           _vec_len (expired) = 0;
3844         }
3845     }
3846
3847   /* unreachable */
3848   return 0;
3849 }
3850
3851 vnet_api_error_t
3852 vnet_lisp_stats_enable_disable (u8 enable)
3853 {
3854   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3855
3856   if (vnet_lisp_enable_disable_status () == 0)
3857     return VNET_API_ERROR_LISP_DISABLED;
3858
3859   if (enable)
3860     lcm->flags |= LISP_FLAG_STATS_ENABLED;
3861   else
3862     lcm->flags &= ~LISP_FLAG_STATS_ENABLED;
3863
3864   return 0;
3865 }
3866
3867 u8
3868 vnet_lisp_stats_enable_disable_state (void)
3869 {
3870   lisp_cp_main_t *lcm = vnet_lisp_cp_get_main ();
3871
3872   if (vnet_lisp_enable_disable_status () == 0)
3873     return VNET_API_ERROR_LISP_DISABLED;
3874
3875   return lcm->flags & LISP_FLAG_STATS_ENABLED;
3876 }
3877
3878 /* *INDENT-OFF* */
3879 VLIB_REGISTER_NODE (lisp_retry_service_node,static) = {
3880     .function = send_map_resolver_service,
3881     .type = VLIB_NODE_TYPE_PROCESS,
3882     .name = "lisp-retry-service",
3883     .process_log2_n_stack_bytes = 16,
3884 };
3885 /* *INDENT-ON* */
3886
3887 VLIB_INIT_FUNCTION (lisp_cp_init);
3888
3889 /*
3890  * fd.io coding-style-patch-verification: ON
3891  *
3892  * Local Variables:
3893  * eval: (c-set-style "gnu")
3894  * End:
3895  */