mod
[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    * Add an address to the solver
128    */
129   GAS_solver_address_add s_add;
130
131   /**
132    * Update address in solver
133    */
134   GAS_solver_address_update s_update;
135
136   /**
137    * Get address from solver
138    */
139   GAS_solver_get_preferred_address s_get;
140
141   /**
142    * Delete address in solver
143    */
144   GAS_solver_address_delete s_del;
145
146   /**
147    * Change preference for quality in solver
148    */
149   GAS_solver_address_change_preference s_pref;
150
151   /**
152    * Shutdown solver
153    */
154   GAS_solver_done s_done;
155 };
156
157
158 /**
159  * Temporary handle
160  */
161 struct GAS_Addresses_Handle *handle;
162
163
164 static unsigned int
165 assemble_ats_information (const struct ATS_Address *aa,  struct GNUNET_ATS_Information **dest)
166 {
167   unsigned int ats_count = GNUNET_ATS_PropertyCount - 1;
168   struct GNUNET_ATS_Information *ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
169   (*dest) = ats;
170
171   ats[0].type = ntohl(GNUNET_ATS_UTILIZATION_UP);
172   ats[0].value = aa->atsp_utilization_out.value__;
173   ats[1].type = ntohl(GNUNET_ATS_UTILIZATION_DOWN);
174   ats[1].value = aa->atsp_utilization_in.value__;
175   ats[2].type = ntohl(GNUNET_ATS_NETWORK_TYPE);
176   ats[2].value = ntohl(aa->atsp_network_type);
177   ats[3].type = ntohl(GNUNET_ATS_QUALITY_NET_DELAY);
178   ats[3].value = ntohl(aa->atsp_latency.rel_value);
179   ats[4].type = ntohl(GNUNET_ATS_QUALITY_NET_DISTANCE);
180   ats[4].value = ntohl(aa->atsp_distance);
181   ats[5].type = ntohl(GNUNET_ATS_COST_WAN);
182   ats[5].value = ntohl (aa->atsp_cost_wan);
183   ats[6].type = ntohl(GNUNET_ATS_COST_LAN);
184   ats[6].value = ntohl (aa->atsp_cost_lan);
185   ats[7].type = ntohl(GNUNET_ATS_COST_WLAN);
186   ats[7].value = ntohl (aa->atsp_cost_wlan);
187   return ats_count;
188 }
189
190 static unsigned int
191 disassemble_ats_information (const struct GNUNET_ATS_Information *src,
192                              uint32_t ats_count,
193                              struct ATS_Address *dest)
194 {
195   int i;
196   int res = 0;
197   for (i = 0; i < ats_count; i++)
198     switch (ntohl (src[i].type))
199     {
200     case GNUNET_ATS_UTILIZATION_UP:
201       dest->atsp_utilization_out.value__ = src[i].value;
202       res ++;
203       break;
204     case GNUNET_ATS_UTILIZATION_DOWN:
205       dest->atsp_utilization_in.value__ = src[i].value;
206       res ++;
207       break;
208     case GNUNET_ATS_QUALITY_NET_DELAY:
209       dest->atsp_latency.rel_value = ntohl (src[i].value);
210       res ++;
211       break;
212     case GNUNET_ATS_QUALITY_NET_DISTANCE:
213       dest->atsp_distance = ntohl (src[i].value);
214       res ++;
215       break;
216     case GNUNET_ATS_COST_WAN:
217       dest->atsp_cost_wan = ntohl (src[i].value);
218       res ++;
219       break;
220     case GNUNET_ATS_COST_LAN:
221       dest->atsp_cost_lan = ntohl (src[i].value);
222       res ++;
223       break;
224     case GNUNET_ATS_COST_WLAN:
225       dest->atsp_cost_wlan = ntohl (src[i].value);
226       res ++;
227       break;
228     case GNUNET_ATS_NETWORK_TYPE:
229       dest->atsp_network_type = ntohl (src[i].value);
230       res ++;
231       break;
232     case GNUNET_ATS_ARRAY_TERMINATOR:
233       break;
234     default:
235       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
236                   "Received unsupported ATS type %u\n", ntohl (src[i].type));
237       GNUNET_break (0);
238       break;
239     }
240   return res;
241 }
242
243 /**
244  * Free the given address
245  * @param addr address to destroy
246  */
247 static void
248 free_address (struct ATS_Address *addr)
249 {
250   GNUNET_free (addr->plugin);
251   GNUNET_free (addr);
252 }
253
254 /**
255  * Create a ATS_address with the given information
256  * @param peer peer
257  * @param plugin_name plugin
258  * @param plugin_addr address
259  * @param plugin_addr_len address length
260  * @param session_id session
261  * @return the ATS_Address
262  */
263 static struct ATS_Address *
264 create_address (const struct GNUNET_PeerIdentity *peer,
265                 const char *plugin_name,
266                 const void *plugin_addr, size_t plugin_addr_len,
267                 uint32_t session_id)
268 {
269   struct ATS_Address *aa = NULL;
270
271   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
272   aa->peer = *peer;
273   aa->addr_len = plugin_addr_len;
274   aa->addr = &aa[1];
275   memcpy (&aa[1], plugin_addr, plugin_addr_len);
276   aa->plugin = GNUNET_strdup (plugin_name);
277   aa->session_id = session_id;
278   return aa;
279 }
280
281
282 /**
283  * Destroy the given address.
284  *
285  * @param addr address to destroy
286  * @return GNUNET_YES if bandwidth allocations should be recalcualted
287  */
288 static int
289 destroy_address (struct ATS_Address *addr)
290 {
291   int ret;
292
293   ret = GNUNET_NO;
294   GNUNET_assert (GNUNET_YES ==
295                  GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
296                                                        &addr->peer.hashPubKey,
297                                                        addr));
298
299   handle->s_del (handle->solver, handle->addresses, addr);
300   free_address (addr);
301   return ret;
302 }
303
304
305 struct CompareAddressContext
306 {
307   const struct ATS_Address *search;
308
309   /* exact_address != NULL if address and session is equal */
310   struct ATS_Address *exact_address;
311   /* exact_address != NULL if address and session is 0 */
312   struct ATS_Address *base_address;
313 };
314
315
316 static int
317 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
318 {
319   struct CompareAddressContext *cac = cls;
320   struct ATS_Address *aa = value;
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 (cac.exact_address == NULL)
404     return cac.base_address;
405   return cac.exact_address;
406 }
407
408
409 static struct ATS_Address *
410 lookup_address (const struct GNUNET_PeerIdentity *peer,
411                 const char *plugin_name, const void *plugin_addr,
412                 size_t plugin_addr_len, uint32_t session_id,
413                 const struct GNUNET_ATS_Information *atsi,
414                 uint32_t atsi_count)
415 {
416   struct ATS_Address *aa;
417   struct ATS_Address *old;
418
419   aa = create_address (peer,
420                        plugin_name,
421                        plugin_addr, plugin_addr_len,
422                        session_id);
423
424   aa->mlp_information = NULL;
425
426   /* Get existing address or address with session == 0 */
427   old = find_address (peer, aa);
428   free_address (aa);
429   if (old == NULL)
430   {
431     return NULL;
432   }
433   else if (old->session_id != session_id)
434   {
435     return NULL;
436   }
437   return old;
438 }
439
440
441 void
442 GAS_addresses_add (const struct GNUNET_PeerIdentity *peer,
443                       const char *plugin_name, const void *plugin_addr,
444                       size_t plugin_addr_len, uint32_t session_id,
445                       const struct GNUNET_ATS_Information *atsi,
446                       uint32_t atsi_count)
447 {
448   struct ATS_Address *aa;
449   struct ATS_Address *old;
450   unsigned int ats_res;
451
452   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
453               "Received `%s' for peer `%s'\n",
454               "ADDRESS ADD",
455               GNUNET_i2s (peer));
456
457   if (GNUNET_NO == handle->running)
458     return;
459
460   GNUNET_assert (NULL != handle->addresses);
461
462   aa = create_address (peer,
463                        plugin_name,
464                        plugin_addr, plugin_addr_len,
465                        session_id);
466   aa->mlp_information = NULL;
467   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, aa)))
468   {
469       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
470                 "While adding address: had %u ATS elements to add, could only add %u\n",
471                 atsi_count, ats_res);
472   }
473
474   /* Get existing address or address with session == 0 */
475   old = find_address (peer, aa);
476   if (old == NULL)
477   {
478     /* We have a new address */
479     GNUNET_assert (GNUNET_OK ==
480                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
481                                                       &peer->hashPubKey, aa,
482                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
483     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
484                 GNUNET_i2s (peer), session_id, aa);
485     /* Tell solver about update */
486     handle->s_add (handle->solver, handle->addresses, aa);
487     return;
488   }
489
490   if (old->session_id != 0)
491   {
492       /* This address and session is already existing */
493       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
494                 "Added already existing address for peer `%s' `%s' %p with new session %u\n",
495                 GNUNET_i2s (peer), plugin_name, session_id);
496       GNUNET_break (0);
497       return;
498   }
499
500   /* We have an address without an session, update this address */
501   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502             "Updated existing address for peer `%s' %p with new session %u\n",
503             GNUNET_i2s (peer), old, session_id);
504   old->session_id = session_id;
505   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, old)))
506   {
507       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
508                 "While updating address: had %u ATS elements to add, could only add %u\n",
509                 atsi_count, ats_res);
510   }
511   GNUNET_free (aa->plugin);
512   GNUNET_free (aa);
513   handle->s_add (handle->solver, handle->addresses, old);
514 }
515
516
517 void
518 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
519                       const char *plugin_name, const void *plugin_addr,
520                       size_t plugin_addr_len, uint32_t session_id,
521                       const struct GNUNET_ATS_Information *atsi,
522                       uint32_t atsi_count)
523 {
524   struct ATS_Address *old;
525   uint32_t ats_res;
526
527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528                 "Received `%s' for peer `%s'\n",
529                 "ADDRESS UPDATE",
530                 GNUNET_i2s (peer));
531
532   if (GNUNET_NO == handle->running)
533     return;
534
535   GNUNET_assert (NULL != handle->addresses);
536
537   /* Get existing address */
538   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
539                        session_id, atsi, atsi_count);
540   if (old == NULL)
541   {
542     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
543                 GNUNET_i2s (peer), plugin_name, session_id);
544     GNUNET_break (0);
545     return;
546   }
547
548   if (atsi_count != (ats_res = disassemble_ats_information (atsi, atsi_count, old)))
549   {
550       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551                 "While adding address: had %u ATS elements to add, could only add %u\n",
552                 atsi_count, ats_res);
553   }
554
555   /* Tell solver about update */
556   handle->s_update (handle->solver, handle->addresses, old);
557 }
558
559
560 /**
561  * Delete an address
562  *
563  * If session != 0, just the session is deleted, the address itself still exists
564  * If session == 0, remove full address
565  * If session == 0 and addrlen == 0, destroy inbound address
566  *
567  * @param cls unused
568  * @param key unused
569  * @param value the 'struct ATS_Address'
570  * @return GNUNET_OK (continue to iterate)
571  */
572 static int
573 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
574 {
575   const struct ATS_Address *info = cls;
576   struct ATS_Address *aa = value;
577
578   GNUNET_assert (0 ==
579                  memcmp (&aa->peer, &info->peer,
580                          sizeof (struct GNUNET_PeerIdentity)));
581   /* session == 0, remove full address  */
582   if ((info->session_id == 0) && (0 == strcmp (info->plugin, aa->plugin)) &&
583       (aa->addr_len == info->addr_len) &&
584       (0 == memcmp (info->addr, aa->addr, aa->addr_len)))
585   {
586
587     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
588                 "Deleting address for peer `%s': `%s' %u\n",
589                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
590
591     destroy_address (aa);
592       // FIXME if (GNUNET_YES == destroy_address (aa))recalculate_assigned_bw ();
593     return GNUNET_OK;
594   }
595   /* session != 0, just remove session */
596   if (aa->session_id != info->session_id)
597     return GNUNET_OK;           /* irrelevant */
598   if (aa->session_id != 0)
599     GNUNET_break (0 == strcmp (info->plugin, aa->plugin));
600   /* session died */
601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
602               "Deleting session for peer `%s': `%s' %u\n",
603               GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
604   aa->session_id = 0;
605
606   if (GNUNET_YES == aa->active)
607   {
608     aa->active = GNUNET_NO;
609     //FIXME recalculate_assigned_bw ();
610   }
611
612   /* session == 0 and addrlen == 0 : destroy address */
613   if (aa->addr_len == 0)
614   {
615     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
616                 "Deleting session and address for peer `%s': `%s' %u\n",
617                 GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
618     (void) destroy_address (aa);
619   }
620   else
621   {
622     /* session was set to 0, update address */
623 #if HAVE_LIBGLPK
624   if (handle->ats_mode == MODE_MLP)
625     GAS_mlp_address_update (handle->solver, handle->addresses, aa);
626 #endif
627   }
628
629   return GNUNET_OK;
630 }
631
632
633 void
634 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
635                        const char *plugin_name, const void *plugin_addr,
636                        size_t plugin_addr_len, uint32_t session_id)
637 {
638   struct ATS_Address *aa;
639   struct ATS_Address *old;
640
641   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
642               "Received `%s' for peer `%s'\n",
643               "ADDRESS DESTROY",
644               GNUNET_i2s (peer));
645
646   if (GNUNET_NO == handle->running)
647     return;
648
649   /* Get existing address */
650   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len,
651                        session_id, NULL, 0);
652   if (old == NULL)
653   {
654     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
655                 GNUNET_i2s (peer), plugin_name, session_id);
656     return;
657   }
658
659   GNUNET_break (0 < strlen (plugin_name));
660   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
661   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
662                                               &destroy_by_session_id, aa);
663   free_address (aa);
664 }
665
666
667 int
668 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
669                       const char *plugin_name, const void *plugin_addr,
670                       size_t plugin_addr_len, uint32_t session_id, int in_use)
671 {
672   struct ATS_Address *old;
673
674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
675                 "Received `%s' for peer `%s'\n",
676                 "ADDRESS IN USE",
677                 GNUNET_i2s (peer));
678
679   if (GNUNET_NO == handle->running)
680     return GNUNET_SYSERR;
681
682   old = lookup_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id, NULL, 0);
683   if (NULL == old)
684   {
685     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
686                 "Trying to set unknown address `%s', %s %u %s \n",
687                 GNUNET_i2s (peer),
688                 plugin_name, session_id,
689                 (GNUNET_NO == in_use) ? "NO" : "YES");
690     GNUNET_break (0);
691     return GNUNET_SYSERR;
692   }
693   if (old->used == in_use)
694   {
695     GNUNET_break (0);
696     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
697                 "Address in use called multiple times for peer `%s': %s -> %s \n",
698                 GNUNET_i2s (peer),
699                 (GNUNET_NO == old->used) ? "NO" : "YES",
700                 (GNUNET_NO == in_use) ? "NO" : "YES");
701     return GNUNET_SYSERR;
702   }
703   old->used = in_use;
704
705   /* Tell solver about update */
706   handle->s_update (handle->solver, handle->addresses, old);
707
708   return GNUNET_OK;
709 }
710
711
712 /**
713  * Cancel address suggestions for a peer
714  *
715  * @param peer the respective peer
716  */
717 void
718 GAS_addresses_request_address_cancel (const struct GNUNET_PeerIdentity *peer)
719 {
720   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
721
722   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
723               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
724
725   while (NULL != cur)
726   {
727       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
728         break; /* found */
729       cur = cur->next;
730   }
731
732   if (NULL == cur)
733   {
734       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
735                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
736       return;
737   }
738   GAS_addresses_handle_backoff_reset (peer);
739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
740               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
741   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
742   GNUNET_free (cur);
743 }
744
745
746 /**
747  * Add an address suggestions for a peer
748  *
749  * @param peer the respective peer
750  */
751 void
752 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
753 {
754   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
755   struct ATS_Address *aa;
756   struct GNUNET_ATS_Information *ats;
757   unsigned int ats_count;
758
759   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
760               "Received `%s' for peer `%s'\n",
761               "REQUEST ADDRESS",
762               GNUNET_i2s (peer));
763
764   if (GNUNET_NO == handle->running)
765     return;
766   while (NULL != cur)
767   {
768       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
769         break; /* already suggesting */
770       cur = cur->next;
771   }
772   if (NULL == cur)
773   {
774       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
775       cur->id = (*peer);
776       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
777   }
778
779   /* Get prefered address from solver */
780   aa = (struct ATS_Address *) handle->s_get (handle->solver, handle->addresses, peer);
781   if (NULL == aa)
782   {
783     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
784                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
785     return;
786   }
787
788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
789               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
790
791   ats_count = assemble_ats_information (aa, &ats);
792   GAS_scheduling_transmit_address_suggestion (peer,
793                                               aa->plugin,
794                                               aa->addr, aa->addr_len,
795                                               aa->session_id,
796                                               ats, ats_count,
797                                               aa->assigned_bw_out,
798                                               aa->assigned_bw_in);
799
800   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
801   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), aa->block_interval);
802
803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
804        "Address %p ready for suggestion, block interval now %llu \n",
805        aa, aa->block_interval);
806
807
808   GNUNET_free (ats);
809 }
810
811
812 static int
813 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
814 {
815   struct ATS_Address *aa = value;
816
817   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
818               "Resetting interval for peer `%s' address %p from %llu to 0\n",
819               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
820
821   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
822   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
823   return GNUNET_OK;
824 }
825
826
827 void
828 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
829 {
830   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
831               "Received `%s' for peer `%s'\n",
832               "RESET BACKOFF",
833               GNUNET_i2s (peer));
834
835   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
836                                               &peer->hashPubKey,
837                                               &reset_address_it,
838                                               NULL));
839 }
840
841
842 void
843 GAS_addresses_change_preference (const struct GNUNET_PeerIdentity *peer,
844                                  enum GNUNET_ATS_PreferenceKind kind,
845                                  float score)
846 {
847   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
848               "Received `%s' for peer `%s'\n",
849               "CHANGE PREFERENCE",
850               GNUNET_i2s (peer));
851
852   if (GNUNET_NO == handle->running)
853     return;
854
855   /* Tell solver about update */
856   handle->s_pref (handle->solver, peer, kind, score);
857 }
858
859 static unsigned int
860 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
861 {
862   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
863   char * entry_in = NULL;
864   char * entry_out = NULL;
865   char * quota_out_str;
866   char * quota_in_str;
867   int c;
868
869   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
870   {
871     in_dest[c] = 0;
872     out_dest[c] = 0;
873     switch (quotas[c]) {
874       case GNUNET_ATS_NET_UNSPECIFIED:
875         entry_out = "UNSPECIFIED_QUOTA_OUT";
876         entry_in = "UNSPECIFIED_QUOTA_IN";
877         break;
878       case GNUNET_ATS_NET_LOOPBACK:
879         entry_out = "LOOPBACK_QUOTA_OUT";
880         entry_in = "LOOPBACK_QUOTA_IN";
881         break;
882       case GNUNET_ATS_NET_LAN:
883         entry_out = "LAN_QUOTA_OUT";
884         entry_in = "LAN_QUOTA_IN";
885         break;
886       case GNUNET_ATS_NET_WAN:
887         entry_out = "WAN_QUOTA_OUT";
888         entry_in = "WAN_QUOTA_IN";
889         break;
890       case GNUNET_ATS_NET_WLAN:
891         entry_out = "WLAN_QUOTA_OUT";
892         entry_in = "WLAN_QUOTA_IN";
893         break;
894       default:
895         break;
896     }
897
898     if ((entry_in == NULL) || (entry_out == NULL))
899       continue;
900
901     /* quota out */
902     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
903     {
904       if (0 == strcmp(quota_out_str, BIG_M_STRING) ||
905           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
906         out_dest[c] = UINT32_MAX;
907
908       GNUNET_free (quota_out_str);
909       quota_out_str = NULL;
910     }
911     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
912       out_dest[c] = UINT32_MAX;
913     else
914       out_dest[c] = UINT32_MAX;
915
916     /* quota in */
917     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
918     {
919       if (0 == strcmp(quota_in_str, BIG_M_STRING) ||
920           (GNUNET_SYSERR == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
921         in_dest[c] = UINT32_MAX;
922
923       GNUNET_free (quota_in_str);
924       quota_in_str = NULL;
925     }
926     else if (GNUNET_ATS_NET_UNSPECIFIED == quotas[c])
927     {
928       in_dest[c] = UINT32_MAX;
929     }
930     else
931     {
932         in_dest[c] = UINT32_MAX;
933     }
934     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded quota: %s %u, %s %u\n", entry_in, in_dest[c], entry_out, out_dest[c]);
935
936   }
937   return GNUNET_ATS_NetworkTypeCount;
938 }
939
940
941
942 /**
943  * Initialize address subsystem.
944  *
945  * @param cfg configuration to use
946  * @param stats the statistics handle to use
947  */
948 struct GAS_Addresses_Handle *
949 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
950                     const struct GNUNET_STATISTICS_Handle *stats)
951 {
952   struct GAS_Addresses_Handle *ah;
953   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
954   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
955   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
956   int quota_count;
957   char *mode_str;
958   int c;
959
960   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
961   handle = ah;
962   handle->running = GNUNET_NO;
963
964   /* Initialize the addresses database */
965   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
966   GNUNET_assert (NULL != ah->addresses);
967
968   /* Figure out configured solution method */
969   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
970   {
971       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No ressource assignment method configured, using simplistic approch\n");
972       ah->ats_mode = MODE_SIMPLISTIC;
973   }
974   else
975   {
976       for (c = 0; c < strlen (mode_str); c++)
977         mode_str[c] = toupper (mode_str[c]);
978       if (0 == strcmp (mode_str, "SIMPLISTIC"))
979       {
980           ah->ats_mode = MODE_SIMPLISTIC;
981       }
982       else if (0 == strcmp (mode_str, "MLP"))
983       {
984           ah->ats_mode = MODE_MLP;
985 #if !HAVE_LIBGLPK
986           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not availabe, please install \n", mode_str);
987           ah->ats_mode = MODE_SIMPLISTIC;
988 #endif
989       }
990       else
991       {
992           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid ressource assignment method `%s' configured, using simplistic approch\n", mode_str);
993           ah->ats_mode = MODE_SIMPLISTIC;
994       }
995       GNUNET_free (mode_str);
996   }
997   /* Start configured solution method */
998   switch (ah->ats_mode)
999   {
1000     case MODE_MLP:
1001       /* Init the MLP solver with default values */
1002 #if HAVE_LIBGLPK
1003       ah->ats_mode = MODE_MLP;
1004       ah->s_init = &GAS_mlp_init;
1005       ah->s_add = &GAS_mlp_address_add;
1006       ah->s_update = &GAS_mlp_address_update;
1007       ah->s_get = &GAS_mlp_get_preferred_address;
1008       ah->s_pref = &GAS_mlp_address_change_preference;
1009       ah->s_del =  &GAS_mlp_address_delete;
1010       ah->s_done = &GAS_mlp_done;
1011 #else
1012       GNUNET_free (ah);
1013       return NULL;
1014 #endif
1015       break;
1016     case MODE_SIMPLISTIC:
1017       /* Init the simplistic solver with default values */
1018       ah->ats_mode = MODE_SIMPLISTIC;
1019       ah->s_init = &GAS_simplistic_init;
1020       ah->s_add = &GAS_simplistic_address_add;
1021       ah->s_update = &GAS_simplistic_address_update;
1022       ah->s_get = &GAS_simplistic_get_preferred_address;
1023       ah->s_pref = &GAS_simplistic_address_change_preference;
1024       ah->s_del  = &GAS_simplistic_address_delete;
1025       ah->s_done = &GAS_simplistic_done;
1026       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "SIMPLISTIC");
1027       break;
1028     default:
1029       return NULL;
1030       break;
1031   }
1032
1033   GNUNET_assert (NULL != ah->s_init);
1034   GNUNET_assert (NULL != ah->s_add);
1035   GNUNET_assert (NULL != ah->s_update);
1036   GNUNET_assert (NULL != ah->s_get);
1037   GNUNET_assert (NULL != ah->s_pref);
1038   GNUNET_assert (NULL != ah->s_del);
1039   GNUNET_assert (NULL != ah->s_done);
1040
1041   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1042
1043   ah->solver = ah->s_init (cfg, stats, quotas, quotas_in, quotas_out, quota_count);
1044   if (NULL == ah->solver)
1045   {
1046     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to initialize solver!\n");
1047     GNUNET_free (ah);
1048     return NULL;
1049   }
1050
1051   /* up and running */
1052   ah->running = GNUNET_YES;
1053   return ah;
1054 }
1055
1056
1057 /**
1058  * Free memory of address.
1059  *
1060  * @param cls NULL
1061  * @param key peer identity (unused)
1062  * @param value the 'struct ATS_Address' to free
1063  * @return GNUNET_OK (continue to iterate)
1064  */
1065 static int
1066 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1067 {
1068   struct ATS_Address *aa = value;
1069
1070   destroy_address (aa);
1071   return GNUNET_OK;
1072 }
1073
1074
1075 void
1076 GAS_addresses_destroy_all ()
1077 {
1078   if (GNUNET_NO == handle->running)
1079     return;
1080
1081   if (handle->addresses != NULL)
1082     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &free_address_it, NULL);
1083 }
1084
1085
1086 /**
1087  * Shutdown address subsystem.
1088  */
1089 void
1090 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1091 {
1092   struct GAS_Addresses_Suggestion_Requests *cur;
1093
1094   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1095               "Shutting down addresses\n");
1096   GNUNET_assert (NULL != handle);
1097   GAS_addresses_destroy_all ();
1098   handle->running = GNUNET_NO;
1099   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1100   handle->addresses = NULL;
1101   while (NULL != (cur = handle->r_head))
1102   {
1103       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1104       GNUNET_free (cur);
1105   }
1106
1107   GNUNET_free (handle);
1108   /* Stop configured solution method */
1109
1110 }
1111
1112 struct PeerIteratorContext
1113 {
1114   GNUNET_ATS_Peer_Iterator it;
1115   void *it_cls;
1116   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1117 };
1118
1119 static int
1120 peer_it (void *cls,
1121          const struct GNUNET_HashCode * key,
1122          void *value)
1123 {
1124   struct PeerIteratorContext *ip_ctx = cls;
1125   struct GNUNET_PeerIdentity tmp;
1126
1127   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1128   {
1129       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1130       tmp.hashPubKey = (*key);
1131       ip_ctx->it (ip_ctx->it_cls, &tmp);
1132   }
1133
1134   return GNUNET_OK;
1135 }
1136
1137 /**
1138  * Return all peers currently known to ATS
1139  *
1140  * @param p_it the iterator to call for every peer, callbach with id == NULL
1141  *        when done
1142  * @param p_it_cls the closure for the iterator
1143  */
1144 void
1145 GAS_addresses_iterate_peers (GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1146 {
1147   struct PeerIteratorContext ip_ctx;
1148   unsigned int size;
1149
1150   if (NULL == p_it)
1151       return;
1152   GNUNET_assert (NULL != handle->addresses);
1153
1154   size = GNUNET_CONTAINER_multihashmap_size(handle->addresses);
1155   if (0 != size)
1156   {
1157     ip_ctx.it = p_it;
1158     ip_ctx.it_cls = p_it_cls;
1159     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1160     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &peer_it, &ip_ctx);
1161     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1162   }
1163   p_it (p_it_cls, NULL);
1164 }
1165
1166 struct PeerInfoIteratorContext
1167 {
1168   GNUNET_ATS_PeerInfo_Iterator it;
1169   void *it_cls;
1170 };
1171
1172
1173 static int 
1174 peerinfo_it (void *cls,
1175              const struct GNUNET_HashCode * key,
1176              void *value)
1177 {
1178   struct PeerInfoIteratorContext *pi_ctx = cls;
1179   struct ATS_Address *addr = (struct ATS_Address *)  value;
1180   struct GNUNET_ATS_Information *ats;
1181   uint32_t ats_count;
1182
1183   if (NULL != pi_ctx->it)
1184   {
1185     ats_count = assemble_ats_information (addr, &ats);
1186
1187     pi_ctx->it (pi_ctx->it_cls,
1188                 &addr->peer,
1189                 addr->plugin,
1190                 addr->addr, addr->addr_len,
1191                 addr->active,
1192                 ats, ats_count,
1193                 addr->assigned_bw_out,
1194                 addr->assigned_bw_in);
1195     GNUNET_free (ats);
1196   }
1197   return GNUNET_YES;
1198 }
1199
1200
1201 /**
1202  * Return all peers currently known to ATS
1203  *
1204  * @param peer the respective peer
1205  * @param pi_it the iterator to call for every peer
1206  * @param pi_it_cls the closure for the iterator
1207  */
1208 void
1209 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer, GNUNET_ATS_PeerInfo_Iterator pi_it, void *pi_it_cls)
1210 {
1211   struct PeerInfoIteratorContext pi_ctx;
1212   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1213   GNUNET_assert (NULL != peer);
1214   GNUNET_assert (NULL != handle->addresses);
1215   if (NULL == pi_it)
1216     return; /* does not make sense without callback */
1217
1218   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1219   pi_ctx.it = pi_it;
1220   pi_ctx.it_cls = pi_it_cls;
1221
1222   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1223
1224   if (NULL != pi_it)
1225     pi_it (pi_it_cls, NULL, NULL, NULL, 0, GNUNET_NO, NULL, 0, zero_bw, zero_bw);
1226
1227 }
1228
1229
1230 /* end of gnunet-service-ats_addresses.c */