change
[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   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
501               "Received `%s' for peer `%s'\n",
502               "ADDRESS ADD",
503               GNUNET_i2s (peer));
504
505   if (GNUNET_NO == handle->running)
506     return;
507
508   GNUNET_assert (NULL != handle->addresses);
509
510   aa = create_address (peer,
511                        plugin_name,
512                        plugin_addr, plugin_addr_len,
513                        session_id);
514   aa->mlp_information = NULL;
515   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, aa)))
516   {
517       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
518                 "While adding address: had %u ATS elements to add, could only add %u\n",
519                 atsi_count, ats_res);
520   }
521
522   /* Get existing address or address with session == 0 */
523   old = find_address (peer, aa);
524   if (old == NULL)
525   {
526     /* We have a new address */
527     GNUNET_assert (GNUNET_OK ==
528                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
529                                                       &peer->hashPubKey, aa,
530                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
531     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
532                 GNUNET_i2s (peer), session_id, aa);
533     /* Tell solver about update */
534     handle->s_update (handle->solver, handle->addresses, aa);
535     return;
536   }
537
538   if (old->session_id != 0)
539   {
540       /* This address and session is already existing */
541       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
542                 "Added already existing address for peer `%s' `%s' %p with new session %u\n",
543                 GNUNET_i2s (peer), plugin_name, session_id);
544       GNUNET_break (0);
545       return;
546   }
547
548   /* We have an address without an session, update this address */
549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
550             "Updated existing address for peer `%s' %p with new session %u\n",
551             GNUNET_i2s (peer), old, session_id);
552   old->session_id = session_id;
553   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, old)))
554   {
555       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
556                 "While updating address: had %u ATS elements to add, could only add %u\n",
557                 atsi_count, ats_res);
558   }
559   GNUNET_free (aa->plugin);
560   GNUNET_free (aa);
561   handle->s_update (handle->solver, handle->addresses, old);
562 }
563
564
565 void
566 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
567                       const char *plugin_name, const void *plugin_addr,
568                       size_t plugin_addr_len, uint32_t session_id,
569                       const struct GNUNET_ATS_Information *atsi,
570                       uint32_t atsi_count)
571 {
572   struct ATS_Address *old;
573   uint32_t ats_res;
574
575   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
576                 "Received `%s' for peer `%s'\n",
577                 "ADDRESS UPDATE",
578                 GNUNET_i2s (peer));
579
580   if (GNUNET_NO == handle->running)
581     return;
582
583   GNUNET_assert (NULL != handle->addresses);
584
585   /* Get existing address */
586   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
587                        session_id, atsi, atsi_count);
588   if (old == NULL)
589   {
590     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
591                 GNUNET_i2s (peer), plugin_name, session_id);
592     GNUNET_break (0);
593     return;
594   }
595
596   if (atsi_count != (ats_res = disassemble_ats_information (atsi, atsi_count, old)))
597   {
598       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
599                 "While adding address: had %u ATS elements to add, could only add %u\n",
600                 atsi_count, ats_res);
601   }
602
603   /* Tell solver about update */
604   handle->s_update (handle->solver, handle->addresses, old);
605 }
606
607
608 /**
609  * Delete an address
610  *
611  * If session != 0, just the session is deleted, the address itself still exists
612  * If session == 0, remove full address
613  * If session == 0 and addrlen == 0, destroy inbound address
614  *
615  * @param cls unused
616  * @param key unused
617  * @param value the 'struct ATS_Address'
618  * @return GNUNET_OK (continue to iterate)
619  */
620 static int
621 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
622 {
623   const struct ATS_Address *info = cls;
624   struct ATS_Address *aa = value;
625
626   GNUNET_assert (0 ==
627                  memcmp (&aa->peer, &info->peer,
628                          sizeof (struct GNUNET_PeerIdentity)));
629   /* session == 0, remove full address  */
630   if ((info->session_id == 0) && (0 == strcmp (info->plugin, aa->plugin)) &&
631       (aa->addr_len == info->addr_len) &&
632       (0 == memcmp (info->addr, aa->addr, aa->addr_len)))
633   {
634
635     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
636                 "Deleting address for peer `%s': `%s' %u\n",
637                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
638
639     destroy_address (aa);
640       // FIXME if (GNUNET_YES == destroy_address (aa))recalculate_assigned_bw ();
641     return GNUNET_OK;
642   }
643   /* session != 0, just remove session */
644   if (aa->session_id != info->session_id)
645     return GNUNET_OK;           /* irrelevant */
646   if (aa->session_id != 0)
647     GNUNET_break (0 == strcmp (info->plugin, aa->plugin));
648   /* session died */
649   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
650               "Deleting session for peer `%s': `%s' %u\n",
651               GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
652   aa->session_id = 0;
653
654   if (GNUNET_YES == aa->active)
655   {
656     aa->active = GNUNET_NO;
657     //FIXME recalculate_assigned_bw ();
658   }
659
660   /* session == 0 and addrlen == 0 : destroy address */
661   if (aa->addr_len == 0)
662   {
663     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
664                 "Deleting session and address for peer `%s': `%s' %u\n",
665                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
666     (void) destroy_address (aa);
667   }
668   else
669   {
670     /* session was set to 0, update address */
671 #if HAVE_LIBGLPK
672   if (handle->ats_mode == MODE_MLP)
673     GAS_mlp_address_update (handle->solver, handle->addresses, aa);
674 #endif
675   }
676
677   return GNUNET_OK;
678 }
679
680
681 void
682 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
683                        const char *plugin_name, const void *plugin_addr,
684                        size_t plugin_addr_len, uint32_t session_id)
685 {
686   struct ATS_Address *aa;
687   struct ATS_Address *old;
688
689   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
690               "Received `%s' for peer `%s'\n",
691               "ADDRESS DESTROY",
692               GNUNET_i2s (peer));
693
694   if (GNUNET_NO == handle->running)
695     return;
696
697   /* Get existing address */
698   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
699                        session_id, NULL, 0);
700   if (old == NULL)
701   {
702     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
703                 GNUNET_i2s (peer), plugin_name, session_id);
704     return;
705   }
706
707   GNUNET_break (0 < strlen (plugin_name));
708   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
709   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
710                                               &destroy_by_session_id, aa);
711   free_address (aa);
712 }
713
714
715 int
716 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
717                       const char *plugin_name, const void *plugin_addr,
718                       size_t plugin_addr_len, uint32_t session_id, int in_use)
719 {
720   struct ATS_Address *old;
721
722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
723                 "Received `%s' for peer `%s'\n",
724                 "ADDRESS IN USE",
725                 GNUNET_i2s (peer));
726
727   if (GNUNET_NO == handle->running)
728     return GNUNET_SYSERR;
729
730   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id, NULL, 0);
731   if (NULL == old)
732   {
733     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
734                 "Trying to set unknown address `%s', %s %u %s \n",
735                 GNUNET_i2s (peer),
736                 plugin_name, session_id,
737                 (GNUNET_NO == in_use) ? "NO" : "YES");
738     GNUNET_break (0);
739     return GNUNET_SYSERR;
740   }
741   if (old->used == in_use)
742   {
743     GNUNET_break (0);
744     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
745                 "Address in use called multiple times for peer `%s': %s -> %s \n",
746                 GNUNET_i2s (peer),
747                 (GNUNET_NO == old->used) ? "NO" : "YES",
748                 (GNUNET_NO == in_use) ? "NO" : "YES");
749     return GNUNET_SYSERR;
750   }
751   old->used = in_use;
752
753   /* Tell solver about update */
754   handle->s_update (handle->solver, handle->addresses, old);
755
756   return GNUNET_OK;
757 }
758
759
760 /**
761  * Cancel address suggestions for a peer
762  *
763  * @param peer the respective peer
764  */
765 void
766 GAS_addresses_request_address_cancel (const struct GNUNET_PeerIdentity *peer)
767 {
768   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
769
770   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
771               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
772
773   while (NULL != cur)
774   {
775       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
776         break; /* found */
777       cur = cur->next;
778   }
779
780   if (NULL == cur)
781   {
782       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
783                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
784       return;
785   }
786   GAS_addresses_handle_backoff_reset (peer);
787   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
788               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
789   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
790   GNUNET_free (cur);
791 }
792
793
794 /**
795  * Add an address suggestions for a peer
796  *
797  * @param peer the respective peer
798  */
799 void
800 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
801 {
802   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
803   struct ATS_Address *aa;
804   struct GNUNET_ATS_Information *ats;
805   unsigned int ats_count;
806
807   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808               "Received `%s' for peer `%s'\n",
809               "REQUEST ADDRESS",
810               GNUNET_i2s (peer));
811
812   if (GNUNET_NO == handle->running)
813     return;
814   while (NULL != cur)
815   {
816       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
817         break; /* already suggesting */
818       cur = cur->next;
819   }
820   if (NULL == cur)
821   {
822       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
823       cur->id = (*peer);
824       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
825   }
826
827   /* Get prefered address from solver */
828   aa = (struct ATS_Address *) handle->s_get (handle->solver, handle->addresses, peer);
829   if (NULL == aa)
830   {
831     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
832                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
833     return;
834   }
835
836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
837               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
838
839   ats_count = assemble_ats_information (aa, &ats);
840   GAS_scheduling_transmit_address_suggestion (peer,
841                                               aa->plugin,
842                                               aa->addr, aa->addr_len,
843                                               aa->session_id,
844                                               ats, ats_count,
845                                               aa->assigned_bw_out,
846                                               aa->assigned_bw_in);
847
848   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
849   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), aa->block_interval);
850
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852        "Address %p ready for suggestion, block interval now %llu \n",
853        aa, aa->block_interval);
854
855
856   GNUNET_free (ats);
857 }
858
859
860 static int
861 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
862 {
863   struct ATS_Address *aa = value;
864
865   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
866               "Resetting interval for peer `%s' address %p from %llu to 0\n",
867               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
868
869   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
870   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
871   return GNUNET_OK;
872 }
873
874
875 void
876 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
877 {
878   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879               "Received `%s' for peer `%s'\n",
880               "RESET BACKOFF",
881               GNUNET_i2s (peer));
882
883   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
884                                               &peer->hashPubKey,
885                                               &reset_address_it,
886                                               NULL));
887 }
888
889
890 void
891 GAS_addresses_change_preference (const struct GNUNET_PeerIdentity *peer,
892                                  enum GNUNET_ATS_PreferenceKind kind,
893                                  float score)
894 {
895   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
896               "Received `%s' for peer `%s'\n",
897               "CHANGE PREFERENCE",
898               GNUNET_i2s (peer));
899
900   if (GNUNET_NO == handle->running)
901     return;
902
903   /* Tell solver about update */
904   handle->s_pref (handle->solver, peer, kind, score);
905 }
906
907 static unsigned int
908 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
909 {
910   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
911   char * entry_in = NULL;
912   char * entry_out = NULL;
913   char * quota_out_str;
914   char * quota_in_str;
915   int c;
916
917   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
918   {
919     in_dest[c] = 0;
920     out_dest[c] = 0;
921     switch (quotas[c]) {
922       case GNUNET_ATS_NET_UNSPECIFIED:
923         entry_out = "UNSPECIFIED_QUOTA_OUT";
924         entry_in = "UNSPECIFIED_QUOTA_IN";
925         break;
926       case GNUNET_ATS_NET_LOOPBACK:
927         entry_out = "LOOPBACK_QUOTA_OUT";
928         entry_in = "LOOPBACK_QUOTA_IN";
929         break;
930       case GNUNET_ATS_NET_LAN:
931         entry_out = "LAN_QUOTA_OUT";
932         entry_in = "LAN_QUOTA_IN";
933         break;
934       case GNUNET_ATS_NET_WAN:
935         entry_out = "WAN_QUOTA_OUT";
936         entry_in = "WAN_QUOTA_IN";
937         break;
938       case GNUNET_ATS_NET_WLAN:
939         entry_out = "WLAN_QUOTA_OUT";
940         entry_in = "WLAN_QUOTA_IN";
941         break;
942       default:
943         break;
944     }
945
946     if ((entry_in == NULL) || (entry_out == NULL))
947       continue;
948
949     /* quota out */
950     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
951     {
952       if (0 == strcmp(quota_out_str, BIG_M_STRING) ||
953           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
954         out_dest[c] = UINT32_MAX;
955
956       GNUNET_free (quota_out_str);
957       quota_out_str = NULL;
958     }
959     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
960       out_dest[c] = UINT32_MAX;
961     else
962       out_dest[c] = UINT32_MAX;
963
964     /* quota in */
965     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
966     {
967       if (0 == strcmp(quota_in_str, BIG_M_STRING) ||
968           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
969         in_dest[c] = UINT32_MAX;
970
971       GNUNET_free (quota_in_str);
972       quota_in_str = NULL;
973     }
974     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
975     {
976       in_dest[c] = UINT32_MAX;
977     }
978     else
979     {
980         in_dest[c] = UINT32_MAX;
981     }
982     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded quota: %s %u, %s %u\n", entry_in, in_dest[c], entry_out, out_dest[c]);
983
984   }
985   return GNUNET_ATS_NetworkTypeCount;
986 }
987
988
989
990 /**
991  * Initialize address subsystem.
992  *
993  * @param cfg configuration to use
994  * @param stats the statistics handle to use
995  */
996 struct GAS_Addresses_Handle *
997 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
998                     const struct GNUNET_STATISTICS_Handle *stats)
999 {
1000   struct GAS_Addresses_Handle *ah;
1001   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1002   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
1003   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
1004   int quota_count;
1005   char *mode_str;
1006   int c;
1007
1008   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
1009   handle = ah;
1010   handle->running = GNUNET_NO;
1011
1012   /* Initialize the addresses database */
1013   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1014   GNUNET_assert (NULL != ah->addresses);
1015
1016   /* Figure out configured solution method */
1017   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1018   {
1019       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No ressource assignment method configured, using simplistic approch\n");
1020       ah->ats_mode = MODE_SIMPLISTIC;
1021   }
1022   else
1023   {
1024       for (c = 0; c < strlen (mode_str); c++)
1025         mode_str[c] = toupper (mode_str[c]);
1026       if (0 == strcmp (mode_str, "SIMPLISTIC"))
1027       {
1028           ah->ats_mode = MODE_SIMPLISTIC;
1029       }
1030       else if (0 == strcmp (mode_str, "MLP"))
1031       {
1032           ah->ats_mode = MODE_MLP;
1033 #if !HAVE_LIBGLPK
1034           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not availabe, please install \n", mode_str);
1035           ah->ats_mode = MODE_SIMPLISTIC;
1036 #endif
1037       }
1038       else
1039       {
1040           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid ressource assignment method `%s' configured, using simplistic approch\n", mode_str);
1041           ah->ats_mode = MODE_SIMPLISTIC;
1042       }
1043       GNUNET_free (mode_str);
1044   }
1045   /* Start configured solution method */
1046   switch (ah->ats_mode)
1047   {
1048     case MODE_MLP:
1049       /* Init the MLP solver with default values */
1050 #if HAVE_LIBGLPK
1051       ah->ats_mode = MODE_MLP;
1052       ah->s_init = &GAS_mlp_init;
1053       ah->s_update = &GAS_mlp_address_update;
1054       ah->s_get = &GAS_mlp_get_preferred_address;
1055       ah->s_pref = &GAS_mlp_address_change_preference;
1056       ah->s_del =  &GAS_mlp_address_delete;
1057       ah->s_done = &GAS_mlp_done;
1058 #else
1059       GNUNET_free (ah);
1060       return NULL;
1061 #endif
1062       break;
1063     case MODE_SIMPLISTIC:
1064       /* Init the simplistic solver with default values */
1065       ah->ats_mode = MODE_SIMPLISTIC;
1066       ah->s_init = &GAS_simplistic_init;
1067       ah->s_update = &GAS_simplistic_address_update;
1068       ah->s_get = &GAS_simplistic_get_preferred_address;
1069       ah->s_pref = &GAS_simplistic_address_change_preference;
1070       ah->s_del  = &GAS_simplistic_address_delete;
1071       ah->s_done = &GAS_simplistic_done;
1072       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "SIMPLISTIC");
1073       break;
1074     default:
1075       return NULL;
1076       break;
1077   }
1078
1079   GNUNET_assert (NULL != ah->s_init);
1080   GNUNET_assert (NULL != ah->s_update);
1081   GNUNET_assert (NULL != ah->s_get);
1082   GNUNET_assert (NULL != ah->s_pref);
1083   GNUNET_assert (NULL != ah->s_del);
1084   GNUNET_assert (NULL != ah->s_done);
1085
1086   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1087
1088   ah->solver = ah->s_init (cfg, stats, quotas, quotas_in, quotas_out, quota_count);
1089   if (NULL == ah->solver)
1090   {
1091     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to initialize solver!\n");
1092     GNUNET_free (ah);
1093     return NULL;
1094   }
1095
1096   /* up and running */
1097   ah->running = GNUNET_YES;
1098   return ah;
1099 }
1100
1101
1102 /**
1103  * Free memory of address.
1104  *
1105  * @param cls NULL
1106  * @param key peer identity (unused)
1107  * @param value the 'struct ATS_Address' to free
1108  * @return GNUNET_OK (continue to iterate)
1109  */
1110 static int
1111 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1112 {
1113   struct ATS_Address *aa = value;
1114
1115   destroy_address (aa);
1116   return GNUNET_OK;
1117 }
1118
1119
1120 void
1121 GAS_addresses_destroy_all ()
1122 {
1123   if (GNUNET_NO == handle->running)
1124     return;
1125
1126   if (handle->addresses != NULL)
1127     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &free_address_it, NULL);
1128 }
1129
1130
1131 /**
1132  * Shutdown address subsystem.
1133  */
1134 void
1135 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1136 {
1137   struct GAS_Addresses_Suggestion_Requests *cur;
1138
1139   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1140               "Shutting down addresses\n");
1141   GNUNET_assert (NULL != handle);
1142   GAS_addresses_destroy_all ();
1143   handle->running = GNUNET_NO;
1144   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1145   handle->addresses = NULL;
1146   while (NULL != (cur = handle->r_head))
1147   {
1148       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1149       GNUNET_free (cur);
1150   }
1151
1152   GNUNET_free (handle);
1153   /* Stop configured solution method */
1154
1155 }
1156
1157 struct PeerIteratorContext
1158 {
1159   GNUNET_ATS_Peer_Iterator it;
1160   void *it_cls;
1161   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1162 };
1163
1164 static int
1165 peer_it (void *cls,
1166          const struct GNUNET_HashCode * key,
1167          void *value)
1168 {
1169   struct PeerIteratorContext *ip_ctx = cls;
1170   struct GNUNET_PeerIdentity tmp;
1171
1172   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1173   {
1174       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1175       tmp.hashPubKey = (*key);
1176       ip_ctx->it (ip_ctx->it_cls, &tmp);
1177   }
1178
1179   return GNUNET_OK;
1180 }
1181
1182 /**
1183  * Return all peers currently known to ATS
1184  *
1185  * @param p_it the iterator to call for every peer, callbach with id == NULL
1186  *        when done
1187  * @param p_it_cls the closure for the iterator
1188  */
1189 void
1190 GAS_addresses_iterate_peers (GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1191 {
1192   struct PeerIteratorContext ip_ctx;
1193   unsigned int size;
1194
1195   if (NULL == p_it)
1196       return;
1197   GNUNET_assert (NULL != handle->addresses);
1198
1199   size = GNUNET_CONTAINER_multihashmap_size(handle->addresses);
1200   if (0 != size)
1201   {
1202     ip_ctx.it = p_it;
1203     ip_ctx.it_cls = p_it_cls;
1204     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1205     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &peer_it, &ip_ctx);
1206     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1207   }
1208   p_it (p_it_cls, NULL);
1209 }
1210
1211 struct PeerInfoIteratorContext
1212 {
1213   GNUNET_ATS_PeerInfo_Iterator it;
1214   void *it_cls;
1215 };
1216
1217
1218 static int 
1219 peerinfo_it (void *cls,
1220              const struct GNUNET_HashCode * key,
1221              void *value)
1222 {
1223   struct PeerInfoIteratorContext *pi_ctx = cls;
1224   struct ATS_Address *addr = (struct ATS_Address *)  value;
1225   struct GNUNET_ATS_Information *ats;
1226   uint32_t ats_count;
1227
1228   if (NULL != pi_ctx->it)
1229   {
1230     ats_count = assemble_ats_information (addr, &ats);
1231
1232     pi_ctx->it (pi_ctx->it_cls,
1233                 &addr->peer,
1234                 addr->plugin,
1235                 addr->addr, addr->addr_len,
1236                 addr->active,
1237                 ats, ats_count,
1238                 addr->assigned_bw_out,
1239                 addr->assigned_bw_in);
1240     GNUNET_free (ats);
1241   }
1242   return GNUNET_YES;
1243 }
1244
1245
1246 /**
1247  * Return all peers currently known to ATS
1248  *
1249  * @param peer the respective peer
1250  * @param pi_it the iterator to call for every peer
1251  * @param pi_it_cls the closure for the iterator
1252  */
1253 void
1254 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, GNUNET_ATS_PeerInfo_Iterator pi_it, void *pi_it_cls)
1255 {
1256   struct PeerInfoIteratorContext pi_ctx;
1257   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1258   GNUNET_assert (NULL != peer);
1259   GNUNET_assert (NULL != handle->addresses);
1260   if (NULL == pi_it)
1261     return; /* does not make sense without callback */
1262
1263   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1264   pi_ctx.it = pi_it;
1265   pi_ctx.it_cls = pi_it_cls;
1266
1267   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1268
1269   if (NULL != pi_it)
1270     pi_it (pi_it_cls, NULL, NULL, NULL, 0, GNUNET_NO, NULL, 0, zero_bw, zero_bw);
1271
1272 }
1273
1274
1275 /* end of gnunet-service-ats_addresses.c */