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