docu
[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  * ATS addresses : ATS address management
41  *
42  * - General
43  *
44  * This ATS addresses ("addresses") component manages the addresses known to ATS
45  * service and suggests addresses to transport service when it is interested in
46  * address suggestion for a peer. ATS addresses also instantiates the bandwidth assignment
47  * mechanism (solver), notifies it about changes to addresses and forwards changes
48  * to bandwidth assignments to transport, depending if transport is interested
49  * in this change.
50  *
51  * - Initialization
52  * During initialization a hashmap to store addresses is created. The most
53  * important step is to load the configured solver using configuration
54  * "[ats]:MODE". Current solvers are MODE_SIMPLISTIC, MODE_MLP. Interaction
55  * is done using a solver API
56  *
57  * - Solver API
58  *
59  * Solver functions:
60  * s_init: init the solver with required information
61  * s_add: add a new address
62  * s_update: update ATS values or session for an address
63  * s_get: get prefered address for a peer
64  * s_del: delete an address
65  * s_pref: change preference value for a peer
66  * s_done: shutdown solver
67  * Callbacks:
68  * addresses provides a bandwidth_changed_cb callback to the solver which is
69  * called when bandwidth assigned to peer has changed
70  *
71  * - Shutdown
72  * During shutdown all addresses are freed and the solver told to shutdown
73  *
74  * - Address management:
75  * Transport service notifies ATS about changes to the addresses known to him.
76  *
77  * -- Addresses and sessions
78  * Addresses consist of the address itself and a numerical session.
79  * When a new address without a session is added it has no session, so it gets
80  * session 0 assigned. When an address with a session is added and an address
81  * object with session 0 is found, this object is updated with the
82  * session otherwise a new address object with this session assigned is created.
83  *
84  * Terminology:
85  * Addresses a1,a2 with session s1, s2 are "exact" if:
86  *  (a1 == a2) && (s1 == s2)
87  * Addresses a1,a2 with session s1, s2 are "equivalent" if:
88  *  (a1 == a2) && ((s1 == s2) || (s1 == 0) || (s2 ==0)
89  *
90  * -- Adding an address:
91
92  * When transport learns a new address it tells ATS and ATS is telling addresses
93  * about it using GAS_address_add. If not known to addresses it creates a new
94  * address object and calls solver's s_add. ATS information are deserialized
95  * and solver is notified about the session and ATS information using s_update.
96  *
97  * -- Updating an address
98  * Addresses does an lookup up for the existing address with the given session.
99  * If disassembles included ATS information and notifies the solver using
100  * s_update about the update.
101  *
102  * -- Deleting an address
103  * Addresses does an lookup for the exact address and session and if removes
104  * this address. If session != 0 the session is set to 0 and the address is
105  * kept. If session == 0, the addresses is removed.
106  *
107  * -- Requesting an address suggestion
108  * The address client issues a request address message to be notified about
109  * address suggestions for a specific peer. Addresses asks the solver with s_get.
110  * If no address is available, it will not send a response, otherwise it will
111  * respond with the choosen address.
112  *
113  * -- Address suggestions
114  * Addresses will notify the client automatically on any bandwidth_changed_cb
115  * by the solver if a address suggestion request is pending. If no address is
116  * available it will not respond at all If the client is not interested anymore,
117  * it has to cancel the address suggestion request.
118  *
119  * -- Suggestions blocks and reset
120  * After suggesting an address it is blocked for ATS_BLOCKING_DELTA sec. to
121  * prevent the client from being thrashed. If the client requires immediately
122  * it can reset this block using GAS_addresses_handle_backoff_reset.
123  *
124  * -- Address in use
125  * The client can notify addresses that it successfully uses an address and
126  * wants this address to be kept by calling GSA_address_in_use. Adresses
127  * will mark the address as used an notify the solver about the use.
128  *
129  * - Bandwidth assignment
130  *
131  * The addresses are used to perform resource allocation operations. ATS
132  * addresses takes care of instantiating the solver configured and notifies the
133  * respective solver about address changes and receives changes to the bandwidth
134  * assignment from the solver. The current bandwidth assignment is sent to
135  * transport. The specific solvers will be described in the specific section.
136  *
137  * Address lifecycle:
138  *
139  * - (add address)
140  * - (updated address) || (address in use)
141  * - (delete address)
142  *
143  * Adding addresses:
144  *
145  * - If you add a new address without a session, a new address with session 0
146  *   will be added or an existing address with session 0 used
147  * - If you add this address again now with a session a, the existing address
148  *   will be updated with this session
149  * - If you add this address again now with a session b, a new address object
150  *   with this session will be added
151
152  * Destroying addresses:
153  *
154  * - If you destroy an address without a session, the address itself and all
155  *   address instances with an session will be removed
156  * - If you destroy an address with a session, the session for this address
157  *   will be removed
158  *
159  * Conclusion
160  * Addresses without a session will be updated with a new session and if the
161  * the session is destroyed the session is removed and address itself still
162  * exists for suggestion
163  *
164  */
165
166
167 /**
168  * Available ressource assignment modes
169  */
170 enum ATS_Mode
171 {
172   /*
173    * Simplistic mode:
174    *
175    * Assign each peer an equal amount of bandwidth (bw)
176    *
177    * bw_per_peer = bw_total / #active addresses
178    */
179   MODE_SIMPLISTIC,
180
181   /*
182    * MLP mode:
183    *
184    * Solve ressource assignment as an optimization problem
185    * Uses an mixed integer programming solver
186    */
187   MODE_MLP
188 };
189
190 /**
191  * Pending Address suggestion requests
192  */
193 struct GAS_Addresses_Suggestion_Requests
194 {
195   /**
196    * Next in DLL
197    */
198   struct GAS_Addresses_Suggestion_Requests *next;
199
200   /**
201    * Previous in DLL
202    */
203   struct GAS_Addresses_Suggestion_Requests *prev;
204
205   /**
206    * Peer ID
207    */
208   struct GNUNET_PeerIdentity id;
209 };
210
211 /**
212  * Handle for ATS address component
213  */
214 struct GAS_Addresses_Handle
215 {
216   /**
217    *
218    */
219   struct GNUNET_STATISTICS_Handle *stat;
220
221   /**
222    * A multihashmap to store all addresses
223    */
224   struct GNUNET_CONTAINER_MultiHashMap *addresses;
225
226   /**
227    * Configure WAN quota in
228    */
229   unsigned long long wan_quota_in;
230
231   /**
232    * Configure WAN quota out
233    */
234   unsigned long long wan_quota_out;
235
236   /**
237    * Is ATS addresses running
238    */
239   int running;
240
241   /**
242    * Configured ATS solver
243    */
244   int ats_mode;
245
246   /**
247    *  Solver handle
248    */
249   void *solver;
250
251   /**
252    * Address suggestion requests DLL head
253    */
254   struct GAS_Addresses_Suggestion_Requests *r_head;
255
256   /**
257    * Address suggestion requests DLL tail
258    */
259   struct GAS_Addresses_Suggestion_Requests *r_tail;
260
261   /* Solver functions */
262
263   /**
264    * Initialize solver
265    */
266   GAS_solver_init s_init;
267
268   /**
269    * Add an address to the solver
270    */
271   GAS_solver_address_add s_add;
272
273   /**
274    * Update address in solver
275    */
276   GAS_solver_address_update s_update;
277
278   /**
279    * Get address from solver
280    */
281   GAS_solver_get_preferred_address s_get;
282
283   /**
284    * Delete address in solver
285    */
286   GAS_solver_address_delete s_del;
287
288   /**
289    * Change preference for quality in solver
290    */
291   GAS_solver_address_change_preference s_pref;
292
293   /**
294    * Shutdown solver
295    */
296   GAS_solver_done s_done;
297 };
298
299
300 static unsigned int
301 assemble_ats_information (const struct ATS_Address *aa,  struct GNUNET_ATS_Information **dest)
302 {
303   unsigned int ats_count = GNUNET_ATS_PropertyCount - 1;
304   struct GNUNET_ATS_Information *ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
305   (*dest) = ats;
306
307   ats[0].type = ntohl(GNUNET_ATS_UTILIZATION_UP);
308   ats[0].value = aa->atsp_utilization_out.value__;
309   ats[1].type = ntohl(GNUNET_ATS_UTILIZATION_DOWN);
310   ats[1].value = aa->atsp_utilization_in.value__;
311   ats[2].type = ntohl(GNUNET_ATS_NETWORK_TYPE);
312   ats[2].value = ntohl(aa->atsp_network_type);
313   ats[3].type = ntohl(GNUNET_ATS_QUALITY_NET_DELAY);
314   ats[3].value = ntohl(aa->atsp_latency.rel_value);
315   ats[4].type = ntohl(GNUNET_ATS_QUALITY_NET_DISTANCE);
316   ats[4].value = ntohl(aa->atsp_distance);
317   ats[5].type = ntohl(GNUNET_ATS_COST_WAN);
318   ats[5].value = ntohl (aa->atsp_cost_wan);
319   ats[6].type = ntohl(GNUNET_ATS_COST_LAN);
320   ats[6].value = ntohl (aa->atsp_cost_lan);
321   ats[7].type = ntohl(GNUNET_ATS_COST_WLAN);
322   ats[7].value = ntohl (aa->atsp_cost_wlan);
323   return ats_count;
324 }
325
326 static unsigned int
327 disassemble_ats_information (const struct GNUNET_ATS_Information *src,
328                              uint32_t ats_count,
329                              struct ATS_Address *dest)
330 {
331   int i;
332   int res = 0;
333   for (i = 0; i < ats_count; i++)
334     switch (ntohl (src[i].type))
335     {
336     case GNUNET_ATS_UTILIZATION_UP:
337       dest->atsp_utilization_out.value__ = src[i].value;
338       res ++;
339       break;
340     case GNUNET_ATS_UTILIZATION_DOWN:
341       dest->atsp_utilization_in.value__ = src[i].value;
342       res ++;
343       break;
344     case GNUNET_ATS_QUALITY_NET_DELAY:
345       dest->atsp_latency.rel_value = ntohl (src[i].value);
346       res ++;
347       break;
348     case GNUNET_ATS_QUALITY_NET_DISTANCE:
349       dest->atsp_distance = ntohl (src[i].value);
350       res ++;
351       break;
352     case GNUNET_ATS_COST_WAN:
353       dest->atsp_cost_wan = ntohl (src[i].value);
354       res ++;
355       break;
356     case GNUNET_ATS_COST_LAN:
357       dest->atsp_cost_lan = ntohl (src[i].value);
358       res ++;
359       break;
360     case GNUNET_ATS_COST_WLAN:
361       dest->atsp_cost_wlan = ntohl (src[i].value);
362       res ++;
363       break;
364     case GNUNET_ATS_NETWORK_TYPE:
365       dest->atsp_network_type = ntohl (src[i].value);
366       res ++;
367       break;
368     case GNUNET_ATS_ARRAY_TERMINATOR:
369       break;
370     default:
371       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
372                   "Received unsupported ATS type %u\n", ntohl (src[i].type));
373       GNUNET_break (0);
374       break;
375     }
376   return res;
377 }
378
379 /**
380  * Free the given address
381  * @param addr address to destroy
382  */
383 static void
384 free_address (struct ATS_Address *addr)
385 {
386   GNUNET_free (addr->plugin);
387   GNUNET_free (addr);
388 }
389
390 /**
391  * Create a ATS_address with the given information
392  * @param peer peer
393  * @param plugin_name plugin
394  * @param plugin_addr address
395  * @param plugin_addr_len address length
396  * @param session_id session
397  * @return the ATS_Address
398  */
399 static struct ATS_Address *
400 create_address (const struct GNUNET_PeerIdentity *peer,
401                 const char *plugin_name,
402                 const void *plugin_addr, size_t plugin_addr_len,
403                 uint32_t session_id)
404 {
405   struct ATS_Address *aa = NULL;
406
407   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
408   aa->peer = *peer;
409   aa->addr_len = plugin_addr_len;
410   aa->addr = &aa[1];
411   memcpy (&aa[1], plugin_addr, plugin_addr_len);
412   aa->plugin = GNUNET_strdup (plugin_name);
413   aa->session_id = session_id;
414   aa->active = GNUNET_NO;
415   aa->used = GNUNET_NO;
416   aa->solver_information = NULL;
417   aa->assigned_bw_in = GNUNET_BANDWIDTH_value_init(0);
418   aa->assigned_bw_out = GNUNET_BANDWIDTH_value_init(0);
419   return aa;
420 }
421
422
423 /**
424  * Destroy the given address.
425  *
426  * @param handle the address handle
427  * @param addr address to destroy
428  * @return GNUNET_YES if bandwidth allocations should be recalcualted
429  */
430 static int
431 destroy_address (struct GAS_Addresses_Handle *handle, struct ATS_Address *addr)
432 {
433   int ret;
434
435   ret = GNUNET_NO;
436   GNUNET_assert (GNUNET_YES ==
437                  GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
438                                                        &addr->peer.hashPubKey,
439                                                        addr));
440   free_address (addr);
441   return ret;
442 }
443
444
445 struct CompareAddressContext
446 {
447   const struct ATS_Address *search;
448
449   /* exact_address != NULL if address and session is equal */
450   struct ATS_Address *exact_address;
451   /* exact_address != NULL if address and session is 0 */
452   struct ATS_Address *base_address;
453 };
454
455
456 static int
457 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
458 {
459   struct CompareAddressContext *cac = cls;
460   struct ATS_Address *aa = value;
461
462   /* Find an matching exact address:
463    *
464    * Compare by:
465    * aa->addr_len == cac->search->addr_len
466    * aa->plugin == cac->search->plugin
467    * aa->addr == cac->search->addr
468    * aa->session == cac->search->session
469    *
470    * return as exact address
471    */
472   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
473   {
474       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
475         cac->exact_address = aa;
476   }
477
478   /* Find an matching base address:
479    *
480    * Properties:
481    *
482    * aa->session_id == 0
483    *
484    * Compare by:
485    * aa->addr_len == cac->search->addr_len
486    * aa->plugin == cac->search->plugin
487    * aa->addr == cac->search->addr
488    *
489    * return as base address
490    */
491   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
492   {
493       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == 0))
494         cac->base_address = aa;
495   }
496
497   /* Find an matching exact address based on session:
498    *
499    * Properties:
500    *
501    * cac->search->addr_len == 0
502    *
503    * Compare by:
504    * aa->plugin == cac->search->plugin
505    * aa->session_id == cac->search->session_id
506    *
507    * return as exact address
508    */
509   if (0 == cac->search->addr_len)
510   {
511       if ((0 == strcmp (aa->plugin, cac->search->plugin)) && (aa->session_id == cac->search->session_id))
512         cac->exact_address = aa;
513   }
514
515   if (cac->exact_address == NULL)
516     return GNUNET_YES; /* Continue iteration to find exact address */
517   else
518     return GNUNET_NO; /* Stop iteration since we have an exact address */
519 }
520
521
522 /**
523  * Find an existing equivalent address record.
524  * Compares by peer identity and network address OR by session ID
525  * (one of the two must match).
526  *
527  * @param handle the address handle
528  * @param peer peer to lookup addresses for
529  * @param addr existing address record
530  * @return existing address record, NULL for none
531  */
532 struct ATS_Address *
533 find_equivalent_address (struct GAS_Addresses_Handle *handle,
534                          const struct GNUNET_PeerIdentity *peer,
535                          const struct ATS_Address *addr)
536 {
537   struct CompareAddressContext cac;
538
539   cac.exact_address = NULL;
540   cac.base_address = NULL;
541   cac.search = addr;
542   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
543                                               &compare_address_it, &cac);
544
545   if (cac.exact_address == NULL)
546     return cac.base_address;
547   return cac.exact_address;
548 }
549
550
551 static struct ATS_Address *
552 lookup_address (struct GAS_Addresses_Handle *handle,
553                 const struct GNUNET_PeerIdentity *peer,
554                 const char *plugin_name,
555                 const void *plugin_addr,
556                 size_t plugin_addr_len,
557                 uint32_t session_id,
558                 const struct GNUNET_ATS_Information *atsi,
559                 uint32_t atsi_count)
560 {
561   struct ATS_Address *aa;
562   struct ATS_Address *ea;
563
564   aa = create_address (peer,
565                        plugin_name,
566                        plugin_addr, plugin_addr_len,
567                        session_id);
568
569   /* Get existing address or address with session == 0 */
570   ea = find_equivalent_address (handle, peer, aa);
571   free_address (aa);
572   if (ea == NULL)
573   {
574     return NULL;
575   }
576   else if (ea->session_id != session_id)
577   {
578     return NULL;
579   }
580   return ea;
581 }
582
583
584 void
585 GAS_addresses_add (struct GAS_Addresses_Handle *handle,
586                    const struct GNUNET_PeerIdentity *peer,
587                    const char *plugin_name, const void *plugin_addr,
588                    size_t plugin_addr_len, uint32_t session_id,
589                    const struct GNUNET_ATS_Information *atsi,
590                    uint32_t atsi_count)
591 {
592   struct ATS_Address *aa;
593   struct ATS_Address *ea;
594   unsigned int ats_res;
595
596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
597               "Received `%s' for peer `%s'\n",
598               "ADDRESS ADD",
599               GNUNET_i2s (peer));
600
601   if (GNUNET_NO == handle->running)
602     return;
603
604   GNUNET_assert (NULL != handle->addresses);
605
606   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len,
607                        session_id);
608   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, aa)))
609   {
610       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611                 "While adding address: had %u ATS elements to add, could only add %u\n",
612                 atsi_count, ats_res);
613   }
614
615   /* Get existing address or address with session == 0 */
616   ea = find_equivalent_address (handle, peer, aa);
617   if (ea == NULL)
618   {
619     /* We have a new address */
620     GNUNET_assert (GNUNET_OK ==
621                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
622                                                       &peer->hashPubKey, aa,
623                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
624     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
625                 GNUNET_i2s (peer), session_id, aa);
626     /* Tell solver about new address */
627     handle->s_add (handle->solver, handle->addresses, aa);
628     return;
629   }
630   GNUNET_free (aa->plugin);
631   GNUNET_free (aa);
632
633   if (ea->session_id != 0)
634   {
635       /* This address with the same session is already existing
636        * Should not happen */
637       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
638                 "Added already existing address for peer `%s' `%s' %p with new session %u\n",
639                 GNUNET_i2s (peer), plugin_name, session_id);
640       GNUNET_break (0);
641       return;
642   }
643
644   /* We have an address without an session, update this address */
645
646   /* Notify solver about update with atsi information and session */
647   handle->s_update (handle->solver, handle->addresses, ea, session_id, ea->used, atsi, atsi_count);
648
649   /* Do the update */
650   ea->session_id = session_id;
651   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, ea)))
652   {
653       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
654                   "While updating address: had %u ATS elements to add, could only add %u\n",
655                   atsi_count, ats_res);
656   }
657   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
658            "Updated existing address for peer `%s' %p with new session %u\n",
659            GNUNET_i2s (peer), ea, session_id);
660 }
661
662
663 void
664 GAS_addresses_update (struct GAS_Addresses_Handle *handle,
665                       const struct GNUNET_PeerIdentity *peer,
666                       const char *plugin_name, const void *plugin_addr,
667                       size_t plugin_addr_len, uint32_t session_id,
668                       const struct GNUNET_ATS_Information *atsi,
669                       uint32_t atsi_count)
670 {
671   struct ATS_Address *aa;
672   uint32_t ats_res;
673
674   if (GNUNET_NO == handle->running)
675     return;
676
677   GNUNET_assert (NULL != handle->addresses);
678
679   /* Get existing address */
680   aa = lookup_address (handle, peer, plugin_name, plugin_addr, plugin_addr_len,
681                        session_id, atsi, atsi_count);
682   if (aa == NULL)
683   {
684     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
685                 GNUNET_i2s (peer), plugin_name, session_id);
686     GNUNET_break (0);
687     return;
688   }
689
690   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691                 "Received `%s' for peer `%s' address \n",
692                 "ADDRESS UPDATE",
693                 GNUNET_i2s (peer), aa);
694
695   /* Tell solver about update */
696   handle->s_update (handle->solver, handle->addresses, aa, session_id, aa->used, atsi, atsi_count);
697
698   /* Update address */
699   if (atsi_count != (ats_res = disassemble_ats_information (atsi, atsi_count, aa)))
700   {
701       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
702                 "While adding address: had %u ATS elements to add, could only add %u\n",
703                 atsi_count, ats_res);
704   }
705   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
706             "Updated %u ATS elements for address %p\n",
707             ats_res, aa);
708 }
709
710
711 struct DestroyContext
712 {
713   struct ATS_Address *aa;
714
715   struct GAS_Addresses_Handle *handle;
716
717   /**
718    * GNUNET_NO  : full address
719    * GNUNET_YES : just session
720    */
721   int result;
722 };
723
724
725 /**
726  * Delete an address
727  *
728  * If session != 0, just the session is deleted, the address itself still exists
729  * If session == 0, remove full address
730  * If session == 0 and addrlen == 0, destroy inbound address
731  *
732  * @param cls unused
733  * @param key unused
734  * @param value the 'struct ATS_Address'
735  * @return GNUNET_OK (continue to iterate)
736  */
737 static int
738 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
739 {
740   struct DestroyContext *dc = cls;
741   struct GAS_Addresses_Handle *handle = dc->handle;
742   const struct ATS_Address *des = dc->aa;
743   struct ATS_Address *aa = value;
744
745   GNUNET_assert (0 == memcmp (&aa->peer, &des->peer,
746                               sizeof (struct GNUNET_PeerIdentity)));
747
748
749   if (des->session_id == 0)
750   {
751     /* Session == 0, remove full address  */
752     if ((0 == strcmp (des->plugin, aa->plugin)) &&
753         (aa->addr_len == des->addr_len) &&
754         (0 == memcmp (des->addr, aa->addr, aa->addr_len)))
755     {
756
757       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
758                   "Deleting full address for peer `%s' session %u %p\n",
759                   GNUNET_i2s (&aa->peer), aa->session_id, aa);
760
761       /* Notify solver about deletion */
762       handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
763       destroy_address (handle, aa);
764       dc->result = GNUNET_NO;
765       return GNUNET_OK; /* Continue iteration */
766     }
767   }
768   else
769   {
770     /* Session != 0, just remove session */
771     if (aa->session_id != des->session_id)
772       return GNUNET_OK; /* irrelevant */
773
774     if ((aa->session_id != 0) &&
775         (0 != strcmp (des->plugin, aa->plugin)))
776     {
777         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
778                     "Different plugins during removal: `%s' vs `%s' \n",
779                     des->plugin, aa->plugin);
780         GNUNET_break (0);
781         return GNUNET_OK;
782     }
783
784     if (aa->addr_len == 0)
785     {
786         /* Inbound connection died, delete full address */
787         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
788                     "Deleting inbound address for peer `%s': `%s' session %u\n",
789                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
790
791         /* Notify solver about deletion */
792         handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
793         destroy_address (handle, aa);
794         dc->result = GNUNET_NO;
795         return GNUNET_OK; /* Continue iteration */
796     }
797     else
798     {
799         /* Session died */
800         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801                     "Deleting session for peer `%s': `%s' %u\n",
802                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
803         /* Notify solver to delete session */
804         handle->s_del (handle->solver, handle->addresses, aa, GNUNET_YES);
805         aa->session_id = 0;
806         return GNUNET_OK;
807     }
808   }
809   return GNUNET_OK;
810 }
811
812 void
813 GAS_addresses_destroy (struct GAS_Addresses_Handle *handle,
814                        const struct GNUNET_PeerIdentity *peer,
815                        const char *plugin_name, const void *plugin_addr,
816                        size_t plugin_addr_len, uint32_t session_id)
817 {
818   struct ATS_Address *ea;
819   struct DestroyContext dc;
820
821   if (GNUNET_NO == handle->running)
822     return;
823
824   /* Get existing address */
825   ea = lookup_address (handle, peer, plugin_name, plugin_addr, plugin_addr_len,
826                        session_id, NULL, 0);
827
828   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
829               "Received `%s' for peer `%s' address %p session %u\n",
830               "ADDRESS DESTROY",
831               GNUNET_i2s (peer), ea, session_id);
832
833   if (ea == NULL)
834   {
835     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
836                 GNUNET_i2s (peer), plugin_name, session_id);
837     return;
838   }
839
840   GNUNET_break (0 < strlen (plugin_name));
841   dc.handle = handle;
842   dc.aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
843
844   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
845                                               &destroy_by_session_id, &dc);
846   free_address (dc.aa);
847 }
848
849
850 int
851 GAS_addresses_in_use (struct GAS_Addresses_Handle *handle,
852                       const struct GNUNET_PeerIdentity *peer,
853                       const char *plugin_name, const void *plugin_addr,
854                       size_t plugin_addr_len, uint32_t session_id, int in_use)
855 {
856   struct ATS_Address *ea;
857
858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859                 "Received `%s' for peer `%s'\n",
860                 "ADDRESS IN USE",
861                 GNUNET_i2s (peer));
862
863   if (GNUNET_NO == handle->running)
864     return GNUNET_SYSERR;
865
866   ea = lookup_address (handle, peer, plugin_name,
867                         plugin_addr, plugin_addr_len,
868                         session_id, NULL, 0);
869   if (NULL == ea)
870   {
871     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
872                 "Trying to set unknown address `%s', %s %u %s \n",
873                 GNUNET_i2s (peer),
874                 plugin_name, session_id,
875                 (GNUNET_NO == in_use) ? "NO" : "YES");
876     GNUNET_break (0);
877     return GNUNET_SYSERR;
878   }
879   if (ea->used == in_use)
880   {
881     GNUNET_break (0);
882     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
883                 "Address in use called multiple times for peer `%s': %s -> %s \n",
884                 GNUNET_i2s (peer),
885                 (GNUNET_NO == ea->used) ? "NO" : "YES",
886                 (GNUNET_NO == in_use) ? "NO" : "YES");
887     return GNUNET_SYSERR;
888   }
889
890   /* Tell solver about update */
891   handle->s_update (handle->solver, handle->addresses, ea, session_id, in_use, NULL, 0);
892   ea->used = in_use;
893
894   return GNUNET_OK;
895 }
896
897
898 /**
899  * Cancel address suggestions for a peer
900  *
901  * @param handle the address handle
902  * @param peer the respective peer
903  */
904 void
905 GAS_addresses_request_address_cancel (struct GAS_Addresses_Handle *handle,
906                                       const struct GNUNET_PeerIdentity *peer)
907 {
908   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
909
910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
911               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
912
913   while (NULL != cur)
914   {
915       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
916         break; /* found */
917       cur = cur->next;
918   }
919
920   if (NULL == cur)
921   {
922       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
923                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
924       return;
925   }
926   GAS_addresses_handle_backoff_reset (handle, peer);
927   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
928               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
929   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
930   GNUNET_free (cur);
931 }
932
933
934 /**
935  * Add an address suggestions for a peer
936  *
937  * @param handle the address handle
938  * @param peer the respective peer
939  */
940 void
941 GAS_addresses_request_address (struct GAS_Addresses_Handle *handle,
942                                const struct GNUNET_PeerIdentity *peer)
943 {
944   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
945   struct ATS_Address *aa;
946   struct GNUNET_ATS_Information *ats;
947   unsigned int ats_count;
948
949   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950               "Received `%s' for peer `%s'\n",
951               "REQUEST ADDRESS",
952               GNUNET_i2s (peer));
953
954   if (GNUNET_NO == handle->running)
955     return;
956   while (NULL != cur)
957   {
958       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
959         break; /* already suggesting */
960       cur = cur->next;
961   }
962   if (NULL == cur)
963   {
964       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
965       cur->id = (*peer);
966       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
967   }
968
969   /* Get prefered address from solver */
970   aa = (struct ATS_Address *) handle->s_get (handle->solver, handle->addresses, peer);
971   if (NULL == aa)
972   {
973     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
974                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
975     return;
976   }
977
978   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
979               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
980
981   ats_count = assemble_ats_information (aa, &ats);
982   GAS_scheduling_transmit_address_suggestion (peer,
983                                               aa->plugin,
984                                               aa->addr, aa->addr_len,
985                                               aa->session_id,
986                                               ats, ats_count,
987                                               aa->assigned_bw_out,
988                                               aa->assigned_bw_in);
989
990   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
991   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), aa->block_interval);
992
993   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
994        "Address %p ready for suggestion, block interval now %llu \n",
995        aa, aa->block_interval);
996
997   GNUNET_free (ats);
998 }
999
1000
1001 static int
1002 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1003 {
1004   struct ATS_Address *aa = value;
1005
1006   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007               "Resetting interval for peer `%s' address %p from %llu to 0\n",
1008               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
1009
1010   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
1011   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
1012   return GNUNET_OK;
1013 }
1014
1015
1016 void
1017 GAS_addresses_handle_backoff_reset (struct GAS_Addresses_Handle *handle,
1018                                     const struct GNUNET_PeerIdentity *peer)
1019 {
1020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1021               "Received `%s' for peer `%s'\n",
1022               "RESET BACKOFF",
1023               GNUNET_i2s (peer));
1024
1025   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
1026                                               &peer->hashPubKey,
1027                                               &reset_address_it,
1028                                               NULL));
1029 }
1030
1031
1032 void
1033 GAS_addresses_change_preference (struct GAS_Addresses_Handle *handle,
1034                                  void *client,
1035                                  const struct GNUNET_PeerIdentity *peer,
1036                                  enum GNUNET_ATS_PreferenceKind kind,
1037                                  float score)
1038 {
1039   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1040               "Received `%s' for peer `%s' for client %p\n",
1041               "CHANGE PREFERENCE",
1042               GNUNET_i2s (peer), client);
1043
1044   if (GNUNET_NO == handle->running)
1045     return;
1046
1047   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->addresses,
1048                                                           &peer->hashPubKey))
1049   {
1050       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1051                   "Received `%s' for unknown peer `%s' from client %p\n",
1052                   "CHANGE PREFERENCE",
1053                   GNUNET_i2s (peer), client);
1054       return;
1055   }
1056
1057   /* Tell solver about update */
1058   handle->s_pref (handle->solver, client, peer, kind, score);
1059 }
1060
1061
1062 /**
1063  * Load quotas for networks from configuration
1064  *
1065  * @param cfg configuration handle
1066  * @param out_dest where to write outbound quotas
1067  * @param in_dest where to write inbound quotas
1068  * @param dest_length length of inbound and outbound arrays
1069  * @return number of networks loaded
1070  */
1071 static unsigned int
1072 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
1073 {
1074   char *network_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1075   char * entry_in = NULL;
1076   char * entry_out = NULL;
1077   char * quota_out_str;
1078   char * quota_in_str;
1079   int c;
1080   int res;
1081
1082   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
1083   {
1084     in_dest[c] = 0;
1085     out_dest[c] = 0;
1086     GNUNET_asprintf (&entry_out, "%s_QUOTA_OUT", network_str[c]);
1087     GNUNET_asprintf (&entry_in, "%s_QUOTA_IN", network_str[c]);
1088
1089     /* quota out */
1090     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
1091     {
1092       res = GNUNET_NO;
1093       if (0 == strcmp(quota_out_str, BIG_M_STRING))
1094       {
1095         out_dest[c] = GNUNET_ATS_MaxBandwidth;
1096         res = GNUNET_YES;
1097       }
1098       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
1099         res = GNUNET_YES;
1100       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_out,  &out_dest[c])))
1101          res = GNUNET_YES;
1102
1103       if (GNUNET_NO == res)
1104       {
1105           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1106               network_str[c], quota_out_str, GNUNET_ATS_DefaultBandwidth);
1107           out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1108       }
1109       else
1110       {
1111           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Outbound quota configure for network `%s' is %llu\n"),
1112               network_str[c], out_dest[c]);
1113       }
1114       GNUNET_free (quota_out_str);
1115     }
1116     else
1117     {
1118       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"),
1119           network_str[c], GNUNET_ATS_DefaultBandwidth);
1120       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1121     }
1122
1123     /* quota in */
1124     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
1125     {
1126       res = GNUNET_NO;
1127       if (0 == strcmp(quota_in_str, BIG_M_STRING))
1128       {
1129         in_dest[c] = GNUNET_ATS_MaxBandwidth;
1130         res = GNUNET_YES;
1131       }
1132       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
1133         res = GNUNET_YES;
1134       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_in,  &in_dest[c])))
1135          res = GNUNET_YES;
1136
1137       if (GNUNET_NO == res)
1138       {
1139           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1140               network_str[c], quota_in_str, GNUNET_ATS_DefaultBandwidth);
1141           in_dest[c] = GNUNET_ATS_DefaultBandwidth;
1142       }
1143       else
1144       {
1145           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Inbound quota configured for network `%s' is %llu\n"),
1146               network_str[c], in_dest[c]);
1147       }
1148       GNUNET_free (quota_in_str);
1149     }
1150     else
1151     {
1152       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"),
1153           network_str[c], GNUNET_ATS_DefaultBandwidth);
1154       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1155     }
1156     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded quota for network `%s' (in/out): %llu %llu\n", network_str[c], in_dest[c], out_dest[c]);
1157     GNUNET_free (entry_out);
1158     GNUNET_free (entry_in);
1159   }
1160   return GNUNET_ATS_NetworkTypeCount;
1161 }
1162
1163
1164 static void
1165 bandwidth_changed_cb (void *cls, struct ATS_Address *address)
1166 {
1167   struct GAS_Addresses_Handle *handle = cls;
1168   struct GAS_Addresses_Suggestion_Requests *cur;
1169
1170   GNUNET_assert (handle != NULL);
1171   GNUNET_assert (address != NULL);
1172
1173   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bandwidth assignment changed for peer %s \n", GNUNET_i2s(&address->peer));
1174   struct GNUNET_ATS_Information *ats;
1175   unsigned int ats_count;
1176
1177   cur = handle->r_head;
1178   while (NULL != cur)
1179   {
1180       if (0 == memcmp (&address->peer, &cur->id, sizeof (cur->id)))
1181         break; /* we have an address request pending*/
1182       cur = cur->next;
1183   }
1184   if (NULL == cur)
1185   {
1186       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1187                   "Nobody is interested in peer `%s' :(\n",GNUNET_i2s (&address->peer));
1188       return;
1189   }
1190
1191   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1192               "Sending bandwidth update for peer `%s'\n",GNUNET_i2s (&address->peer));
1193
1194   ats_count = assemble_ats_information (address, &ats);
1195   GAS_scheduling_transmit_address_suggestion (&address->peer,
1196                                               address->plugin,
1197                                               address->addr, address->addr_len,
1198                                               address->session_id,
1199                                               ats, ats_count,
1200                                               address->assigned_bw_out,
1201                                               address->assigned_bw_in);
1202   GNUNET_free (ats);
1203 }
1204
1205
1206 /**
1207  * Initialize address subsystem.
1208  *
1209  * @param cfg configuration to use
1210  * @param stats the statistics handle to use
1211  */
1212 struct GAS_Addresses_Handle *
1213 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1214                     const struct GNUNET_STATISTICS_Handle *stats)
1215 {
1216   struct GAS_Addresses_Handle *ah;
1217   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1218   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
1219   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
1220   int quota_count;
1221   char *mode_str;
1222   int c;
1223
1224   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
1225   ah->running = GNUNET_NO;
1226
1227   ah->stat = (struct GNUNET_STATISTICS_Handle *) stats;
1228   /* Initialize the addresses database */
1229   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1230   GNUNET_assert (NULL != ah->addresses);
1231
1232   /* Figure out configured solution method */
1233   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1234   {
1235       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No ressource assignment method configured, using simplistic approch\n");
1236       ah->ats_mode = MODE_SIMPLISTIC;
1237   }
1238   else
1239   {
1240       for (c = 0; c < strlen (mode_str); c++)
1241         mode_str[c] = toupper (mode_str[c]);
1242       if (0 == strcmp (mode_str, "SIMPLISTIC"))
1243       {
1244           ah->ats_mode = MODE_SIMPLISTIC;
1245       }
1246       else if (0 == strcmp (mode_str, "MLP"))
1247       {
1248           ah->ats_mode = MODE_MLP;
1249 #if !HAVE_LIBGLPK
1250           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not availabe, please install \n", mode_str);
1251           ah->ats_mode = MODE_SIMPLISTIC;
1252 #endif
1253       }
1254       else
1255       {
1256           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid ressource assignment method `%s' configured, using simplistic approch\n", mode_str);
1257           ah->ats_mode = MODE_SIMPLISTIC;
1258       }
1259       GNUNET_free (mode_str);
1260   }
1261   /* Start configured solution method */
1262   switch (ah->ats_mode)
1263   {
1264     case MODE_MLP:
1265       /* Init the MLP solver with default values */
1266 #if HAVE_LIBGLPK
1267       ah->ats_mode = MODE_MLP;
1268       ah->s_init = &GAS_mlp_init;
1269       ah->s_add = &GAS_mlp_address_add;
1270       ah->s_update = &GAS_mlp_address_update;
1271       ah->s_get = &GAS_mlp_get_preferred_address;
1272       ah->s_pref = &GAS_mlp_address_change_preference;
1273       ah->s_del =  &GAS_mlp_address_delete;
1274       ah->s_done = &GAS_mlp_done;
1275 #else
1276       GNUNET_free (ah);
1277       return NULL;
1278 #endif
1279       break;
1280     case MODE_SIMPLISTIC:
1281       /* Init the simplistic solver with default values */
1282       ah->ats_mode = MODE_SIMPLISTIC;
1283       ah->s_init = &GAS_simplistic_init;
1284       ah->s_add = &GAS_simplistic_address_add;
1285       ah->s_update = &GAS_simplistic_address_update;
1286       ah->s_get = &GAS_simplistic_get_preferred_address;
1287       ah->s_pref = &GAS_simplistic_address_change_preference;
1288       ah->s_del  = &GAS_simplistic_address_delete;
1289       ah->s_done = &GAS_simplistic_done;
1290       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "SIMPLISTIC");
1291       break;
1292     default:
1293       return NULL;
1294       break;
1295   }
1296
1297   GNUNET_assert (NULL != ah->s_init);
1298   GNUNET_assert (NULL != ah->s_add);
1299   GNUNET_assert (NULL != ah->s_update);
1300   GNUNET_assert (NULL != ah->s_get);
1301   GNUNET_assert (NULL != ah->s_pref);
1302   GNUNET_assert (NULL != ah->s_del);
1303   GNUNET_assert (NULL != ah->s_done);
1304
1305   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1306
1307   ah->solver = ah->s_init (cfg, stats, quotas, quotas_in, quotas_out, quota_count, &bandwidth_changed_cb, ah);
1308   if (NULL == ah->solver)
1309   {
1310     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to initialize solver!\n");
1311     GNUNET_free (ah);
1312     return NULL;
1313   }
1314
1315   /* up and running */
1316   ah->running = GNUNET_YES;
1317   return ah;
1318 }
1319
1320
1321 /**
1322  * Free memory of address.
1323  *
1324  * @param cls NULL
1325  * @param key peer identity (unused)
1326  * @param value the 'struct ATS_Address' to free
1327  * @return GNUNET_OK (continue to iterate)
1328  */
1329 static int
1330 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1331 {
1332   struct GAS_Addresses_Handle *handle = cls;
1333   struct ATS_Address *aa = value;
1334   handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
1335   destroy_address (handle, aa);
1336   return GNUNET_OK;
1337 }
1338
1339
1340 void
1341 GAS_addresses_destroy_all (struct GAS_Addresses_Handle *handle)
1342 {
1343   if (GNUNET_NO == handle->running)
1344     return;
1345
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1347               "Received `%s'\n",
1348               "DESTROY ALL");
1349
1350   if (handle->addresses != NULL)
1351     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &free_address_it, handle);
1352 }
1353
1354
1355 /**
1356  * Shutdown address subsystem.
1357  */
1358 void
1359 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1360 {
1361   struct GAS_Addresses_Suggestion_Requests *cur;
1362
1363   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1364               "Shutting down addresses\n");
1365   GNUNET_assert (NULL != handle);
1366   GAS_addresses_destroy_all (handle);
1367   handle->running = GNUNET_NO;
1368   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1369   handle->addresses = NULL;
1370   while (NULL != (cur = handle->r_head))
1371   {
1372       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1373       GNUNET_free (cur);
1374   }
1375   handle->s_done (handle->solver);
1376   GNUNET_free (handle);
1377   /* Stop configured solution method */
1378
1379 }
1380
1381 struct PeerIteratorContext
1382 {
1383   GNUNET_ATS_Peer_Iterator it;
1384   void *it_cls;
1385   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1386 };
1387
1388 static int
1389 peer_it (void *cls,
1390          const struct GNUNET_HashCode * key,
1391          void *value)
1392 {
1393   struct PeerIteratorContext *ip_ctx = cls;
1394   struct GNUNET_PeerIdentity tmp;
1395
1396   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1397   {
1398       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1399       tmp.hashPubKey = (*key);
1400       ip_ctx->it (ip_ctx->it_cls, &tmp);
1401   }
1402
1403   return GNUNET_OK;
1404 }
1405
1406 /**
1407  * Return all peers currently known to ATS
1408  *
1409  * @param handle the address handle
1410  * @param p_it the iterator to call for every peer, callbach with id == NULL
1411  *        when done
1412  * @param p_it_cls the closure for the iterator
1413  */
1414 void
1415 GAS_addresses_iterate_peers (struct GAS_Addresses_Handle *handle, GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1416 {
1417   struct PeerIteratorContext ip_ctx;
1418   unsigned int size;
1419
1420   if (NULL == p_it)
1421       return;
1422   GNUNET_assert (NULL != handle->addresses);
1423
1424   size = GNUNET_CONTAINER_multihashmap_size(handle->addresses);
1425   if (0 != size)
1426   {
1427     ip_ctx.it = p_it;
1428     ip_ctx.it_cls = p_it_cls;
1429     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1430     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &peer_it, &ip_ctx);
1431     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1432   }
1433   p_it (p_it_cls, NULL);
1434 }
1435
1436 struct PeerInfoIteratorContext
1437 {
1438   GNUNET_ATS_PeerInfo_Iterator it;
1439   void *it_cls;
1440 };
1441
1442
1443 static int 
1444 peerinfo_it (void *cls,
1445              const struct GNUNET_HashCode * key,
1446              void *value)
1447 {
1448   struct PeerInfoIteratorContext *pi_ctx = cls;
1449   struct ATS_Address *addr = (struct ATS_Address *)  value;
1450   struct GNUNET_ATS_Information *ats;
1451   uint32_t ats_count;
1452
1453   if (NULL != pi_ctx->it)
1454   {
1455     ats_count = assemble_ats_information (addr, &ats);
1456
1457     pi_ctx->it (pi_ctx->it_cls,
1458                 &addr->peer,
1459                 addr->plugin,
1460                 addr->addr, addr->addr_len,
1461                 addr->active,
1462                 ats, ats_count,
1463                 addr->assigned_bw_out,
1464                 addr->assigned_bw_in);
1465     GNUNET_free (ats);
1466   }
1467   return GNUNET_YES;
1468 }
1469
1470
1471 /**
1472  * Return all peers currently known to ATS
1473  *
1474  * @param handle the address handle
1475  * @param peer the respective peer
1476  * @param pi_it the iterator to call for every peer
1477  * @param pi_it_cls the closure for the iterator
1478  */
1479 void
1480 GAS_addresses_get_peer_info (struct GAS_Addresses_Handle *handle,
1481                              const struct GNUNET_PeerIdentity *peer,
1482                              GNUNET_ATS_PeerInfo_Iterator pi_it,
1483                              void *pi_it_cls)
1484 {
1485   struct PeerInfoIteratorContext pi_ctx;
1486   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1487   GNUNET_assert (NULL != peer);
1488   GNUNET_assert (NULL != handle->addresses);
1489   if (NULL == pi_it)
1490     return; /* does not make sense without callback */
1491
1492   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1493   pi_ctx.it = pi_it;
1494   pi_ctx.it_cls = pi_it_cls;
1495
1496   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1497
1498   if (NULL != pi_it)
1499     pi_it (pi_it_cls, NULL, NULL, NULL, 0, GNUNET_NO, NULL, 0, zero_bw, zero_bw);
1500
1501 }
1502
1503
1504 /* end of gnunet-service-ats_addresses.c */