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