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