-misc bugfixes, travel hacking
[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_ERROR, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
623                 GNUNET_i2s (peer), plugin_name, session_id);
624     GNUNET_break (0);
625     return;
626   }
627
628
629   GNUNET_break (0 < strlen (plugin_name));
630   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
631
632   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
633                                               &destroy_by_session_id, aa);
634
635   free_address (aa);
636 }
637
638
639 /**
640  * Find a "good" address to use for a peer.  If we already have an existing
641  * address, we stick to it.  Otherwise, we pick by lowest distance and then
642  * by lowest latency.
643  *
644  * @param cls the 'struct ATS_Address**' where we store the result
645  * @param key unused
646  * @param value another 'struct ATS_Address*' to consider using
647  * @return GNUNET_OK (continue to iterate)
648  */
649 static int
650 find_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
651 {
652   struct ATS_Address **ap = cls;
653   struct ATS_Address *aa = (struct ATS_Address *) value;
654   struct ATS_Address *ab = *ap;
655   struct GNUNET_TIME_Absolute now;
656
657   now = GNUNET_TIME_absolute_get();
658
659   if (aa->blocked_until.abs_value == GNUNET_TIME_absolute_max (now, aa->blocked_until).abs_value)
660   {
661     /* This address is blocked for suggestion */
662     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
663                 "Address %p blocked for suggestion for %llu ms \n",
664                 aa,
665                 GNUNET_TIME_absolute_get_difference(now, aa->blocked_until).rel_value);
666     return GNUNET_OK;
667   }
668
669   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
670   aa->blocked_until = GNUNET_TIME_absolute_add (now, aa->block_interval);
671
672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
673               "Address %p ready for suggestion, block interval now %llu \n", aa, aa->block_interval);
674
675   /* FIXME this is a hack */
676
677
678   if (NULL != ab)
679   {
680     if ((0 == strcmp (ab->plugin, "tcp")) &&
681         (0 == strcmp (aa->plugin, "tcp")))
682     {
683       if ((0 != ab->addr_len) &&
684           (0 == aa->addr_len))
685       {
686         /* saved address was an outbound address, but we have an inbound address */
687         *ap = aa;
688         return GNUNET_OK;
689       }
690       if (0 == ab->addr_len)
691       {
692         /* saved address was an inbound address, so do not overwrite */
693         return GNUNET_OK;
694       }
695     }
696   }
697   /* FIXME end of hack */
698
699   if (NULL == ab)
700   {
701     *ap = aa;
702     return GNUNET_OK;
703   }
704   if ((ntohl (ab->assigned_bw_in.value__) == 0) &&
705       (ntohl (aa->assigned_bw_in.value__) > 0))
706   {
707     /* stick to existing connection */
708     *ap = aa;
709     return GNUNET_OK;
710   }
711   if (ab->atsp_distance > aa->atsp_distance)
712   {
713     /* user shorter distance */
714     *ap = aa;
715     return GNUNET_OK;
716   }
717   if (ab->atsp_latency.rel_value > aa->atsp_latency.rel_value)
718   {
719     /* user lower latency */
720     *ap = aa;
721     return GNUNET_OK;
722   }
723   /* don't care */
724   return GNUNET_OK;
725 }
726
727
728 int
729 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
730                       const char *plugin_name, const void *plugin_addr,
731                       size_t plugin_addr_len, uint32_t session_id, int in_use)
732 {
733 #if DEBUG_ATS
734   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
735               "Received `%s' message for peer `%s': %i\n", "ADDRESS_IN_USE",
736               GNUNET_i2s (peer), in_use);
737 #endif
738
739   struct ATS_Address *old;
740
741   if (GNUNET_NO == running)
742     return GNUNET_SYSERR;
743
744   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id, NULL, 0);
745   if (NULL == old)
746   {
747     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
748                 "Trying to set unknown address `%s', %s %u %s \n",
749                 GNUNET_i2s (peer),
750                 plugin_name, session_id,
751                 (GNUNET_NO == in_use) ? "NO" : "YES");
752     GNUNET_break (0);
753     return GNUNET_SYSERR;
754   }
755   if (old->used == in_use)
756   {
757     GNUNET_break (0);
758     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
759                 "Address in use called multiple times for peer `%s': %s -> %s \n",
760                 GNUNET_i2s (peer),
761                 (GNUNET_NO == old->used) ? "NO" : "YES",
762                 (GNUNET_NO == in_use) ? "NO" : "YES");
763     return GNUNET_SYSERR;
764   }
765   old->used = in_use;
766 #if HAVE_LIBGLPK
767   if (ats_mode == MLP)
768      GAS_mlp_address_update (mlp, addresses, old);
769 #endif
770   return GNUNET_OK;
771 }
772
773
774 static void 
775 request_address_mlp (const struct GNUNET_PeerIdentity *peer)
776 {
777   struct ATS_Address *aa;
778   aa = NULL;
779
780 #if HAVE_GLPK
781   /* Get preferred address from MLP */
782   struct ATS_PreferedAddress * paddr = NULL;
783   paddr = GAS_mlp_get_preferred_address (mlp, addresses, peer);
784   aa = paddr->address;
785   aa->assigned_bw_out = GNUNET_BANDWIDTH_value_init(paddr->bandwidth_out);
786   /* FIXME use bw in value */
787   paddr->bandwidth_in = paddr->bandwidth_out;
788   aa->assigned_bw_in = GNUNET_BANDWIDTH_value_init (paddr->bandwidth_in);
789   GNUNET_free (paddr);
790 #endif
791
792   if (aa == NULL)
793   {
794     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
795                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
796     return;
797   }
798   if (aa->active == GNUNET_NO)
799   {
800     aa->active = GNUNET_YES;
801     active_addr_count++;
802
803     send_bw_notification (aa);
804   }
805   else
806   {
807     /* just to be sure... */
808     GAS_scheduling_transmit_address_suggestion (peer, aa->plugin, aa->addr,
809                                                 aa->addr_len, aa->session_id,
810                                                 aa->ats, aa->ats_count,
811                                                 aa->assigned_bw_out,
812                                                 aa->assigned_bw_in);
813   }
814
815 }
816
817
818 static void 
819 request_address_simple (const struct GNUNET_PeerIdentity *peer)
820 {
821   struct ATS_Address *aa;
822   aa = NULL;
823
824   /* Get address with: stick to current address, lower distance, lower latency */
825   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey,
826                                               &find_address_it, &aa);
827   if (aa == NULL)
828   {
829     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
830                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
831     return;
832   }
833
834   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
835               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
836
837   if (aa->active == GNUNET_NO)
838   {
839     aa->active = GNUNET_YES;
840     active_addr_count++;
841     if (ats_mode == SIMPLE)
842     {
843       recalculate_assigned_bw ();
844     }
845   }
846   else
847   {
848     /* just to be sure... */
849     GAS_scheduling_transmit_address_suggestion (peer, aa->plugin, aa->addr,
850                                                 aa->addr_len, aa->session_id,
851                                                 aa->ats, aa->ats_count,
852                                                 aa->assigned_bw_out,
853                                                 aa->assigned_bw_in);
854   }
855 }
856
857
858 void
859 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
860 {
861   if (GNUNET_NO == running)
862     return;
863
864   if (ats_mode == SIMPLE)
865   {
866     request_address_simple (peer);
867   }
868   if (ats_mode == MLP)
869   {
870     request_address_mlp(peer);
871   }
872 }
873
874
875 static int
876 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
877 {
878   struct ATS_Address *aa = value;
879
880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881               "Resetting interval for peer `%s' address %p from %llu to 0\n", GNUNET_i2s (&aa->peer), aa, aa->block_interval);
882
883   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
884   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
885   return GNUNET_OK;
886 }
887
888
889 void
890 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
891 {
892   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (addresses,
893                                               &peer->hashPubKey,
894                                               &reset_address_it,
895                                               NULL));
896 }
897
898
899
900 // FIXME: this function should likely end up in the LP-subsystem and
901 // not with 'addresses' in the future...
902 void
903 GAS_addresses_change_preference (const struct GNUNET_PeerIdentity *peer,
904                                  enum GNUNET_ATS_PreferenceKind kind,
905                                  float score)
906 {
907   if (GNUNET_NO == running)
908     return;
909 #if HAVE_LIBGLPK
910   if (ats_mode == MLP)
911     GAS_mlp_address_change_preference (mlp, peer, kind, score);
912 #endif
913 }
914
915
916
917 /**
918  * Initialize address subsystem.
919  *
920  * @param cfg configuration to use
921  * @param stats the statistics handle to use
922  */
923 void
924 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
925                     const struct GNUNET_STATISTICS_Handle *stats)
926 {
927   int mode;
928
929   char *quota_wan_in_str;
930   char *quota_wan_out_str;
931
932   running = GNUNET_NO;
933
934   addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
935   GNUNET_assert (NULL != addresses);
936
937   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", "WAN_QUOTA_IN", &quota_wan_in_str))
938   {
939     if (0 == strcmp(quota_wan_in_str, "unlimited") ||
940         (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_wan_in_str, &wan_quota_in)))
941       wan_quota_in = (UINT32_MAX) /10;
942
943     GNUNET_free (quota_wan_in_str);
944     quota_wan_in_str = NULL;
945   }
946   else
947   {
948     wan_quota_in = (UINT32_MAX) /10;
949   }
950
951   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", "WAN_QUOTA_OUT", &quota_wan_out_str))
952   {
953     if (0 == strcmp(quota_wan_out_str, "unlimited") ||
954         (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_wan_out_str, &wan_quota_out)))
955       wan_quota_out = (UINT32_MAX) /10;
956
957     GNUNET_free (quota_wan_out_str);
958     quota_wan_out_str = NULL;
959   }
960   else
961   {
962     wan_quota_out = (UINT32_MAX) /10;
963   }
964
965   mode = GNUNET_CONFIGURATION_get_value_yesno (cfg, "ats", "MLP");
966   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "MLP mode %u", mode);
967   switch (mode)
968   {
969     /* MLP = YES */
970     case GNUNET_YES:
971 #if HAVE_LIBGLPK
972       ats_mode = MLP;
973       /* Init the MLP solver with default values */
974       mlp = GAS_mlp_init (cfg, stats, MLP_MAX_EXEC_DURATION, MLP_MAX_ITERATIONS);
975       if (NULL == mlp)
976       {
977         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP mode was configured, but libglpk is not installed, switching to simple mode\n");
978         GNUNET_STATISTICS_update (GSA_stats, "MLP mode enabled", 0, GNUNET_NO);
979         break;
980       }
981       else
982       {
983         GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 1, GNUNET_NO);
984         break;
985       }
986 #else
987       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "MLP mode was configured, but libglpk is not installed, switching to simple mode");
988       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
989       ats_mode = SIMPLE;
990       break;
991 #endif
992     /* MLP = NO */
993     case GNUNET_NO:
994       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
995       ats_mode = SIMPLE;
996       break;
997     /* No configuration value */
998     case GNUNET_SYSERR:
999       GNUNET_STATISTICS_update (GSA_stats, "MLP enabled", 0, GNUNET_NO);
1000       ats_mode = SIMPLE;
1001       break;
1002     default:
1003       break;
1004   }
1005   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started with %s mode\n", (SIMPLE == ats_mode) ? "SIMPLE" : "MLP");
1006   running = GNUNET_YES;
1007 }
1008
1009
1010 /**
1011  * Free memory of address.
1012  *
1013  * @param cls NULL
1014  * @param key peer identity (unused)
1015  * @param value the 'struct ATS_Address' to free
1016  * @return GNUNET_OK (continue to iterate)
1017  */
1018 static int
1019 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1020 {
1021   struct ATS_Address *aa = value;
1022
1023   destroy_address (aa);
1024   return GNUNET_OK;
1025 }
1026
1027
1028 void
1029 GAS_addresses_destroy_all ()
1030 {
1031   if (GNUNET_NO == running)
1032     return;
1033
1034   if (addresses != NULL)
1035     GNUNET_CONTAINER_multihashmap_iterate (addresses, &free_address_it, NULL);
1036   GNUNET_assert (active_addr_count == 0);
1037 }
1038
1039
1040 /**
1041  * Shutdown address subsystem.
1042  */
1043 void
1044 GAS_addresses_done ()
1045 {
1046   GAS_addresses_destroy_all ();
1047   running = GNUNET_NO;
1048   GNUNET_CONTAINER_multihashmap_destroy (addresses);
1049   addresses = NULL;
1050 #if HAVE_LIBGLPK
1051   if (ats_mode == MLP)
1052   {
1053     GAS_mlp_done (mlp);
1054   }
1055 #endif
1056 }
1057
1058 struct PeerIteratorContext
1059 {
1060   GNUNET_ATS_Peer_Iterator it;
1061   void *it_cls;
1062   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1063 };
1064
1065 static int
1066 peer_it (void *cls,
1067          const struct GNUNET_HashCode * key,
1068          void *value)
1069 {
1070   struct PeerIteratorContext *ip_ctx = cls;
1071   struct GNUNET_PeerIdentity tmp;
1072
1073   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1074   {
1075       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1076       tmp.hashPubKey = (*key);
1077       ip_ctx->it (ip_ctx->it_cls, &tmp);
1078   }
1079
1080   return GNUNET_OK;
1081 }
1082
1083 /**
1084  * Return all peers currently known to ATS
1085  *
1086  * @param p_it the iterator to call for every peer
1087  * @param p_it_cls the closure for the iterator
1088  */
1089 void
1090 GAS_addresses_iterate_peers (GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1091 {
1092   struct PeerIteratorContext ip_ctx;
1093   unsigned int size;
1094
1095   if (NULL == p_it)
1096       return;
1097   GNUNET_assert (NULL != addresses);
1098
1099   size = GNUNET_CONTAINER_multihashmap_size(addresses);
1100   if (0 != size)
1101   {
1102     ip_ctx.it = p_it;
1103     ip_ctx.it_cls = p_it_cls;
1104     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1105     GNUNET_CONTAINER_multihashmap_iterate (addresses, &peer_it, &ip_ctx);
1106     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1107   }
1108   p_it (p_it_cls, NULL);
1109 }
1110
1111 struct PeerInfoIteratorContext
1112 {
1113   GNUNET_ATS_PeerInfo_Iterator it;
1114   void *it_cls;
1115 };
1116
1117
1118 static int 
1119 peerinfo_it (void *cls,
1120              const struct GNUNET_HashCode * key,
1121              void *value)
1122 {
1123   struct PeerInfoIteratorContext *pi_ctx = cls;
1124   struct ATS_Address *addr = (struct ATS_Address *)  value;
1125
1126   if ((NULL != pi_ctx->it) && (GNUNET_YES == addr->used))
1127     pi_ctx->it (pi_ctx->it_cls,
1128                 &addr->peer,
1129                 addr->plugin,
1130                 addr->addr, addr->addr_len,
1131                 addr->ats, addr->ats_count,
1132                 addr->assigned_bw_out,
1133                 addr->assigned_bw_in);
1134   return GNUNET_YES;
1135 }
1136
1137
1138 /**
1139  * Return all peers currently known to ATS
1140  *
1141  * @param peer the respective peer
1142  * @param pi_it the iterator to call for every peer
1143  * @param pi_it_cls the closure for the iterator
1144  */
1145 void
1146 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, GNUNET_ATS_PeerInfo_Iterator pi_it, void *pi_it_cls)
1147 {
1148   struct PeerInfoIteratorContext pi_ctx;
1149   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1150   GNUNET_assert (NULL != peer);
1151   GNUNET_assert (NULL != addresses);
1152
1153   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1154   pi_ctx.it = pi_it;
1155   pi_ctx.it_cls = pi_it_cls;
1156
1157   GNUNET_CONTAINER_multihashmap_get_multiple (addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1158
1159   if (NULL != pi_it)
1160     pi_it (pi_it_cls, NULL, NULL, NULL, 0, NULL, 0, zero_bw, zero_bw);
1161
1162 }
1163
1164
1165 /* end of gnunet-service-ats_addresses.c */