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