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