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