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