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