aafa90526fd046d0effb476d75edaa05bc850a75
[oweals/gnunet.git] / src / ats / gnunet-service-ats_addresses.c
1 /*
2      This file is part of GNUnet.
3      (C) 2011 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file ats/gnunet-service-ats_addresses.c
23  * @brief ats service address management
24  * @author Matthias Wachs
25  * @author Christian Grothoff
26  */
27 #include "platform.h"
28 #include "gnunet_ats_service.h"
29 #include "gnunet-service-ats.h"
30 #include "gnunet-service-ats_addresses.h"
31 #include "gnunet-service-ats_performance.h"
32 #include "gnunet-service-ats_scheduling.h"
33 #include "gnunet-service-ats_reservations.h"
34 #if HAVE_LIBGLPK
35 #include "gnunet-service-ats_addresses_mlp.h"
36 #endif
37
38 #define ATS_BLOCKING_DELTA GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100)
39
40 enum ATS_Mode
41 {
42   /*
43    * Assign each peer an equal amount of bandwidth (bw)
44    *
45    * bw_per_peer = bw_total / #active addresses
46    */
47   SIMPLE,
48
49   /*
50    * Use MLP solver to assign bandwidth
51    */
52   MLP
53 };
54
55 static struct GNUNET_CONTAINER_MultiHashMap *addresses;
56
57 #if HAVE_LIBGLPK
58 static struct GAS_MLP_Handle *mlp;
59 #endif
60
61 static unsigned long long wan_quota_in;
62
63 static unsigned long long wan_quota_out;
64
65 static unsigned int active_addr_count;
66
67 static int ats_mode;
68
69 static int running;
70
71
72 static void
73 send_bw_notification (struct ATS_Address *aa)
74 {
75   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "New bandwidth for peer %s is %u/%u\n",
76               GNUNET_i2s (&aa->peer), ntohl (aa->assigned_bw_in.value__),
77               ntohl (aa->assigned_bw_out.value__));
78   GAS_scheduling_transmit_address_suggestion (&aa->peer, aa->plugin, aa->addr,
79                                               aa->addr_len, aa->session_id,
80                                               aa->ats, aa->ats_count,
81                                               aa->assigned_bw_out,
82                                               aa->assigned_bw_in);
83   GAS_reservations_set_bandwidth (&aa->peer, aa->assigned_bw_in);
84   GAS_performance_notify_all_clients (&aa->peer, aa->plugin, aa->addr, aa->addr_len,
85                                   aa->ats, aa->ats_count, aa->assigned_bw_out,
86                                   aa->assigned_bw_in);
87 }
88
89 /**
90  * Update a bandwidth assignment for a peer.  This trivial method currently
91  * simply assigns the same share to all active connections.
92  *
93  * @param cls unused
94  * @param key unused
95  * @param value the 'struct ATS_Address'
96  * @return GNUNET_OK (continue to iterate)
97  */
98 static int
99 update_bw_simple_it (void *cls, const struct GNUNET_HashCode * key, void *value)
100 {
101   struct ATS_Address *aa = value;
102
103   if (GNUNET_YES != aa->active)
104     return GNUNET_OK;
105   GNUNET_assert (active_addr_count > 0);
106
107
108   /* Simple method */
109   aa->assigned_bw_in.value__ = htonl (wan_quota_in / active_addr_count);
110   aa->assigned_bw_out.value__ = htonl (wan_quota_out / active_addr_count);
111
112   send_bw_notification (aa);
113
114   return GNUNET_OK;
115 }
116
117
118 /**
119  * Some (significant) input changed, recalculate bandwidth assignment
120  * for all peers.
121  */
122 static void
123 recalculate_assigned_bw ()
124 {
125   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
126               "Recalculating bandwidth for all active connections\n");
127   GNUNET_STATISTICS_update (GSA_stats, "# bandwidth recalculations performed",
128                             1, GNUNET_NO);
129   GNUNET_STATISTICS_set (GSA_stats, "# active addresses", active_addr_count,
130                          GNUNET_NO);
131
132   GNUNET_CONTAINER_multihashmap_iterate (addresses, &update_bw_simple_it, NULL);
133 }
134
135 /**
136  * Free the given address
137  * @param addr address to destroy
138  */
139 static void
140 free_address (struct ATS_Address *addr)
141 {
142   GNUNET_free_non_null (addr->ats);
143   GNUNET_free (addr->plugin);
144   GNUNET_free (addr);
145 }
146
147 /**
148  * Create a ATS_address with the given information
149  * @param peer peer
150  * @param plugin_name plugin
151  * @param plugin_addr address
152  * @param plugin_addr_len address length
153  * @param session_id session
154  * @return the ATS_Address
155  */
156 static struct ATS_Address *
157 create_address (const struct GNUNET_PeerIdentity *peer,
158                 const char *plugin_name,
159                 const void *plugin_addr, size_t plugin_addr_len,
160                 uint32_t session_id)
161 {
162   struct ATS_Address *aa = NULL;
163
164   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
165   aa->peer = *peer;
166   aa->addr_len = plugin_addr_len;
167   aa->addr = &aa[1];
168   memcpy (&aa[1], plugin_addr, plugin_addr_len);
169   aa->plugin = GNUNET_strdup (plugin_name);
170   aa->session_id = session_id;
171   return aa;
172 }
173
174
175 /**
176  * Destroy the given address.
177  *
178  * @param addr address to destroy
179  * @return GNUNET_YES if bandwidth allocations should be recalcualted
180  */
181 static int
182 destroy_address (struct ATS_Address *addr)
183 {
184   int ret;
185
186   ret = GNUNET_NO;
187   GNUNET_assert (GNUNET_YES ==
188                  GNUNET_CONTAINER_multihashmap_remove (addresses,
189                                                        &addr->peer.hashPubKey,
190                                                        addr));
191
192 #if HAVE_LIBGLPK
193   if (ats_mode == MLP)
194     GAS_mlp_address_delete (mlp, addresses, addr);
195 #endif
196
197   if (GNUNET_YES == addr->active)
198   {
199     active_addr_count--;
200     addr->active = GNUNET_NO;
201     ret = GNUNET_YES;
202   }
203   free_address (addr);
204   return ret;
205 }
206
207
208 struct CompareAddressContext
209 {
210   const struct ATS_Address *search;
211
212   /* exact_address != NULL if address and session is equal */
213   struct ATS_Address *exact_address;
214   /* exact_address != NULL if address and session is 0 */
215   struct ATS_Address *base_address;
216 };
217
218
219 static int
220 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
221 {
222   struct CompareAddressContext *cac = cls;
223   struct ATS_Address *aa = value;
224
225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing peer %4s: address length %u session %u <-> address length %u session %u\n",
226       GNUNET_h2s (key),
227       aa->addr_len, aa->session_id,
228       cac->search->addr_len, cac->search->session_id);
229
230   /* Find an matching exact address:
231    *
232    * Compare by:
233    * aa->addr_len == cac->search->addr_len
234    * aa->plugin == cac->search->plugin
235    * aa->addr == cac->search->addr
236    * aa->session == cac->search->session
237    *
238    * return as exact address
239    */
240   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
241   {
242       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
243         cac->exact_address = aa;
244   }
245
246   /* Find an matching base address:
247    *
248    * Properties:
249    *
250    * aa->session_id == 0
251    *
252    * Compare by:
253    * aa->addr_len == cac->search->addr_len
254    * aa->plugin == cac->search->plugin
255    * aa->addr == cac->search->addr
256    *
257    * return as base address
258    */
259   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
260   {
261       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == 0))
262         cac->base_address = aa;
263   }
264
265   /* Find an matching exact address based on session:
266    *
267    * Properties:
268    *
269    * cac->search->addr_len == 0
270    *
271    * Compare by:
272    * aa->plugin == cac->search->plugin
273    * aa->session_id == cac->search->session_id
274    *
275    * return as exact address
276    */
277   if (0 == cac->search->addr_len)
278   {
279       if ((0 == strcmp (aa->plugin, cac->search->plugin)) && (aa->session_id == cac->search->session_id))
280         cac->exact_address = aa;
281   }
282
283   if (cac->exact_address == NULL)
284     return GNUNET_YES; /* Continue iteration to find exact address */
285   else
286     return GNUNET_NO; /* Stop iteration since we have an exact address */
287 }
288
289
290 /**
291  * Find an existing equivalent address record.
292  * Compares by peer identity and network address OR by session ID
293  * (one of the two must match).
294  *
295  * @param peer peer to lookup addresses for
296  * @param addr existing address record
297  * @return existing address record, NULL for none
298  */
299 struct ATS_Address *
300 find_address (const struct GNUNET_PeerIdentity *peer,
301               const struct ATS_Address *addr)
302 {
303   struct CompareAddressContext cac;
304
305   cac.exact_address = NULL;
306   cac.base_address = NULL;
307   cac.search = addr;
308   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
309                                               &compare_address_it, &cac);
310
311 #if 0
312   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
313               "Found exact address: %s           base address: %s\n",
314               (cac.exact_address != NULL) ? "YES" : "NO",
315               (cac.base_address != NULL) ? "YES" : "NO");
316 #endif
317   if (cac.exact_address == NULL)
318     return cac.base_address;
319   return cac.exact_address;
320 }
321
322
323 static struct ATS_Address *
324 lookup_address (const struct GNUNET_PeerIdentity *peer,
325                 const char *plugin_name, const void *plugin_addr,
326                 size_t plugin_addr_len, uint32_t session_id,
327                 const struct GNUNET_ATS_Information *atsi,
328                 uint32_t atsi_count)
329 {
330   struct ATS_Address *aa;
331   struct ATS_Address *old;
332
333   aa = create_address (peer,
334                        plugin_name,
335                        plugin_addr, plugin_addr_len,
336                        session_id);
337
338   aa->mlp_information = NULL;
339   aa->ats = GNUNET_malloc (atsi_count * sizeof (struct GNUNET_ATS_Information));
340   aa->ats_count = atsi_count;
341   memcpy (aa->ats, atsi, atsi_count * sizeof (struct GNUNET_ATS_Information));
342
343   /* Get existing address or address with session == 0 */
344   old = find_address (peer, aa);
345   free_address (aa);
346   if (old == NULL)
347   {
348     return NULL;
349   }
350   else if (old->session_id != session_id)
351   {
352     return NULL;
353   }
354   return old;
355 }
356
357
358 #if DEADCODE
359 static int
360 compare_address_session_it (void *cls, const struct GNUNET_HashCode * key, void *value)
361 {
362   struct CompareAddressContext *cac = cls;
363   struct ATS_Address *aa = value;
364
365   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
366   {
367       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
368       {
369         cac->exact_address = aa;
370         return GNUNET_NO;
371       }
372   }
373   return GNUNET_YES;
374 }
375
376
377 /**
378  * Find an existing equivalent address record.
379  * Compares by peer identity and network address AND by session ID
380  * (one of the two must match).
381  *
382  * @param peer peer to lookup addresses for
383  * @param addr existing address record
384  * @return existing address record, NULL for none
385  */
386 static struct ATS_Address *
387 find_exact_address (const struct GNUNET_PeerIdentity *peer,
388               const struct ATS_Address *addr)
389 {
390   struct CompareAddressContext cac;
391
392   cac.exact_address = NULL;
393   cac.search = addr;
394   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
395                                               &compare_address_session_it, &cac);
396   return cac.exact_address;
397 }
398 #endif
399
400
401 void
402 GAS_addresses_add (const struct GNUNET_PeerIdentity *peer,
403                       const char *plugin_name, const void *plugin_addr,
404                       size_t plugin_addr_len, uint32_t session_id,
405                       const struct GNUNET_ATS_Information *atsi,
406                       uint32_t atsi_count)
407 {
408   struct ATS_Address *aa;
409   struct ATS_Address *old;
410
411   if (GNUNET_NO == running)
412     return;
413
414   GNUNET_assert (NULL != addresses);
415
416   aa = create_address (peer,
417                        plugin_name,
418                        plugin_addr, plugin_addr_len,
419                        session_id);
420
421   aa->mlp_information = NULL;
422   aa->ats = GNUNET_malloc (atsi_count * sizeof (struct GNUNET_ATS_Information));
423   aa->ats_count = atsi_count;
424   memcpy (aa->ats, atsi, atsi_count * sizeof (struct GNUNET_ATS_Information));
425
426   /* Get existing address or address with session == 0 */
427   old = find_address (peer, aa);
428   if (old == NULL)
429   {
430     /* We have a new address */
431     GNUNET_assert (GNUNET_OK ==
432                    GNUNET_CONTAINER_multihashmap_put (addresses,
433                                                       &peer->hashPubKey, aa,
434                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
435     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
436                 GNUNET_i2s (peer), session_id, aa);
437     return;
438   }
439
440   if (old->session_id == 0)
441   {
442     /* We have a base address with out an session, update this address */
443     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
444               "Updated existing address for peer `%s' %p with new session %u\n",
445               GNUNET_i2s (peer), old, session_id);
446     GNUNET_free_non_null (old->ats);
447     old->session_id = session_id;
448     old->ats = NULL;
449     old->ats_count = 0;
450     old->ats = aa->ats;
451     old->ats_count = aa->ats_count;
452     GNUNET_free (aa->plugin);
453     GNUNET_free (aa);
454     return;
455   }
456
457   /* This address and session is already existing */
458   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
459             "Added already existing address for peer `%s' `%s' %p with new session %u\n",
460             GNUNET_i2s (peer), plugin_name, session_id);
461   GNUNET_break (0);
462 }
463
464
465 void
466 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
467                       const char *plugin_name, const void *plugin_addr,
468                       size_t plugin_addr_len, uint32_t session_id,
469                       const struct GNUNET_ATS_Information *atsi,
470                       uint32_t atsi_count)
471 {
472   struct ATS_Address *old;
473   uint32_t i;
474
475   if (GNUNET_NO == running)
476     return;
477
478   GNUNET_assert (NULL != addresses);
479
480   /* Get existing address */
481   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
482                        session_id, atsi, atsi_count);
483   if (old == NULL)
484   {
485     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
486                 GNUNET_i2s (peer), plugin_name, session_id);
487     GNUNET_break (0);
488     return;
489   }
490
491   for (i = 0; i < atsi_count; i++)
492     switch (ntohl (atsi[i].type))
493     {
494     case GNUNET_ATS_UTILIZATION_UP:
495       old->atsp_utilization_out.value__ = atsi[i].value;
496       break;
497     case GNUNET_ATS_UTILIZATION_DOWN:
498       old->atsp_utilization_in.value__ = atsi[i].value;
499       break;
500     case GNUNET_ATS_QUALITY_NET_DELAY:
501       old->atsp_latency.rel_value = ntohl (atsi[i].value);
502       break;
503     case GNUNET_ATS_QUALITY_NET_DISTANCE:
504       old->atsp_distance = ntohl (atsi[i].value);
505       break;
506     case GNUNET_ATS_COST_WAN:
507       old->atsp_cost_wan = ntohl (atsi[i].value);
508       break;
509     case GNUNET_ATS_COST_LAN:
510       old->atsp_cost_lan = ntohl (atsi[i].value);
511       break;
512     case GNUNET_ATS_COST_WLAN:
513       old->atsp_cost_wlan = ntohl (atsi[i].value);
514       break;
515     case GNUNET_ATS_NETWORK_TYPE:
516       old->atsp_network_type = ntohl (atsi[i].value);
517       break;
518
519     default:
520       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
521                   "Received unsupported ATS type %u\n", ntohl (atsi[i].type));
522       GNUNET_break (0);
523       break;
524     }
525 #if HAVE_LIBGLPK
526   if (ats_mode == MLP)
527     GAS_mlp_address_update (mlp, addresses, old);
528 #endif
529 }
530
531
532 /**
533  * Delete an address
534  *
535  * If session != 0, just the session is deleted, the address itself still exists
536  * If session == 0, remove full address
537  * If session == 0 and addrlen == 0, destroy inbound address
538  *
539  * @param cls unused
540  * @param key unused
541  * @param value the 'struct ATS_Address'
542  * @return GNUNET_OK (continue to iterate)
543  */
544 static int
545 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
546 {
547   const struct ATS_Address *info = cls;
548   struct ATS_Address *aa = value;
549
550   GNUNET_assert (0 ==
551                  memcmp (&aa->peer, &info->peer,
552                          sizeof (struct GNUNET_PeerIdentity)));
553   /* session == 0, remove full address  */
554   if ((info->session_id == 0) && (0 == strcmp (info->plugin, aa->plugin)) &&
555       (aa->addr_len == info->addr_len) &&
556       (0 == memcmp (info->addr, aa->addr, aa->addr_len)))
557   {
558
559     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
560                 "Deleting address for peer `%s': `%s' %u\n",
561                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
562
563     if (GNUNET_YES == destroy_address (aa))
564       recalculate_assigned_bw ();
565     return GNUNET_OK;
566   }
567   /* session != 0, just remove session */
568   if (aa->session_id != info->session_id)
569     return GNUNET_OK;           /* irrelevant */
570   if (aa->session_id != 0)
571     GNUNET_break (0 == strcmp (info->plugin, aa->plugin));
572   /* session died */
573   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
574               "Deleting session for peer `%s': `%s' %u\n",
575               GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
576   aa->session_id = 0;
577
578   if (GNUNET_YES == aa->active)
579   {
580     aa->active = GNUNET_NO;
581     active_addr_count--;
582     recalculate_assigned_bw ();
583   }
584
585   /* session == 0 and addrlen == 0 : destroy address */
586   if (aa->addr_len == 0)
587   {
588     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
589                 "Deleting session and address for peer `%s': `%s' %u\n",
590                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
591     (void) destroy_address (aa);
592   }
593   else
594   {
595     /* session was set to 0, update address */
596 #if HAVE_LIBGLPK
597   if (ats_mode == MLP)
598     GAS_mlp_address_update (mlp, addresses, aa);
599 #endif
600   }
601
602   return GNUNET_OK;
603 }
604
605
606 void
607 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
608                        const char *plugin_name, const void *plugin_addr,
609                        size_t plugin_addr_len, uint32_t session_id)
610 {
611   struct ATS_Address *aa;
612   struct ATS_Address *old;
613
614   if (GNUNET_NO == running)
615     return;
616
617   /* Get existing address */
618   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
619                        session_id, NULL, 0);
620   if (old == NULL)
621   {
622     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
623                 GNUNET_i2s (peer), plugin_name, session_id);
624     return;
625   }
626
627
628   GNUNET_break (0 < strlen (plugin_name));
629   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
630
631   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
632                                               &destroy_by_session_id, aa);
633
634   free_address (aa);
635 }
636
637
638 /**
639  * Find a "good" address to use for a peer.  If we already have an existing
640  * address, we stick to it.  Otherwise, we pick by lowest distance and then
641  * by lowest latency.
642  *
643  * @param cls the 'struct ATS_Address**' where we store the result
644  * @param key unused
645  * @param value another 'struct ATS_Address*' to consider using
646  * @return GNUNET_OK (continue to iterate)
647  */
648 static int
649 find_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
650 {
651   struct ATS_Address **ap = cls;
652   struct ATS_Address *aa = (struct ATS_Address *) value;
653   struct ATS_Address *ab = *ap;
654   struct GNUNET_TIME_Absolute now;
655
656   now = GNUNET_TIME_absolute_get();
657
658   if (aa->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, aa->blocked_until).abs_value)
659   {
660     /* This address is blocked for suggestion */
661     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
662                 "Address %p blocked for suggestion for %llu ms \n",
663                 aa,
664                 GNUNET_TIME_absolute_get_difference(now, aa->blocked_until).rel_value);
665     return GNUNET_OK;
666   }
667
668   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
669   aa->blocked_until = GNUNET_TIME_absolute_add (now, aa->block_interval);
670
671   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
672               "Address %p ready for suggestion, block interval now %llu \n", aa, aa->block_interval);
673
674   /* FIXME this is a hack */
675
676
677   if (NULL != ab)
678   {
679     if ((0 == strcmp (ab->plugin, "tcp")) &&
680         (0 == strcmp (aa->plugin, "tcp")))
681     {
682       if ((0 != ab->addr_len) &&
683           (0 == aa->addr_len))
684       {
685         /* saved address was an outbound address, but we have an inbound address */
686         *ap = aa;
687         return GNUNET_OK;
688       }
689       if (0 == ab->addr_len)
690       {
691         /* saved address was an inbound address, so do not overwrite */
692         return GNUNET_OK;
693       }
694     }
695   }
696   /* FIXME end of hack */
697
698   if (NULL == ab)
699   {
700     *ap = aa;
701     return GNUNET_OK;
702   }
703   if ((ntohl (ab->assigned_bw_in.value__) == 0) &&
704       (ntohl (aa->assigned_bw_in.value__) > 0))
705   {
706     /* stick to existing connection */
707     *ap = aa;
708     return GNUNET_OK;
709   }
710   if (ab->atsp_distance > aa->atsp_distance)
711   {
712     /* user shorter distance */
713     *ap = aa;
714     return GNUNET_OK;
715   }
716   if (ab->atsp_latency.rel_value > aa->atsp_latency.rel_value)
717   {
718     /* user lower latency */
719     *ap = aa;
720     return GNUNET_OK;
721   }
722   /* don't care */
723   return GNUNET_OK;
724 }
725
726
727 int
728 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
729                       const char *plugin_name, const void *plugin_addr,
730                       size_t plugin_addr_len, uint32_t session_id, int in_use)
731 {
732 #if DEBUG_ATS
733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734               "Received `%s' message for peer `%s': %i\n", "ADDRESS_IN_USE",
735               GNUNET_i2s (peer), in_use);
736 #endif
737
738   struct ATS_Address *old;
739
740   if (GNUNET_NO == running)
741     return GNUNET_SYSERR;
742
743   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id, NULL, 0);
744   if (NULL == old)
745   {
746     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
747                 "Trying to set unknown address `%s', %s %u %s \n",
748                 GNUNET_i2s (peer),
749                 plugin_name, session_id,
750                 (GNUNET_NO == in_use) ? "NO" : "YES");
751     GNUNET_break (0);
752     return GNUNET_SYSERR;
753   }
754   if (old->used == in_use)
755   {
756     GNUNET_break (0);
757     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
758                 "Address in use called multiple times for peer `%s': %s -> %s \n",
759                 GNUNET_i2s (peer),
760                 (GNUNET_NO == old->used) ? "NO" : "YES",
761                 (GNUNET_NO == in_use) ? "NO" : "YES");
762     return GNUNET_SYSERR;
763   }
764   old->used = in_use;
765 #if HAVE_LIBGLPK
766   if (ats_mode == MLP)
767      GAS_mlp_address_update (mlp, addresses, old);
768 #endif
769   return GNUNET_OK;
770 }
771
772
773 static void 
774 request_address_mlp (const struct GNUNET_PeerIdentity *peer)
775 {
776   struct ATS_Address *aa;
777   aa = NULL;
778
779 #if HAVE_GLPK
780   /* Get preferred address from MLP */
781   struct ATS_PreferedAddress * paddr = NULL;
782   paddr = GAS_mlp_get_preferred_address (mlp, addresses, peer);
783   aa = paddr->address;
784   aa->assigned_bw_out = GNUNET_BANDWIDTH_value_init(paddr->bandwidth_out);
785   /* FIXME use bw in value */
786   paddr->bandwidth_in = paddr->bandwidth_out;
787   aa->assigned_bw_in = GNUNET_BANDWIDTH_value_init (paddr->bandwidth_in);
788   GNUNET_free (paddr);
789 #endif
790
791   if (aa == NULL)
792   {
793     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
794                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
795     return;
796   }
797   if (aa->active == GNUNET_NO)
798   {
799     aa->active = GNUNET_YES;
800     active_addr_count++;
801
802     send_bw_notification (aa);
803   }
804   else
805   {
806     /* just to be sure... */
807     GAS_scheduling_transmit_address_suggestion (peer, aa->plugin, aa->addr,
808                                                 aa->addr_len, aa->session_id,
809                                                 aa->ats, aa->ats_count,
810                                                 aa->assigned_bw_out,
811                                                 aa->assigned_bw_in);
812   }
813
814 }
815
816
817 static void 
818 request_address_simple (const struct GNUNET_PeerIdentity *peer)
819 {
820   struct ATS_Address *aa;
821   aa = NULL;
822
823   /* Get address with: stick to current address, lower distance, lower latency */
824   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
825                                               &find_address_it, &aa);
826   if (aa == NULL)
827   {
828     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
829                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
830     return;
831   }
832
833   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
834               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
835
836   if (aa->active == GNUNET_NO)
837   {
838     aa->active = GNUNET_YES;
839     active_addr_count++;
840     if (ats_mode == SIMPLE)
841     {
842       recalculate_assigned_bw ();
843     }
844   }
845   else
846   {
847     /* just to be sure... */
848     GAS_scheduling_transmit_address_suggestion (peer, aa->plugin, aa->addr,
849                                                 aa->addr_len, aa->session_id,
850                                                 aa->ats, aa->ats_count,
851                                                 aa->assigned_bw_out,
852                                                 aa->assigned_bw_in);
853   }
854 }
855
856
857 void
858 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
859 {
860   if (GNUNET_NO == running)
861     return;
862
863   if (ats_mode == SIMPLE)
864   {
865     request_address_simple (peer);
866   }
867   if (ats_mode == MLP)
868   {
869     request_address_mlp(peer);
870   }
871 }
872
873
874 static int
875 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
876 {
877   struct ATS_Address *aa = value;
878
879   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
880               "Resetting interval for peer `%s' address %p from %llu to 0\n", GNUNET_i2s (&aa->peer), aa, aa->block_interval);
881
882   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
883   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
884   return GNUNET_OK;
885 }
886
887
888 void
889 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
890 {
891   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (addresses,
892                                               &peer->hashPubKey,
893                                               &reset_address_it,
894                                               NULL));
895 }
896
897
898
899 // FIXME: this function should likely end up in the LP-subsystem and
900 // not with 'addresses' in the future...
901 void
902 GAS_addresses_change_preference (const struct GNUNET_PeerIdentity *peer,
903                                  enum GNUNET_ATS_PreferenceKind kind,
904                                  float score)
905 {
906   if (GNUNET_NO == running)
907     return;
908 #if HAVE_LIBGLPK
909   if (ats_mode == MLP)
910     GAS_mlp_address_change_preference (mlp, peer, kind, score);
911 #endif
912 }
913
914
915
916 /**
917  * Initialize address subsystem.
918  *
919  * @param cfg configuration to use
920  * @param stats the statistics handle to use
921  */
922 void
923 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
924                     const struct GNUNET_STATISTICS_Handle *stats)
925 {
926   int mode;
927
928   char *quota_wan_in_str;
929   char *quota_wan_out_str;
930
931   running = GNUNET_NO;
932
933   addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
934   GNUNET_assert (NULL != addresses);
935
936   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", "WAN_QUOTA_IN", &quota_wan_in_str))
937   {
938     if (0 == strcmp(quota_wan_in_str, "unlimited") ||
939         (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_wan_in_str, &wan_quota_in)))
940       wan_quota_in = (UINT32_MAX) /10;
941
942     GNUNET_free (quota_wan_in_str);
943     quota_wan_in_str = NULL;
944   }
945   else
946   {
947     wan_quota_in = (UINT32_MAX) /10;
948   }
949
950   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", "WAN_QUOTA_OUT", &quota_wan_out_str))
951   {
952     if (0 == strcmp(quota_wan_out_str, "unlimited") ||
953         (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_wan_out_str, &wan_quota_out)))
954       wan_quota_out = (UINT32_MAX) /10;
955
956     GNUNET_free (quota_wan_out_str);
957     quota_wan_out_str = NULL;
958   }
959   else
960   {
961     wan_quota_out = (UINT32_MAX) /10;
962   }
963
964   mode = GNUNET_CONFIGURATION_get_value_yesno (cfg, "ats", "MLP");
965   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MLP mode %u", mode);
966   switch (mode)
967   {
968     /* MLP = YES */
969     case GNUNET_YES:
970 #if HAVE_LIBGLPK
971       ats_mode = MLP;
972       /* Init the MLP solver with default values */
973       mlp = GAS_mlp_init (cfg, stats, MLP_MAX_EXEC_DURATION, MLP_MAX_ITERATIONS);
974       if (NULL == mlp)
975       {
976         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP mode was configured, but libglpk is not installed, switching to simple mode\n");
977         GNUNET_STATISTICS_update (GSA_stats, "MLP mode enabled", 0, GNUNET_NO);
978         break;
979       }
980       else
981       {
982         GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 1, GNUNET_NO);
983         break;
984       }
985 #else
986       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP mode was configured, but libglpk is not installed, switching to simple mode");
987       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
988       ats_mode = SIMPLE;
989       break;
990 #endif
991     /* MLP = NO */
992     case GNUNET_NO:
993       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
994       ats_mode = SIMPLE;
995       break;
996     /* No configuration value */
997     case GNUNET_SYSERR:
998       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
999       ats_mode = SIMPLE;
1000       break;
1001     default:
1002       break;
1003   }
1004   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started with %s mode\n", (SIMPLE == ats_mode) ? "SIMPLE" : "MLP");
1005   running = GNUNET_YES;
1006 }
1007
1008
1009 /**
1010  * Free memory of address.
1011  *
1012  * @param cls NULL
1013  * @param key peer identity (unused)
1014  * @param value the 'struct ATS_Address' to free
1015  * @return GNUNET_OK (continue to iterate)
1016  */
1017 static int
1018 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1019 {
1020   struct ATS_Address *aa = value;
1021
1022   destroy_address (aa);
1023   return GNUNET_OK;
1024 }
1025
1026
1027 void
1028 GAS_addresses_destroy_all ()
1029 {
1030   if (GNUNET_NO == running)
1031     return;
1032
1033   if (addresses != NULL)
1034     GNUNET_CONTAINER_multihashmap_iterate (addresses, &free_address_it, NULL);
1035   GNUNET_assert (active_addr_count == 0);
1036 }
1037
1038
1039 /**
1040  * Shutdown address subsystem.
1041  */
1042 void
1043 GAS_addresses_done ()
1044 {
1045   GAS_addresses_destroy_all ();
1046   running = GNUNET_NO;
1047   GNUNET_CONTAINER_multihashmap_destroy (addresses);
1048   addresses = NULL;
1049 #if HAVE_LIBGLPK
1050   if (ats_mode == MLP)
1051   {
1052     GAS_mlp_done (mlp);
1053   }
1054 #endif
1055 }
1056
1057 struct PeerIteratorContext
1058 {
1059   GNUNET_ATS_Peer_Iterator it;
1060   void *it_cls;
1061   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1062 };
1063
1064 static int
1065 peer_it (void *cls,
1066          const struct GNUNET_HashCode * key,
1067          void *value)
1068 {
1069   struct PeerIteratorContext *ip_ctx = cls;
1070   struct GNUNET_PeerIdentity tmp;
1071
1072   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1073   {
1074       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1075       tmp.hashPubKey = (*key);
1076       ip_ctx->it (ip_ctx->it_cls, &tmp);
1077   }
1078
1079   return GNUNET_OK;
1080 }
1081
1082 /**
1083  * Return all peers currently known to ATS
1084  *
1085  * @param p_it the iterator to call for every peer
1086  * @param p_it_cls the closure for the iterator
1087  */
1088 void
1089 GAS_addresses_iterate_peers (GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1090 {
1091   struct PeerIteratorContext ip_ctx;
1092   unsigned int size;
1093
1094   if (NULL == p_it)
1095       return;
1096   GNUNET_assert (NULL != addresses);
1097
1098   size = GNUNET_CONTAINER_multihashmap_size(addresses);
1099   if (0 != size)
1100   {
1101     ip_ctx.it = p_it;
1102     ip_ctx.it_cls = p_it_cls;
1103     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1104     GNUNET_CONTAINER_multihashmap_iterate (addresses, &peer_it, &ip_ctx);
1105     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1106   }
1107   p_it (p_it_cls, NULL);
1108 }
1109
1110 struct PeerInfoIteratorContext
1111 {
1112   GNUNET_ATS_PeerInfo_Iterator it;
1113   void *it_cls;
1114 };
1115
1116
1117 static int 
1118 peerinfo_it (void *cls,
1119              const struct GNUNET_HashCode * key,
1120              void *value)
1121 {
1122   struct PeerInfoIteratorContext *pi_ctx = cls;
1123   struct ATS_Address *addr = (struct ATS_Address *)  value;
1124
1125   if ((NULL != pi_ctx->it) && (GNUNET_YES == addr->used))
1126     pi_ctx->it (pi_ctx->it_cls,
1127                 &addr->peer,
1128                 addr->plugin,
1129                 addr->addr, addr->addr_len,
1130                 addr->ats, addr->ats_count,
1131                 addr->assigned_bw_out,
1132                 addr->assigned_bw_in);
1133   return GNUNET_YES;
1134 }
1135
1136
1137 /**
1138  * Return all peers currently known to ATS
1139  *
1140  * @param peer the respective peer
1141  * @param pi_it the iterator to call for every peer
1142  * @param pi_it_cls the closure for the iterator
1143  */
1144 void
1145 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, GNUNET_ATS_PeerInfo_Iterator pi_it, void *pi_it_cls)
1146 {
1147   struct PeerInfoIteratorContext pi_ctx;
1148   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1149   GNUNET_assert (NULL != peer);
1150   GNUNET_assert (NULL != addresses);
1151
1152   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1153   pi_ctx.it = pi_it;
1154   pi_ctx.it_cls = pi_it_cls;
1155
1156   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1157
1158   if (NULL != pi_it)
1159     pi_it (pi_it_cls, NULL, NULL, NULL, 0, NULL, 0, zero_bw, zero_bw);
1160
1161 }
1162
1163
1164 /* end of gnunet-service-ats_addresses.c */