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