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