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