tests
[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
40 /**
41  * Available ressource assignment modes
42  */
43 enum ATS_Mode
44 {
45   /*
46    * Simplistic mode:
47    *
48    * Assign each peer an equal amount of bandwidth (bw)
49    *
50    * bw_per_peer = bw_total / #active addresses
51    */
52   MODE_SIMPLISTIC,
53
54   /*
55    * MLP mode:
56    *
57    * Solve ressource assignment as an optimization problem
58    * Uses an mixed integer programming solver
59    */
60   MODE_MLP
61 };
62
63 /**
64  * Handle for ATS address component
65  */
66 struct GAS_Addresses_Suggestion_Requests
67 {
68   struct GAS_Addresses_Suggestion_Requests *next;
69   struct GAS_Addresses_Suggestion_Requests *prev;
70
71   struct GNUNET_PeerIdentity id;
72 };
73
74 /**
75  * Handle for ATS address component
76  */
77 struct GAS_Addresses_Handle
78 {
79   /**
80    * A multihashmap to store all addresses
81    */
82   struct GNUNET_CONTAINER_MultiHashMap *addresses;
83
84   /**
85    * Configure WAN quota in
86    */
87   unsigned long long wan_quota_in;
88
89   /**
90    * Configure WAN quota out
91    */
92   unsigned long long wan_quota_out;
93
94   /**
95    * Is ATS addresses running
96    */
97   int running;
98
99   /**
100    * Configured ATS solver
101    */
102   int ats_mode;
103
104   /**
105    *  Solver handle
106    */
107   void *solver;
108
109   /**
110    * Address suggestion requests DLL head
111    */
112   struct GAS_Addresses_Suggestion_Requests *r_head;
113
114   /**
115    * Address suggestion requests DLL tail
116    */
117   struct GAS_Addresses_Suggestion_Requests *r_tail;
118
119   /* Solver functions */
120
121   /**
122    * Initialize solver
123    */
124   GAS_solver_init s_init;
125
126   /**
127    * Update address in solver
128    */
129   GAS_solver_address_update s_update;
130
131   /**
132    * Get address from solver
133    */
134   GAS_solver_get_preferred_address s_get;
135
136   /**
137    * Delete address in solver
138    */
139   GAS_solver_address_delete s_del;
140
141   /**
142    * Change preference for quality in solver
143    */
144   GAS_solver_address_change_preference s_pref;
145
146   /**
147    * Shutdown solver
148    */
149   GAS_solver_done s_done;
150 };
151
152
153 /**
154  * Temporary handle
155  */
156 struct GAS_Addresses_Handle *handle;
157
158
159 static unsigned int
160 assemble_ats_information (const struct ATS_Address *aa,  struct GNUNET_ATS_Information **dest)
161 {
162   unsigned int ats_count = GNUNET_ATS_PropertyCount - 1;
163   struct GNUNET_ATS_Information *ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
164   (*dest) = ats;
165
166   ats[0].type = ntohl(GNUNET_ATS_UTILIZATION_UP);
167   ats[0].value = aa->atsp_utilization_out.value__;
168   ats[1].type = ntohl(GNUNET_ATS_UTILIZATION_DOWN);
169   ats[1].value = aa->atsp_utilization_in.value__;
170   ats[2].type = ntohl(GNUNET_ATS_NETWORK_TYPE);
171   ats[2].value = ntohl(aa->atsp_network_type);
172   ats[3].type = ntohl(GNUNET_ATS_QUALITY_NET_DELAY);
173   ats[3].value = ntohl(aa->atsp_latency.rel_value);
174   ats[4].type = ntohl(GNUNET_ATS_QUALITY_NET_DISTANCE);
175   ats[4].value = ntohl(aa->atsp_distance);
176   ats[5].type = ntohl(GNUNET_ATS_COST_WAN);
177   ats[5].value = ntohl (aa->atsp_cost_wan);
178   ats[6].type = ntohl(GNUNET_ATS_COST_LAN);
179   ats[6].value = ntohl (aa->atsp_cost_lan);
180   ats[7].type = ntohl(GNUNET_ATS_COST_WLAN);
181   ats[7].value = ntohl (aa->atsp_cost_wlan);
182   return ats_count;
183 }
184
185 static unsigned int
186 disassemble_ats_information (const struct GNUNET_ATS_Information *src,
187                              uint32_t ats_count,
188                              struct ATS_Address *dest)
189 {
190   int i;
191   int res = 0;
192   for (i = 0; i < ats_count; i++)
193     switch (ntohl (src[i].type))
194     {
195     case GNUNET_ATS_UTILIZATION_UP:
196       dest->atsp_utilization_out.value__ = src[i].value;
197       res ++;
198       break;
199     case GNUNET_ATS_UTILIZATION_DOWN:
200       dest->atsp_utilization_in.value__ = src[i].value;
201       res ++;
202       break;
203     case GNUNET_ATS_QUALITY_NET_DELAY:
204       dest->atsp_latency.rel_value = ntohl (src[i].value);
205       res ++;
206       break;
207     case GNUNET_ATS_QUALITY_NET_DISTANCE:
208       dest->atsp_distance = ntohl (src[i].value);
209       res ++;
210       break;
211     case GNUNET_ATS_COST_WAN:
212       dest->atsp_cost_wan = ntohl (src[i].value);
213       res ++;
214       break;
215     case GNUNET_ATS_COST_LAN:
216       dest->atsp_cost_lan = ntohl (src[i].value);
217       res ++;
218       break;
219     case GNUNET_ATS_COST_WLAN:
220       dest->atsp_cost_wlan = ntohl (src[i].value);
221       res ++;
222       break;
223     case GNUNET_ATS_NETWORK_TYPE:
224       dest->atsp_network_type = ntohl (src[i].value);
225       res ++;
226       break;
227     case GNUNET_ATS_ARRAY_TERMINATOR:
228       break;
229     default:
230       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
231                   "Received unsupported ATS type %u\n", ntohl (src[i].type));
232       GNUNET_break (0);
233       break;
234     }
235   return res;
236 }
237
238 /**
239  * Free the given address
240  * @param addr address to destroy
241  */
242 static void
243 free_address (struct ATS_Address *addr)
244 {
245   GNUNET_free (addr->plugin);
246   GNUNET_free (addr);
247 }
248
249 /**
250  * Create a ATS_address with the given information
251  * @param peer peer
252  * @param plugin_name plugin
253  * @param plugin_addr address
254  * @param plugin_addr_len address length
255  * @param session_id session
256  * @return the ATS_Address
257  */
258 static struct ATS_Address *
259 create_address (const struct GNUNET_PeerIdentity *peer,
260                 const char *plugin_name,
261                 const void *plugin_addr, size_t plugin_addr_len,
262                 uint32_t session_id)
263 {
264   struct ATS_Address *aa = NULL;
265
266   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
267   aa->peer = *peer;
268   aa->addr_len = plugin_addr_len;
269   aa->addr = &aa[1];
270   memcpy (&aa[1], plugin_addr, plugin_addr_len);
271   aa->plugin = GNUNET_strdup (plugin_name);
272   aa->session_id = session_id;
273   return aa;
274 }
275
276
277 /**
278  * Destroy the given address.
279  *
280  * @param addr address to destroy
281  * @return GNUNET_YES if bandwidth allocations should be recalcualted
282  */
283 static int
284 destroy_address (struct ATS_Address *addr)
285 {
286   int ret;
287
288   ret = GNUNET_NO;
289   GNUNET_assert (GNUNET_YES ==
290                  GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
291                                                        &addr->peer.hashPubKey,
292                                                        addr));
293
294   handle->s_del (handle->solver, handle->addresses, addr);
295   free_address (addr);
296   return ret;
297 }
298
299
300 struct CompareAddressContext
301 {
302   const struct ATS_Address *search;
303
304   /* exact_address != NULL if address and session is equal */
305   struct ATS_Address *exact_address;
306   /* exact_address != NULL if address and session is 0 */
307   struct ATS_Address *base_address;
308 };
309
310
311 static int
312 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
313 {
314   struct CompareAddressContext *cac = cls;
315   struct ATS_Address *aa = value;
316
317   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Comparing peer %4s: address length %u session %u <-> address length %u session %u\n",
318       GNUNET_h2s (key),
319       aa->addr_len, aa->session_id,
320       cac->search->addr_len, cac->search->session_id);
321
322   /* Find an matching exact address:
323    *
324    * Compare by:
325    * aa->addr_len == cac->search->addr_len
326    * aa->plugin == cac->search->plugin
327    * aa->addr == cac->search->addr
328    * aa->session == cac->search->session
329    *
330    * return as exact address
331    */
332   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
333   {
334       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
335         cac->exact_address = aa;
336   }
337
338   /* Find an matching base address:
339    *
340    * Properties:
341    *
342    * aa->session_id == 0
343    *
344    * Compare by:
345    * aa->addr_len == cac->search->addr_len
346    * aa->plugin == cac->search->plugin
347    * aa->addr == cac->search->addr
348    *
349    * return as base address
350    */
351   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
352   {
353       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == 0))
354         cac->base_address = aa;
355   }
356
357   /* Find an matching exact address based on session:
358    *
359    * Properties:
360    *
361    * cac->search->addr_len == 0
362    *
363    * Compare by:
364    * aa->plugin == cac->search->plugin
365    * aa->session_id == cac->search->session_id
366    *
367    * return as exact address
368    */
369   if (0 == cac->search->addr_len)
370   {
371       if ((0 == strcmp (aa->plugin, cac->search->plugin)) && (aa->session_id == cac->search->session_id))
372         cac->exact_address = aa;
373   }
374
375   if (cac->exact_address == NULL)
376     return GNUNET_YES; /* Continue iteration to find exact address */
377   else
378     return GNUNET_NO; /* Stop iteration since we have an exact address */
379 }
380
381
382 /**
383  * Find an existing equivalent address record.
384  * Compares by peer identity and network address OR by session ID
385  * (one of the two must match).
386  *
387  * @param peer peer to lookup addresses for
388  * @param addr existing address record
389  * @return existing address record, NULL for none
390  */
391 struct ATS_Address *
392 find_address (const struct GNUNET_PeerIdentity *peer,
393               const struct ATS_Address *addr)
394 {
395   struct CompareAddressContext cac;
396
397   cac.exact_address = NULL;
398   cac.base_address = NULL;
399   cac.search = addr;
400   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
401                                               &compare_address_it, &cac);
402
403 #if 0
404   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
405               "Found exact address: %s           base address: %s\n",
406               (cac.exact_address != NULL) ? "YES" : "NO",
407               (cac.base_address != NULL) ? "YES" : "NO");
408 #endif
409   if (cac.exact_address == NULL)
410     return cac.base_address;
411   return cac.exact_address;
412 }
413
414
415 static struct ATS_Address *
416 lookup_address (const struct GNUNET_PeerIdentity *peer,
417                 const char *plugin_name, const void *plugin_addr,
418                 size_t plugin_addr_len, uint32_t session_id,
419                 const struct GNUNET_ATS_Information *atsi,
420                 uint32_t atsi_count)
421 {
422   struct ATS_Address *aa;
423   struct ATS_Address *old;
424
425   aa = create_address (peer,
426                        plugin_name,
427                        plugin_addr, plugin_addr_len,
428                        session_id);
429
430   aa->mlp_information = NULL;
431
432   /* Get existing address or address with session == 0 */
433   old = find_address (peer, aa);
434   free_address (aa);
435   if (old == NULL)
436   {
437     return NULL;
438   }
439   else if (old->session_id != session_id)
440   {
441     return NULL;
442   }
443   return old;
444 }
445
446
447 #if 0
448 static int
449 compare_address_session_it (void *cls, const struct GNUNET_HashCode * key, void *value)
450 {
451   struct CompareAddressContext *cac = cls;
452   struct ATS_Address *aa = value;
453
454   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
455   {
456       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
457       {
458        cac->exact_address = aa;
459         return GNUNET_NO;
460       }
461   }
462   return GNUNET_YES;
463 }
464
465
466 /**
467  * Find an existing equivalent address record.
468  * Compares by peer identity and network address AND by session ID
469  * (one of the two must match).
470  *
471  * @param peer peer to lookup addresses for
472  * @param addr existing address record
473  * @return existing address record, NULL for none
474  */
475 static struct ATS_Address *
476 find_exact_address (const struct GNUNET_PeerIdentity *peer,
477               const struct ATS_Address *addr)
478 {
479   struct CompareAddressContext cac;
480
481   cac.exact_address = NULL;
482   cac.search = addr;
483   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
484                                               &compare_address_session_it, &cac);
485   return cac.exact_address;
486 }
487 #endif
488
489 void
490 GAS_addresses_add (const struct GNUNET_PeerIdentity *peer,
491                       const char *plugin_name, const void *plugin_addr,
492                       size_t plugin_addr_len, uint32_t session_id,
493                       const struct GNUNET_ATS_Information *atsi,
494                       uint32_t atsi_count)
495 {
496   struct ATS_Address *aa;
497   struct ATS_Address *old;
498   unsigned int ats_res;
499
500   if (GNUNET_NO == handle->running)
501     return;
502
503   GNUNET_assert (NULL != handle->addresses);
504
505   aa = create_address (peer,
506                        plugin_name,
507                        plugin_addr, plugin_addr_len,
508                        session_id);
509   aa->mlp_information = NULL;
510   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, aa)))
511   {
512       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
513                 "While adding address: had %u ATS elements to add, could only add %u\n",
514                 atsi_count, ats_res);
515   }
516
517   /* Get existing address or address with session == 0 */
518   old = find_address (peer, aa);
519   if (old == NULL)
520   {
521     /* We have a new address */
522     GNUNET_assert (GNUNET_OK ==
523                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
524                                                       &peer->hashPubKey, aa,
525                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
526     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
527                 GNUNET_i2s (peer), session_id, aa);
528     /* Tell solver about update */
529     handle->s_update (handle->solver, handle->addresses, aa);
530     return;
531   }
532
533   if (old->session_id != 0)
534   {
535       /* This address and session is already existing */
536       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
537                 "Added already existing address for peer `%s' `%s' %p with new session %u\n",
538                 GNUNET_i2s (peer), plugin_name, session_id);
539       GNUNET_break (0);
540       return;
541   }
542
543   /* We have an address without an session, update this address */
544   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
545             "Updated existing address for peer `%s' %p with new session %u\n",
546             GNUNET_i2s (peer), old, session_id);
547   old->session_id = session_id;
548   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, old)))
549   {
550       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551                 "While updating address: had %u ATS elements to add, could only add %u\n",
552                 atsi_count, ats_res);
553   }
554   GNUNET_free (aa->plugin);
555   GNUNET_free (aa);
556   handle->s_update (handle->solver, handle->addresses, old);
557 }
558
559
560 void
561 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
562                       const char *plugin_name, const void *plugin_addr,
563                       size_t plugin_addr_len, uint32_t session_id,
564                       const struct GNUNET_ATS_Information *atsi,
565                       uint32_t atsi_count)
566 {
567   struct ATS_Address *old;
568   uint32_t i;
569
570   if (GNUNET_NO == handle->running)
571     return;
572
573   GNUNET_assert (NULL != handle->addresses);
574
575   /* Get existing address */
576   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
577                        session_id, atsi, atsi_count);
578   if (old == NULL)
579   {
580     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
581                 GNUNET_i2s (peer), plugin_name, session_id);
582     GNUNET_break (0);
583     return;
584   }
585
586   for (i = 0; i < atsi_count; i++)
587     switch (ntohl (atsi[i].type))
588     {
589     case GNUNET_ATS_UTILIZATION_UP:
590       old->atsp_utilization_out.value__ = atsi[i].value;
591       break;
592     case GNUNET_ATS_UTILIZATION_DOWN:
593       old->atsp_utilization_in.value__ = atsi[i].value;
594       break;
595     case GNUNET_ATS_QUALITY_NET_DELAY:
596       old->atsp_latency.rel_value = ntohl (atsi[i].value);
597       break;
598     case GNUNET_ATS_QUALITY_NET_DISTANCE:
599       old->atsp_distance = ntohl (atsi[i].value);
600       break;
601     case GNUNET_ATS_COST_WAN:
602       old->atsp_cost_wan = ntohl (atsi[i].value);
603       break;
604     case GNUNET_ATS_COST_LAN:
605       old->atsp_cost_lan = ntohl (atsi[i].value);
606       break;
607     case GNUNET_ATS_COST_WLAN:
608       old->atsp_cost_wlan = ntohl (atsi[i].value);
609       break;
610     case GNUNET_ATS_NETWORK_TYPE:
611       old->atsp_network_type = ntohl (atsi[i].value);
612       break;
613
614     default:
615       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
616                   "Received unsupported ATS type %u\n", ntohl (atsi[i].type));
617       GNUNET_break (0);
618       break;
619     }
620   /* Tell solver about update */
621   handle->s_update (handle->solver, handle->addresses, old);
622 }
623
624
625 /**
626  * Delete an address
627  *
628  * If session != 0, just the session is deleted, the address itself still exists
629  * If session == 0, remove full address
630  * If session == 0 and addrlen == 0, destroy inbound address
631  *
632  * @param cls unused
633  * @param key unused
634  * @param value the 'struct ATS_Address'
635  * @return GNUNET_OK (continue to iterate)
636  */
637 static int
638 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
639 {
640   const struct ATS_Address *info = cls;
641   struct ATS_Address *aa = value;
642
643   GNUNET_assert (0 ==
644                  memcmp (&aa->peer, &info->peer,
645                          sizeof (struct GNUNET_PeerIdentity)));
646   /* session == 0, remove full address  */
647   if ((info->session_id == 0) && (0 == strcmp (info->plugin, aa->plugin)) &&
648       (aa->addr_len == info->addr_len) &&
649       (0 == memcmp (info->addr, aa->addr, aa->addr_len)))
650   {
651
652     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
653                 "Deleting address for peer `%s': `%s' %u\n",
654                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
655
656     destroy_address (aa);
657       // FIXME if (GNUNET_YES == destroy_address (aa))recalculate_assigned_bw ();
658     return GNUNET_OK;
659   }
660   /* session != 0, just remove session */
661   if (aa->session_id != info->session_id)
662     return GNUNET_OK;           /* irrelevant */
663   if (aa->session_id != 0)
664     GNUNET_break (0 == strcmp (info->plugin, aa->plugin));
665   /* session died */
666   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
667               "Deleting session for peer `%s': `%s' %u\n",
668               GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
669   aa->session_id = 0;
670
671   if (GNUNET_YES == aa->active)
672   {
673     aa->active = GNUNET_NO;
674     //FIXME recalculate_assigned_bw ();
675   }
676
677   /* session == 0 and addrlen == 0 : destroy address */
678   if (aa->addr_len == 0)
679   {
680     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
681                 "Deleting session and address for peer `%s': `%s' %u\n",
682                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
683     (void) destroy_address (aa);
684   }
685   else
686   {
687     /* session was set to 0, update address */
688 #if HAVE_LIBGLPK
689   if (handle->ats_mode == MODE_MLP)
690     GAS_mlp_address_update (handle->solver, handle->addresses, aa);
691 #endif
692   }
693
694   return GNUNET_OK;
695 }
696
697
698 void
699 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
700                        const char *plugin_name, const void *plugin_addr,
701                        size_t plugin_addr_len, uint32_t session_id)
702 {
703   struct ATS_Address *aa;
704   struct ATS_Address *old;
705
706   if (GNUNET_NO == handle->running)
707     return;
708
709   /* Get existing address */
710   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
711                        session_id, NULL, 0);
712   if (old == NULL)
713   {
714     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
715                 GNUNET_i2s (peer), plugin_name, session_id);
716     return;
717   }
718
719   GNUNET_break (0 < strlen (plugin_name));
720   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
721   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
722                                               &destroy_by_session_id, aa);
723   free_address (aa);
724 }
725
726
727 int
728 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
729                       const char *plugin_name, const void *plugin_addr,
730                       size_t plugin_addr_len, uint32_t session_id, int in_use)
731 {
732 #if DEBUG_ATS
733   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
734               "Received `%s' message for peer `%s': %i\n", "ADDRESS_IN_USE",
735               GNUNET_i2s (peer), in_use);
736 #endif
737
738   struct ATS_Address *old;
739
740   if (GNUNET_NO == handle->running)
741     return GNUNET_SYSERR;
742
743   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id, NULL, 0);
744   if (NULL == old)
745   {
746     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
747                 "Trying to set unknown address `%s', %s %u %s \n",
748                 GNUNET_i2s (peer),
749                 plugin_name, session_id,
750                 (GNUNET_NO == in_use) ? "NO" : "YES");
751     GNUNET_break (0);
752     return GNUNET_SYSERR;
753   }
754   if (old->used == in_use)
755   {
756     GNUNET_break (0);
757     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
758                 "Address in use called multiple times for peer `%s': %s -> %s \n",
759                 GNUNET_i2s (peer),
760                 (GNUNET_NO == old->used) ? "NO" : "YES",
761                 (GNUNET_NO == in_use) ? "NO" : "YES");
762     return GNUNET_SYSERR;
763   }
764   old->used = in_use;
765
766   /* Tell solver about update */
767   handle->s_update (handle->solver, handle->addresses, old);
768
769   return GNUNET_OK;
770 }
771
772
773 /**
774  * Cancel address suggestions for a peer
775  *
776  * @param peer the respective peer
777  */
778 void
779 GAS_addresses_request_address_cancel (const struct GNUNET_PeerIdentity *peer)
780 {
781   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
782
783   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
785
786   while (NULL != cur)
787   {
788       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
789         break; /* found */
790       cur = cur->next;
791   }
792
793   if (NULL == cur)
794   {
795       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
796                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
797       return;
798   }
799   GAS_addresses_handle_backoff_reset (peer);
800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
802   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
803   GNUNET_free (cur);
804 }
805
806
807 /**
808  * Add an address suggestions for a peer
809  *
810  * @param peer the respective peer
811  */
812 void
813 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
814 {
815   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
816   const struct ATS_Address *aa;
817   struct GNUNET_ATS_Information *ats;
818   unsigned int ats_count;
819
820   if (GNUNET_NO == handle->running)
821     return;
822   while (NULL != cur)
823   {
824       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
825         break; /* already suggesting */
826       cur = cur->next;
827   }
828   if (NULL == cur)
829   {
830       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
831       cur->id = (*peer);
832       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
833   }
834
835   /* Get prefered address from solver */
836   aa = handle->s_get (handle->solver, handle->addresses, peer);
837   if (NULL == aa)
838     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
839                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
840   else
841   {
842     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
843                 "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
844
845     ats_count = assemble_ats_information (aa, &ats);
846     GAS_scheduling_transmit_address_suggestion (peer,
847                                                 aa->plugin,
848                                                 aa->addr, aa->addr_len,
849                                                 aa->session_id,
850                                                 ats, ats_count,
851                                                 aa->assigned_bw_out,
852                                                 aa->assigned_bw_in);
853     GNUNET_free (ats);
854   }
855 }
856
857
858 static int
859 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
860 {
861   struct ATS_Address *aa = value;
862
863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
864               "Resetting interval for peer `%s' address %p from %llu to 0\n",
865               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
866
867   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
868   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
869   return GNUNET_OK;
870 }
871
872
873 void
874 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
875 {
876   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
877                                               &peer->hashPubKey,
878                                               &reset_address_it,
879                                               NULL));
880 }
881
882
883 void
884 GAS_addresses_change_preference (const struct GNUNET_PeerIdentity *peer,
885                                  enum GNUNET_ATS_PreferenceKind kind,
886                                  float score)
887 {
888   if (GNUNET_NO == handle->running)
889     return;
890
891   /* Tell solver about update */
892   handle->s_pref (handle->solver, peer, kind, score);
893 }
894
895 static unsigned int
896 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
897 {
898   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
899   char * entry_in = NULL;
900   char * entry_out = NULL;
901   char * quota_out_str;
902   char * quota_in_str;
903   int c;
904
905   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
906   {
907     in_dest[c] = 0;
908     out_dest[c] = 0;
909     switch (quotas[c]) {
910       case GNUNET_ATS_NET_UNSPECIFIED:
911         entry_out = "UNSPECIFIED_QUOTA_OUT";
912         entry_in = "UNSPECIFIED_QUOTA_IN";
913         break;
914       case GNUNET_ATS_NET_LOOPBACK:
915         entry_out = "LOOPBACK_QUOTA_OUT";
916         entry_in = "LOOPBACK_QUOTA_IN";
917         break;
918       case GNUNET_ATS_NET_LAN:
919         entry_out = "LAN_QUOTA_OUT";
920         entry_in = "LAN_QUOTA_IN";
921         break;
922       case GNUNET_ATS_NET_WAN:
923         entry_out = "WAN_QUOTA_OUT";
924         entry_in = "WAN_QUOTA_IN";
925         break;
926       case GNUNET_ATS_NET_WLAN:
927         entry_out = "WLAN_QUOTA_OUT";
928         entry_in = "WLAN_QUOTA_IN";
929         break;
930       default:
931         break;
932     }
933
934     if ((entry_in == NULL) || (entry_out == NULL))
935       continue;
936
937     /* quota out */
938     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
939     {
940       if (0 == strcmp(quota_out_str, BIG_M_STRING) ||
941           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
942         out_dest[c] = UINT32_MAX;
943
944       GNUNET_free (quota_out_str);
945       quota_out_str = NULL;
946     }
947     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
948       out_dest[c] = UINT32_MAX;
949     else
950       out_dest[c] = UINT32_MAX;
951
952     /* quota in */
953     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
954     {
955       if (0 == strcmp(quota_in_str, BIG_M_STRING) ||
956           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
957         in_dest[c] = UINT32_MAX;
958
959       GNUNET_free (quota_in_str);
960       quota_in_str = NULL;
961     }
962     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
963     {
964       in_dest[c] = UINT32_MAX;
965     }
966     else
967     {
968         in_dest[c] = UINT32_MAX;
969     }
970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded quota: %s %u, %s %u\n", entry_in, in_dest[c], entry_out, out_dest[c]);
971
972   }
973   return GNUNET_ATS_NetworkTypeCount;
974 }
975
976
977
978 /**
979  * Initialize address subsystem.
980  *
981  * @param cfg configuration to use
982  * @param stats the statistics handle to use
983  */
984 struct GAS_Addresses_Handle *
985 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
986                     const struct GNUNET_STATISTICS_Handle *stats)
987 {
988   struct GAS_Addresses_Handle *ah;
989   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
990   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
991   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
992   int quota_count;
993   char *mode_str;
994   int c;
995
996   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
997   handle = ah;
998   handle->running = GNUNET_NO;
999
1000   /* Initialize the addresses database */
1001   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1002   GNUNET_assert (NULL != ah->addresses);
1003
1004   /* Figure out configured solution method */
1005   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1006   {
1007       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No ressource assignment method configured, using simplistic approch\n");
1008       ah->ats_mode = MODE_SIMPLISTIC;
1009   }
1010   else
1011   {
1012       for (c = 0; c < strlen (mode_str); c++)
1013         mode_str[c] = toupper (mode_str[c]);
1014       if (0 == strcmp (mode_str, "SIMPLISTIC"))
1015       {
1016           ah->ats_mode = MODE_SIMPLISTIC;
1017       }
1018       else if (0 == strcmp (mode_str, "MLP"))
1019       {
1020           ah->ats_mode = MODE_MLP;
1021 #if !HAVE_LIBGLPK
1022           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not availabe, please install \n", mode_str);
1023           ah->ats_mode = MODE_SIMPLISTIC;
1024 #endif
1025       }
1026       else
1027       {
1028           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid ressource assignment method `%s' configured, using simplistic approch\n", mode_str);
1029           ah->ats_mode = MODE_SIMPLISTIC;
1030       }
1031       GNUNET_free (mode_str);
1032   }
1033   /* Start configured solution method */
1034   switch (ah->ats_mode)
1035   {
1036     case MODE_MLP:
1037       /* Init the MLP solver with default values */
1038 #if HAVE_LIBGLPK
1039       ah->ats_mode = MODE_MLP;
1040       ah->s_init = &GAS_mlp_init;
1041       ah->s_update = &GAS_mlp_address_update;
1042       ah->s_get = &GAS_mlp_get_preferred_address;
1043       ah->s_pref = &GAS_mlp_address_change_preference;
1044       ah->s_del =  &GAS_mlp_address_delete;
1045       ah->s_done = &GAS_mlp_done;
1046 #else
1047       GNUNET_free (ah);
1048       return NULL;
1049 #endif
1050       break;
1051     case MODE_SIMPLISTIC:
1052       /* Init the simplistic solver with default values */
1053       ah->ats_mode = MODE_SIMPLISTIC;
1054       ah->s_init = &GAS_simplistic_init;
1055       ah->s_update = &GAS_simplistic_address_update;
1056       ah->s_get = &GAS_simplistic_get_preferred_address;
1057       ah->s_pref = &GAS_simplistic_address_change_preference;
1058       ah->s_del  = &GAS_simplistic_address_delete;
1059       ah->s_done = &GAS_simplistic_done;
1060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "SIMPLISTIC");
1061       break;
1062     default:
1063       return NULL;
1064       break;
1065   }
1066
1067   GNUNET_assert (NULL != ah->s_init);
1068   GNUNET_assert (NULL != ah->s_update);
1069   GNUNET_assert (NULL != ah->s_get);
1070   GNUNET_assert (NULL != ah->s_pref);
1071   GNUNET_assert (NULL != ah->s_del);
1072   GNUNET_assert (NULL != ah->s_done);
1073
1074   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1075
1076   ah->solver = ah->s_init (cfg, stats, quotas, quotas_in, quotas_out, quota_count);
1077   if (NULL == ah->solver)
1078   {
1079     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to initialize solver!\n");
1080     GNUNET_free (ah);
1081     return NULL;
1082   }
1083
1084   /* up and running */
1085   ah->running = GNUNET_YES;
1086   return ah;
1087 }
1088
1089
1090 /**
1091  * Free memory of address.
1092  *
1093  * @param cls NULL
1094  * @param key peer identity (unused)
1095  * @param value the 'struct ATS_Address' to free
1096  * @return GNUNET_OK (continue to iterate)
1097  */
1098 static int
1099 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1100 {
1101   struct ATS_Address *aa = value;
1102
1103   destroy_address (aa);
1104   return GNUNET_OK;
1105 }
1106
1107
1108 void
1109 GAS_addresses_destroy_all ()
1110 {
1111   if (GNUNET_NO == handle->running)
1112     return;
1113
1114   if (handle->addresses != NULL)
1115     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &free_address_it, NULL);
1116 }
1117
1118
1119 /**
1120  * Shutdown address subsystem.
1121  */
1122 void
1123 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1124 {
1125   struct GAS_Addresses_Suggestion_Requests *cur;
1126
1127   GNUNET_assert (NULL != handle);
1128   GAS_addresses_destroy_all ();
1129   handle->running = GNUNET_NO;
1130   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1131   handle->addresses = NULL;
1132   while (NULL != (cur = handle->r_head))
1133   {
1134       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1135       GNUNET_free (cur);
1136   }
1137
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 */