d89c9af0d159f203e2e4d6c50cde4cbf05a9f72c
[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_ats_plugin.h"
30 #include "gnunet-service-ats.h"
31 #include "gnunet-service-ats_addresses.h"
32 #include "gnunet-service-ats_normalization.h"
33 #include "gnunet-service-ats_performance.h"
34 #include "gnunet-service-ats_scheduling.h"
35 #include "gnunet-service-ats_reservations.h"
36
37
38 /**
39  * NOTE: Do not change this documentation. This documentation is based on
40  * gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
41  * use build_txt.sh to generate plaintext output
42  *
43  *   1 ATS addresses : ATS address management
44  *
45  *    This ATS addresses ("addresses") component manages the addresses known to
46  *    ATS service and suggests addresses to transport service when it is
47  *    interested in address suggestion for a peer. ATS addresses also
48  *    instantiates the bandwidth assignment mechanism (solver), notifies it
49  *    about changes to addresses and forwards changes to bandwidth assignments
50  *    to transport, depending if transport is interested in this change.
51  *
52  *     1.1 Input data
53  *
54  *       1.1.1 Addresses
55  *
56  *    Addresses are added by specifying peer ID, plugin, address, address length
57  *    and session, if available. ATS information can be specified if available.
58  *
59  *       1.1.2 Networks
60  *
61  *    ATS specifies a fix set of networks an address can belong to. For each
62  *    network an inbound and outbound quota will be specified. The available
63  *    networks and addtional helper varaibles are defined in
64  *    gnunet_ats_service.h. At the moment 5 networks are defined:
65  *      * GNUNET_ATS_NET_UNSPECIFIED
66  *      * GNUNET_ATS_NET_LOOPBACK
67  *      * GNUNET_ATS_NET_LAN
68  *      * GNUNET_ATS_NET_WAN
69  *      * GNUNET_ATS_NET_WLAN
70  *
71  *    The total number of networks defined is stored in
72  *    GNUNET_ATS_NetworkTypeCount GNUNET_ATS_NetworkType can be used array
73  *    initializer for an int array, while GNUNET_ATS_NetworkType is an
74  *    initializer for a char array containing a string description of all
75  *    networks
76  *
77  *       1.1.3 Quotas
78  *
79  *    An inbound and outbound quota for each of the networks mentioned in 1.1.2
80  *    is loaded from ats configuration during initialization. This quota defines
81  *    to total amount of inbound and outbound traffic allowed for a specific
82  *    network. The configuration values used are in section ats:
83  *      * "NETWORK"_QUOTA_IN = <value>
84  *      * "NETWORK"_QUOTA_IN = <value>
85  *
86  *    You can specify quotas by setting the <value> to a:
87  *      * unrestricted: unlimited
88  *      * number of bytes: e.g. 10240
89  *      * fancy value: e.g. 64 Kib
90  *
91  *    unlimited is defined as GNUNET_ATS_MaxBandwidthString and equivalent to
92  *    the value GNUNET_ATS_MaxBandwidth Important predefined values for quotas
93  *    are:
94  *      * GNUNET_ATS_DefaultBandwidth: 65536
95  *      * GNUNET_ATS_MaxBandwidth: UINT32_MAX
96  *      * GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT: 1024
97  *
98  *    Details of loading quotas and default values will be described on
99  *
100  *       1.1.4 Preference values
101  *
102  *     1.2 Data structures used
103  *
104  *    Addresse uses struct ATS_Address for each address. The structs are stored
105  *    in a linked list and provides a pointer void *solver_information for the
106  *    solver to store address specific information. It provides the int values
107  *    active which is set to GNUNET_YES if the address is select for transport
108  *    use and used, representing that transport service is actively using this
109  *    address. Address information are stored in peer, addr, addr_len, plugin.
110  *
111  *     1.3 Initialization
112  *
113  *    During initialization a hashmap to store addresses is created. The quotas
114  *    for all networks defined for ATS are loaded from configuration. For each
115  *    network first the logic will check if the string
116  *    GNUNET_ATS_MaxBandwidthString is configured, if not it will try to convert
117  *    the configured value as a fancy size and if this fails it will try to use
118  *    it as a value_number. If no configuration value is found it will assign
119  *    GNUNET_ATS_DefaultBandwidth. The most important step is to load the
120  *    configured solver using configuration "[ats]:MODE". Current solvers are
121  *    MODE_PROPORTIONAL, MODE_MLP. Interaction is done using a solver API
122  *
123  *     1.4 Solver API
124  *
125  *    Solver functions:
126  *      * s_init: init the solver with required information
127  *      * s_add: add a new address
128  *      * s_update: update ATS values or session for an address
129  *      * s_get: get prefered address for a peer
130  *      * s_del: delete an address
131  *      * s_pref: change preference value for a peer
132  *      * s_done: shutdown solver
133  *
134  *    Callbacks: addresses provides a bandwidth_changed_cb callback to the
135  *    solver which is called when bandwidth assigned to peer has changed
136  *
137  *     1.5 Shutdown
138  *
139  *    During shutdown all addresses are freed and the solver told to shutdown
140  *
141  *     1.6 Addresses and sessions
142  *
143  *    Addresses consist of the address itself and a numerical session. When a
144  *    new address without a session is added it has no session, so it gets
145  *    session 0 assigned. When an address with a session is added and an address
146  *    object with session 0 is found, this object is updated with the session
147  *    otherwise a new address object with this session assigned is created.
148  *
149  *       1.6.1 Terminology
150  *
151  *    Addresses a1,a2 with session s1, s2 are "exact" if:
152  *    (a1 == a2)&&(s1 == s2)
153  *    Addresses a1,a2 with session s1, s2 are "equivalent" if:
154  *    (a1 == a2)&&((s1 == s2)||(s1 == 0)||(s2 == 0)
155  *
156  *     1.7 Address management
157  *
158  *    Transport service notifies ATS about changes to the addresses known to
159  *    him.
160  *
161  *       1.7.1 Adding an address
162  *
163  *    When transport learns a new address it tells ATS and ATS is telling
164  *    addresses about it using GAS_address_add. If not known to addresses it
165  *    creates a new address object and calls solver's s_add. ATS information are
166  *    deserialized and solver is notified about the session and ATS information
167  *    using s_update.
168  *
169  *       1.7.2 Updating an address
170  *
171  *    Addresses does an lookup up for the existing address with the given
172  *    session. If disassembles included ATS information and notifies the solver
173  *    using s_update about the update.
174  *
175  *       1.7.3 Deleting an address
176  *
177  *    Addresses does an lookup for the exact address and session and if removes
178  *    this address. If session != 0 the session is set to 0 and the address is
179  *    kept. If session == 0, the addresses is removed.
180  *
181  *       1.7.4 Requesting an address suggestion
182  *
183  *    The address client issues a request address message to be notified about
184  *    address suggestions for a specific peer. Addresses asks the solver with
185  *    s_get. If no address is available, it will not send a response, otherwise
186  *    it will respond with the choosen address.
187  *
188  *       1.7.5 Address suggestions
189  *
190  *    Addresses will notify the client automatically on any bandwidth_changed_cb
191  *    by the solver if a address suggestion request is pending. If no address is
192  *    available it will not respond at all If the client is not interested
193  *    anymore, it has to cancel the address suggestion request.
194  *
195  *       1.7.6 Suggestions blocks and reset
196  *
197  *    After suggesting an address it is blocked for ATS_BLOCKING_DELTA sec. to
198  *    prevent the client from being thrashed. If the client requires immediately
199  *    it can reset this block using GAS_addresses_handle_backoff_reset.
200  *
201  *       1.7.7 Marking address in use
202  *
203  *    The client can notify addresses that it successfully uses an address and
204  *    wants this address to be kept by calling GSA_address_in_use. Adresses will
205  *    mark the address as used an notify the solver about the use.
206  *
207  *       1.7.8 Address lifecycle
208  *
209  *      * (add address)
210  *      * (updated address) || (address in use)
211  *      * (delete address)
212  *
213  *     1.8 Bandwidth assignment
214  *
215  *    The addresses are used to perform resource allocation operations. ATS
216  *    addresses takes care of instantiating the solver configured and notifies
217  *    the respective solver about address changes and receives changes to the
218  *    bandwidth assignment from the solver. The current bandwidth assignment is
219  *    sent to transport. The specific solvers will be described in the specific
220  *    section.
221  *
222  *     1.9 Changing peer preferences
223  *
224  *    The bandwidth assigned to a peer can be influenced by setting a preference
225  *    for a peer. The prefernce will be given to to the solver with s_pref which
226  *    has to take care of the preference value
227
228  */
229
230
231 /**
232  * Pending Address suggestion requests
233  */
234 struct GAS_Addresses_Suggestion_Requests
235 {
236   /**
237    * Next in DLL
238    */
239   struct GAS_Addresses_Suggestion_Requests *next;
240
241   /**
242    * Previous in DLL
243    */
244   struct GAS_Addresses_Suggestion_Requests *prev;
245
246   /**
247    * Peer ID
248    */
249   struct GNUNET_PeerIdentity id;
250 };
251
252 /**
253  * Pending Address suggestion requests
254  */
255 struct GAS_Addresses_Preference_Clients
256 {
257   /**
258    * Next in DLL
259    */
260   struct GAS_Addresses_Preference_Clients *next;
261
262   /**
263    * Previous in DLL
264    */
265   struct GAS_Addresses_Preference_Clients *prev;
266
267   /**
268    * Peer ID
269    */
270   void *client;
271 };
272
273
274 /**
275  *
276  */
277 static struct GNUNET_STATISTICS_Handle *stats;
278
279 /**
280  * A multihashmap to store all addresses
281  */
282 static struct GNUNET_CONTAINER_MultiPeerMap *addresses;
283
284 /**
285  * Is ATS addresses running
286  */
287 static int running;
288
289 /**
290  * Preferences clients
291  */
292 static int pref_clients;
293
294 /**
295  * Configured ATS solver
296  */
297 static int ats_mode;
298
299 /**
300  * Solver handle
301  */
302 static void *solver;
303
304 /**
305  * Address suggestion requests DLL head
306  */
307 static struct GAS_Addresses_Suggestion_Requests *pending_requests_head;
308
309 /**
310  * Address suggestion requests DLL tail
311  */
312 static struct GAS_Addresses_Suggestion_Requests *pending_requests_tail;
313
314 /**
315  * Preference requests DLL head
316  */
317 static struct GAS_Addresses_Preference_Clients *preference_clients_head;
318
319 /**
320  * Preference requests DLL head
321  */
322 static struct GAS_Addresses_Preference_Clients *preference_clients_tail;
323
324 /**
325  * Solver functions
326  */
327 static struct GNUNET_ATS_PluginEnvironment env;
328
329 /**
330  * Solver plugin name as string
331  */
332 static char *plugin;
333
334 /**
335  * Value we pass for zero bandwidth.
336  */
337 static const struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
338
339
340 /**
341  * Disassemble ATS information and update performance information in address
342  *
343  * Updates existing information and adds new information
344  *
345  * @param dest destination address
346  * @param update source ATS information
347  * @param update_count number of ATS information in @a update
348  * @param delta_dest ats performance information which were updated
349  *                              including previous value
350  * @param delta_count number of ATS information in the @a delta_dest
351  * @return #GNUNET_YES if address was address updated, GNUNET_NO otherwise
352  */
353 static unsigned int
354 disassemble_ats_information (struct ATS_Address *dest,
355                              const struct GNUNET_ATS_Information *update,
356                              uint32_t update_count,
357                              struct GNUNET_ATS_Information **delta_dest,
358                              uint32_t *delta_count)
359 {
360   int c1;
361   int c2;
362   int found;
363   int change;
364   struct GNUNET_ATS_Information add_atsi[update_count];
365   struct GNUNET_ATS_Information delta_atsi[update_count];
366   struct GNUNET_ATS_Information *tmp_atsi;
367   uint32_t add_atsi_count;
368   uint32_t delta_atsi_count;
369
370   change = GNUNET_NO;
371   add_atsi_count = 0;
372   delta_atsi_count = 0;
373
374   if (0 == update_count)
375     return GNUNET_NO;
376
377   if (NULL == dest->atsi)
378   {
379     /* Create performance information */
380     dest->atsi =
381         GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
382     dest->atsi_count = update_count;
383     memcpy (dest->atsi, update,
384         update_count * sizeof(struct GNUNET_ATS_Information));
385     (*delta_dest) =
386         GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
387     for (c1 = 0; c1 < update_count; c1++)
388     {
389       (*delta_dest)[c1].type = update[c1].type;
390       (*delta_dest)[c1].value = htonl (GNUNET_ATS_VALUE_UNDEFINED);
391     }
392     (*delta_count) = update_count;
393     return GNUNET_YES;
394   }
395
396   for (c1 = 0; c1 < update_count; c1++)
397   {
398     /* Update existing performance information */
399     found = GNUNET_NO;
400     for (c2 = 0; c2 < dest->atsi_count; c2++)
401     {
402       if (update[c1].type == dest->atsi[c2].type)
403       {
404         if (update[c1].value != dest->atsi[c2].value)
405         {
406           /* Save previous value in delta */
407           delta_atsi[delta_atsi_count] = dest->atsi[c2];
408           delta_atsi_count++;
409           /* Set new value */
410           dest->atsi[c2].value = update[c1].value;
411           change = GNUNET_YES;
412         }
413         found = GNUNET_YES;
414         break;
415       }
416     }
417     if (GNUNET_NO == found)
418     {
419       add_atsi[add_atsi_count] = update[c1];
420       add_atsi_count++;
421       delta_atsi[delta_atsi_count].type = update[c1].type;
422       delta_atsi[delta_atsi_count].value = htonl (GNUNET_ATS_VALUE_UNDEFINED);
423       delta_atsi_count++;
424     }
425   }
426
427   if (add_atsi_count > 0)
428   {
429     /* Extend ats performance information */
430
431     tmp_atsi = GNUNET_malloc ((dest->atsi_count + add_atsi_count) *
432         (sizeof (struct GNUNET_ATS_Information)));
433     memcpy (tmp_atsi, dest->atsi,
434         dest->atsi_count * sizeof(struct GNUNET_ATS_Information));
435     memcpy (&tmp_atsi[dest->atsi_count], add_atsi,
436         add_atsi_count * sizeof(struct GNUNET_ATS_Information));
437     GNUNET_free(dest->atsi);
438     dest->atsi = tmp_atsi;
439     dest->atsi_count = dest->atsi_count + add_atsi_count;
440     change = GNUNET_YES;
441   }
442
443   if (delta_atsi_count > 0)
444   {
445     /* Copy delta */
446     (*delta_dest) =
447         GNUNET_malloc (delta_atsi_count * sizeof (struct GNUNET_ATS_Information));
448     memcpy ((*delta_dest), delta_atsi,
449         delta_atsi_count * sizeof(struct GNUNET_ATS_Information));
450     (*delta_count) = delta_atsi_count;
451   }
452
453   return change;
454 }
455
456
457 /**
458  * Free the given address
459  *
460  * @param addr address to destroy
461  */
462 static void
463 free_address (struct ATS_Address *addr)
464 {
465   GNUNET_free (addr->plugin);
466   GNUNET_free_non_null (addr->atsi);
467   GNUNET_free (addr);
468 }
469
470
471 /**
472  * Create a ATS_address with the given information
473  *
474  * @param peer peer
475  * @param plugin_name plugin
476  * @param plugin_addr address
477  * @param plugin_addr_len address length
478  * @param local_address_info additional local info for the address
479  * @param session_id session identifier, can never be 0
480  * @return the ATS_Address
481  */
482 static struct ATS_Address *
483 create_address (const struct GNUNET_PeerIdentity *peer,
484                 const char *plugin_name,
485                 const void *plugin_addr,
486                 size_t plugin_addr_len,
487                 uint32_t local_address_info,
488                 uint32_t session_id)
489 {
490   struct ATS_Address *aa;
491   unsigned int c1;
492   unsigned int c2;
493
494   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
495   aa->peer = *peer;
496   aa->addr_len = plugin_addr_len;
497   aa->addr = &aa[1];
498   memcpy (&aa[1], plugin_addr, plugin_addr_len);
499   aa->plugin = GNUNET_strdup (plugin_name);
500   aa->session_id = session_id;
501   aa->local_address_info = local_address_info;
502
503   for (c1 = 0; c1 < GNUNET_ATS_QualityPropertiesCount; c1++)
504   {
505     aa->atsin[c1].avg_queue_index = 0;
506     for (c2 = 0; c2 < GAS_normalization_queue_length; c2++)
507       aa->atsin[c1].atsi_abs[c2] = GNUNET_ATS_VALUE_UNDEFINED;
508   }
509   return aa;
510 }
511
512
513 /**
514  * Closure for #compare_address_it()
515  */
516 struct CompareAddressContext
517 {
518   const struct ATS_Address *search;
519
520   /* exact_address != NULL if address and session is equal */
521   struct ATS_Address *exact_address;
522   /* exact_address != NULL if address and session is 0 */
523   struct ATS_Address *base_address;
524 };
525
526
527 /**
528  * Comapre addresses.
529  *
530  * @param cls a CompareAddressContext containin the source address
531  * @param key peer id
532  * @param value the address to compare with
533  * @return #GNUNET_YES to continue, #GNUNET_NO if address is founce
534  */
535 static int
536 compare_address_it (void *cls,
537                     const struct GNUNET_PeerIdentity *key,
538                     void *value)
539 {
540   struct CompareAddressContext *cac = cls;
541   struct ATS_Address *aa = value;
542
543   /* Find an matching exact address:
544    *
545    * Compare by:
546    * aa->addr_len == cac->search->addr_len
547    * aa->plugin == cac->search->plugin
548    * aa->addr == cac->search->addr
549    * aa->session == cac->search->session
550    *
551    * return as exact address
552    */
553   if ((aa->addr_len == cac->search->addr_len)
554       && (0 == strcmp (aa->plugin, cac->search->plugin)))
555   {
556     if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len))
557         && (aa->session_id == cac->search->session_id))
558       cac->exact_address = aa;
559   }
560
561   /* Find an matching base address:
562    *
563    * Properties:
564    *
565    * aa->session_id == 0
566    *
567    * Compare by:
568    * aa->addr_len == cac->search->addr_len
569    * aa->plugin == cac->search->plugin
570    * aa->addr == cac->search->addr
571    *
572    * return as base address
573    */
574   if ((aa->addr_len == cac->search->addr_len)
575       && (0 == strcmp (aa->plugin, cac->search->plugin)))
576   {
577     if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len))
578         && (aa->session_id == 0))
579       cac->base_address = aa;
580   }
581
582   /* Find an matching exact address based on session:
583    *
584    * Properties:
585    *
586    * cac->search->addr_len == 0
587    *
588    * Compare by:
589    * aa->plugin == cac->search->plugin
590    * aa->session_id == cac->search->session_id
591    *
592    * return as exact address
593    */
594   if (0 == cac->search->addr_len)
595   {
596     if ((0 == strcmp (aa->plugin, cac->search->plugin))
597         && (aa->session_id == cac->search->session_id))
598       cac->exact_address = aa;
599   }
600
601   if (cac->exact_address == NULL )
602     return GNUNET_YES; /* Continue iteration to find exact address */
603   else
604     return GNUNET_NO; /* Stop iteration since we have an exact address */
605 }
606
607
608 /**
609  * Find an existing equivalent address record.
610  * Compares by peer identity and network address OR by session ID
611  * (one of the two must match).
612  *
613  * @param peer peer to lookup addresses for
614  * @param addr existing address record
615  * @return existing address record, NULL for none
616  */
617 struct ATS_Address *
618 find_equivalent_address (const struct GNUNET_PeerIdentity *peer,
619                          const struct ATS_Address *addr)
620 {
621   struct CompareAddressContext cac;
622
623   cac.exact_address = NULL;
624   cac.base_address = NULL;
625   cac.search = addr;
626   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
627                                               peer,
628                                               &compare_address_it, &cac);
629
630   if (NULL == cac.exact_address)
631     return cac.base_address;
632   return cac.exact_address;
633 }
634
635
636 /**
637  * Closure for #find_address_cb()
638  */
639 struct FindAddressContext
640 {
641   /**
642    * Session Id to look for.
643    */
644   uint32_t session_id;
645
646   /**
647    * Where to store matching address result.
648    */
649   struct ATS_Address *exact_address;
650
651 };
652
653
654 /**
655  * Find session matching given session ID.
656  *
657  * @param cls a `struct FindAddressContext`
658  * @param key peer id
659  * @param value the address to compare with
660  * @return #GNUNET_YES to continue, #GNUNET_NO if address is found
661  */
662 static int
663 find_address_cb (void *cls,
664                  const struct GNUNET_PeerIdentity *key,
665                  void *value)
666 {
667   struct FindAddressContext *fac = cls;
668   struct ATS_Address *aa = value;
669
670   if (aa->session_id == fac->session_id)
671   {
672     fac->exact_address = aa;
673     return GNUNET_NO;
674   }
675   return GNUNET_YES;
676 }
677
678
679 /**
680  * Find the exact address
681  *
682  * @param peer peer
683  * @param session_id session id, can never be 0
684  * @return an ATS_address or NULL
685  */
686 static struct ATS_Address *
687 find_exact_address (const struct GNUNET_PeerIdentity *peer,
688                     uint32_t session_id)
689 {
690   struct FindAddressContext fac;
691
692   fac.exact_address = NULL;
693   fac.session_id = session_id;
694   GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
695                                               peer,
696                                               &find_address_cb, &fac);
697   return fac.exact_address;
698 }
699
700
701 /**
702  * Function allowing the solver to obtain normalized preference
703  * values from solver
704  *
705  * @param cls unused
706  * @param id the peer to return the normalized properties for
707  * @return array of double values with |GNUNET_ATS_PreferenceCount| elements
708  */
709 const double *
710 get_preferences_cb (void *cls,
711                     const struct GNUNET_PeerIdentity *id)
712 {
713   return GAS_normalization_get_preferences_by_peer (id);
714 }
715
716
717 /**
718  * Function allowing the solver to obtain normalized property
719  * values for an address from solver
720  *
721  * @param cls unused
722  * @param address the address
723  * @return array of double values with |GNUNET_ATS_QualityPropertiesCount| elements
724  */
725 const double *
726 get_property_cb (void *cls, const struct ATS_Address *address)
727 {
728   return GAS_normalization_get_properties ((struct ATS_Address *) address);
729 }
730
731
732 /**
733  * Extract an ATS performance info from an address
734  *
735  * @param address the address
736  * @param type the type to extract in HBO
737  * @return the value in HBO or #GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
738  */
739 static int
740 get_performance_info (struct ATS_Address *address, uint32_t type)
741 {
742   int c1;
743   GNUNET_assert(NULL != address);
744
745   if ((NULL == address->atsi) || (0 == address->atsi_count))
746     return GNUNET_ATS_VALUE_UNDEFINED;
747
748   for (c1 = 0; c1 < address->atsi_count; c1++)
749   {
750     if (ntohl (address->atsi[c1].type) == type)
751       return ntohl (address->atsi[c1].value);
752   }
753   return GNUNET_ATS_VALUE_UNDEFINED;
754 }
755
756
757 /**
758  * Add a new address for a peer.
759  *
760  * @param peer peer
761  * @param plugin_name transport plugin name
762  * @param plugin_addr plugin address
763  * @param plugin_addr_len length of the plugin address in @a plugin_addr
764  * @param local_address_info the local address for the address
765  * @param session_id session id, can be 0
766  * @param atsi performance information for this address
767  * @param atsi_count number of performance information contained in @a atsi
768  */
769 void
770 GAS_addresses_add (const struct GNUNET_PeerIdentity *peer,
771                    const char *plugin_name,
772                    const void *plugin_addr,
773                    size_t plugin_addr_len,
774                    uint32_t local_address_info,
775                    uint32_t session_id,
776                    const struct GNUNET_ATS_Information *atsi,
777                    uint32_t atsi_count)
778 {
779   struct ATS_Address *new_address;
780   struct ATS_Address *existing_address;
781   struct GNUNET_ATS_Information *atsi_delta;
782   uint32_t atsi_delta_count;
783   uint32_t addr_net;
784   uint32_t previous_session;
785   int c1;
786
787   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
788              "Received `%s' for peer `%s'\n",
789              "ADDRESS ADD",
790              GNUNET_i2s (peer));
791
792   if (GNUNET_NO == running)
793     return;
794
795   GNUNET_assert(NULL != addresses);
796
797   new_address = create_address (peer, plugin_name,
798                                 plugin_addr, plugin_addr_len,
799                                 local_address_info, session_id);
800   atsi_delta = NULL;
801   disassemble_ats_information (new_address, atsi, atsi_count, &atsi_delta,
802                                &atsi_delta_count);
803   GNUNET_free_non_null (atsi_delta);
804   addr_net = get_performance_info (new_address, GNUNET_ATS_NETWORK_TYPE);
805   if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
806     addr_net = GNUNET_ATS_NET_UNSPECIFIED;
807
808   /* Get existing address or address with session == 0 */
809   existing_address = find_equivalent_address (peer, new_address);
810   if (NULL == existing_address)
811   {
812     /* Add a new address */
813     new_address->t_added = GNUNET_TIME_absolute_get();
814     new_address->t_last_activity = GNUNET_TIME_absolute_get();
815     GNUNET_assert(GNUNET_OK ==
816                   GNUNET_CONTAINER_multipeermap_put (addresses,
817                                                      peer,
818                                                      new_address,
819                                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
820
821     GNUNET_STATISTICS_set (stats,
822                            "# addresses",
823                            GNUNET_CONTAINER_multipeermap_size (addresses),
824                            GNUNET_NO);
825
826     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
827                 "Adding new address %p for peer `%s', length %u, session id %u, %s\n",
828                 new_address,
829                 GNUNET_i2s (peer),
830                 plugin_addr_len,
831                 session_id,
832                 GNUNET_ATS_print_network_type (addr_net));
833
834     /* Tell solver about new address */
835     env.sf.s_add (solver, new_address, addr_net);
836
837     env.sf.s_bulk_start (solver);
838     GAS_normalization_normalize_property (addresses,
839                                           new_address,
840                                           atsi,
841                                           atsi_count);
842     env.sf.s_bulk_stop (solver);
843
844     /* Notify performance clients about new address */
845     GAS_performance_notify_all_clients (&new_address->peer, new_address->plugin,
846         new_address->addr, new_address->addr_len, new_address->active,
847         new_address->atsi, new_address->atsi_count,
848         GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_out),
849         GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_in));
850     return;
851   }
852
853   /* FIXME: this case should probably not be allowed... */
854   /* We have an existing address we can use, clean up new */
855   GNUNET_free(new_address->plugin);
856   GNUNET_free_non_null(new_address->atsi);
857   GNUNET_free(new_address);
858   new_address = NULL;
859
860   if (0 != existing_address->session_id)
861   {
862     /* Should not happen */
863     GNUNET_break(0);
864     return;
865   }
866
867   addr_net = get_performance_info (existing_address, GNUNET_ATS_NETWORK_TYPE);
868   if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
869     addr_net = GNUNET_ATS_NET_UNSPECIFIED;
870
871   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
872       "Found existing address for peer `%s' %p with new session %u in network %s\n",
873       GNUNET_i2s (peer), existing_address, session_id,
874       GNUNET_ATS_print_network_type (addr_net));
875   /* We have an address without an session, update this address */
876   existing_address->t_added = GNUNET_TIME_absolute_get();
877   existing_address->t_last_activity = GNUNET_TIME_absolute_get();
878   atsi_delta = NULL;
879   atsi_delta_count = 0;
880   if (GNUNET_YES
881       == disassemble_ats_information (existing_address, atsi, atsi_count,
882           &atsi_delta, &atsi_delta_count))
883   {
884     /* Notify performance clients about properties */
885     GAS_performance_notify_all_clients (&existing_address->peer,
886         existing_address->plugin, existing_address->addr,
887         existing_address->addr_len, existing_address->active,
888         existing_address->atsi, existing_address->atsi_count,
889         GNUNET_BANDWIDTH_value_init (existing_address->assigned_bw_out),
890         GNUNET_BANDWIDTH_value_init (existing_address->assigned_bw_in));
891
892     for (c1 = 0; c1 < atsi_delta_count; c1++)
893     {
894       if ((GNUNET_ATS_NETWORK_TYPE == ntohl (atsi_delta[c1].type))
895           && (addr_net != ntohl (atsi_delta[c1].value)))
896       {
897         /* Network type changed */
898         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
899             "Address for peer `%s' %p changed from network %s to %s\n",
900             GNUNET_i2s (peer), existing_address,
901             GNUNET_ATS_print_network_type (addr_net),
902             GNUNET_ATS_print_network_type (ntohl (atsi_delta[c1].value)));
903         env.sf.s_address_update_network (solver, existing_address,
904             ntohl (atsi_delta[c1].value),
905             get_performance_info (existing_address, GNUNET_ATS_NETWORK_TYPE));
906         addr_net = get_performance_info (existing_address,
907             GNUNET_ATS_NETWORK_TYPE);
908       }
909     }
910     /* Notify solver about update with atsi information and session */
911     env.sf.s_bulk_start (solver);
912     GAS_normalization_normalize_property (addresses, existing_address,
913                                           atsi, atsi_count);
914     env.sf.s_bulk_stop (solver);
915   }
916   GNUNET_free_non_null(atsi_delta);
917
918   /* Notify solver about new session */
919   if (existing_address->session_id == session_id)
920     return; /* possible, can both be 0 since address is revalidated */
921
922   previous_session = existing_address->session_id;
923   existing_address->session_id = session_id;
924   env.sf.s_address_update_session (solver, existing_address,
925       previous_session, session_id);
926
927   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
928       "Updated existing address for peer `%s' %p length %u with new session %u in network %s\n",
929       GNUNET_i2s (peer), existing_address, existing_address->addr_len,
930       session_id, GNUNET_ATS_print_network_type (addr_net));
931 }
932
933
934 /**
935  * Update an address with new performance information for a peer.
936  *
937  * @param peer peer
938  * @param session_id session id, never 0
939  * @param atsi performance information for this address
940  * @param atsi_count number of performance information contained in @a atsi
941  */
942 void
943 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
944                       uint32_t session_id,
945                       const struct GNUNET_ATS_Information *atsi,
946                       uint32_t atsi_count)
947 {
948   struct ATS_Address *aa;
949   struct GNUNET_ATS_Information *atsi_delta;
950   uint32_t atsi_delta_count;
951   uint32_t prev_session;
952   int c1;
953
954   if (GNUNET_NO == running)
955     return;
956   GNUNET_assert (NULL != addresses);
957
958   /* Get existing address */
959   aa = find_exact_address (peer,
960                            session_id);
961   if (NULL == aa)
962   {
963     GNUNET_break (0);
964     return;
965   }
966   if (NULL == aa->solver_information)
967   {
968     GNUNET_break (0);
969     return;
970   }
971
972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973               "Received `%s' for peer `%s' address \n",
974               "ADDRESS UPDATE",
975               GNUNET_i2s (peer),
976               aa);
977
978   /* Update address */
979   aa->t_last_activity = GNUNET_TIME_absolute_get();
980   if (session_id != aa->session_id)
981   {
982     /* Session changed */
983     prev_session = aa->session_id;
984     aa->session_id = session_id;
985     env.sf.s_address_update_session (solver,
986                                      aa,
987                                      prev_session,
988                                      aa->session_id);
989   }
990
991   atsi_delta = NULL;
992   atsi_delta_count = 0;
993   if (GNUNET_YES ==
994       disassemble_ats_information (aa, atsi,
995                                    atsi_count,
996                                    &atsi_delta,
997                                    &atsi_delta_count))
998   {
999     /* ATS properties changed */
1000     for (c1 = 0; c1 < atsi_delta_count; c1++)
1001     {
1002       if (GNUNET_ATS_NETWORK_TYPE == ntohl (atsi_delta[c1].type))
1003       {
1004         /* Network type changed */
1005         env.sf.s_address_update_network (solver, aa,
1006             ntohl (atsi_delta[c1].value),
1007             get_performance_info (aa, GNUNET_ATS_NETWORK_TYPE));
1008       }
1009     }
1010
1011     /* Notify performance clients about updated address */
1012     GAS_performance_notify_all_clients (&aa->peer, aa->plugin, aa->addr,
1013         aa->addr_len, aa->active, aa->atsi, aa->atsi_count,
1014         GNUNET_BANDWIDTH_value_init (aa->assigned_bw_out),
1015         GNUNET_BANDWIDTH_value_init (aa->assigned_bw_in));
1016
1017     env.sf.s_bulk_start (solver);
1018     GAS_normalization_normalize_property (addresses,
1019                                           aa,
1020                                           atsi,
1021                                           atsi_count);
1022     env.sf.s_bulk_stop (solver);
1023   }
1024   GNUNET_free_non_null (atsi_delta);
1025 }
1026
1027
1028 /**
1029  * Remove an address or just a session for a peer.
1030  *
1031  * @param peer peer
1032  * @param session_id session id, can never be 0
1033  */
1034 void
1035 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
1036                        uint32_t session_id)
1037 {
1038   struct ATS_Address *ea;
1039
1040   if (GNUNET_NO == running)
1041     return;
1042
1043   /* Get existing address */
1044   ea = find_exact_address (peer,
1045                            session_id);
1046   if (NULL == ea)
1047   {
1048     GNUNET_break (0);
1049     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1050                 "Tried to destroy unknown address for peer `%s' session id %u\n",
1051                 GNUNET_i2s (peer),
1052                 session_id);
1053     return;
1054   }
1055
1056   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1057               "Received `%s' for peer `%s' address %p session %u\n",
1058               "ADDRESS DESTROYED",
1059               GNUNET_i2s (peer),
1060               ea,
1061               session_id);
1062   GNUNET_CONTAINER_multipeermap_remove (addresses,
1063                                         peer,
1064                                         ea);
1065
1066   env.sf.s_del (solver, ea, GNUNET_NO);
1067   GAS_performance_notify_all_clients (peer,
1068                                       ea->plugin,
1069                                       ea->addr,
1070                                       ea->addr_len,
1071                                       GNUNET_SYSERR,
1072                                       NULL, 0,
1073                                       zero_bw,
1074                                       zero_bw);
1075   free_address (ea);
1076   GNUNET_STATISTICS_set (stats,
1077                          "# addresses",
1078                          GNUNET_CONTAINER_multipeermap_size (addresses),
1079                          GNUNET_NO);
1080 }
1081
1082
1083 /**
1084  * Notification about active use of an address.
1085  * in_use == #GNUNET_YES:
1086  *      This address is used to maintain an active connection with a peer.
1087  * in_use == #GNUNET_NO:
1088  *      This address is no longer used to maintain an active connection with a peer.
1089  *
1090  * Note: can only be called with in_use == #GNUNET_NO if called with #GNUNET_YES
1091  * before
1092  *
1093  * @param peer peer
1094  * @param session_id session id, can be 0
1095  * @param in_use #GNUNET_YES if #GNUNET_NO FIXME
1096  * @return #GNUNET_SYSERR on failure (address unknown ...)
1097  */
1098 int
1099 GAS_addresses_in_use (const struct GNUNET_PeerIdentity *peer,
1100                       uint32_t session_id,
1101                       int in_use)
1102 {
1103   struct ATS_Address *ea;
1104
1105   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1106              "Received `%s' for peer `%s'\n",
1107              "ADDRESS IN USE",
1108              GNUNET_i2s (peer));
1109   if (GNUNET_NO == running)
1110     return GNUNET_SYSERR;
1111   ea = find_exact_address (peer,
1112                            session_id);
1113   if (NULL == ea)
1114   {
1115     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1116                 "Trying to set unknown address `%s' `%u' to %s \n",
1117                 GNUNET_i2s (peer),
1118                 session_id,
1119                 (GNUNET_NO == in_use) ? "NO" : "YES");
1120     GNUNET_break (0);
1121     return GNUNET_SYSERR;
1122   }
1123   if (ea->used == in_use)
1124   {
1125     GNUNET_break (0);
1126     GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1127                "Address in use called multiple times for peer `%s': %s -> %s \n",
1128                GNUNET_i2s (peer),
1129                (GNUNET_NO == ea->used) ? "NO" : "YES",
1130                (GNUNET_NO == in_use) ? "NO" : "YES");
1131     return GNUNET_SYSERR;
1132   }
1133   /* Tell solver about update */
1134   ea->used = in_use;
1135   ea->t_last_activity = GNUNET_TIME_absolute_get();
1136   env.sf.s_address_update_inuse (solver,
1137                                  ea,
1138                                  ea->used);
1139   return GNUNET_OK;
1140 }
1141
1142
1143 /**
1144  * Cancel address suggestions for a peer
1145  *
1146  * @param peer the peer id
1147  */
1148 void
1149 GAS_addresses_request_address_cancel (const struct GNUNET_PeerIdentity *peer)
1150 {
1151   struct GAS_Addresses_Suggestion_Requests *cur = pending_requests_head;
1152
1153   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1154              "Received request: `%s' for peer %s\n",
1155              "request_address_cancel",
1156              GNUNET_i2s (peer));
1157
1158   while (NULL != cur)
1159   {
1160     if (0 == memcmp (peer, &cur->id, sizeof(cur->id)))
1161       break; /* found */
1162     cur = cur->next;
1163   }
1164
1165   if (NULL == cur)
1166   {
1167     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1168         "No address requests pending for peer `%s', cannot remove!\n",
1169         GNUNET_i2s (peer));
1170     return;
1171   }
1172   env.sf.s_get_stop (solver, peer);
1173   GAS_addresses_handle_backoff_reset (peer);
1174   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1175              "Removed request pending for peer `%s\n",
1176              GNUNET_i2s (peer));
1177   GNUNET_CONTAINER_DLL_remove (pending_requests_head,
1178                                pending_requests_tail,
1179                                cur);
1180   GNUNET_free(cur);
1181 }
1182
1183
1184 /**
1185  * Request address suggestions for a peer
1186  *
1187  * @param peer the peer id
1188  */
1189 void
1190 GAS_addresses_request_address (const struct GNUNET_PeerIdentity *peer)
1191 {
1192   struct GAS_Addresses_Suggestion_Requests *cur = pending_requests_head;
1193   struct ATS_Address *aa;
1194
1195   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1196              "Received `%s' for peer `%s'\n",
1197              "REQUEST ADDRESS",
1198              GNUNET_i2s (peer));
1199
1200   if (GNUNET_NO == running)
1201     return;
1202   while (NULL != cur)
1203   {
1204     if (0 == memcmp (peer, &cur->id, sizeof(cur->id)))
1205       break; /* already suggesting */
1206     cur = cur->next;
1207   }
1208   if (NULL == cur)
1209   {
1210     cur = GNUNET_new (struct GAS_Addresses_Suggestion_Requests);
1211     cur->id = (*peer);
1212     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1213         "Adding new address suggestion request for `%s'\n",
1214          GNUNET_i2s (peer));
1215     GNUNET_CONTAINER_DLL_insert (pending_requests_head,
1216                                  pending_requests_tail,
1217                                  cur);
1218   }
1219
1220   /* Get prefered address from solver */
1221   aa = (struct ATS_Address *) env.sf.s_get (solver, peer);
1222   if (NULL == aa)
1223   {
1224     GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Cannot suggest address for peer `%s'\n",
1225         GNUNET_i2s (peer));
1226     return;
1227   }
1228
1229   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Suggesting address %p for peer `%s'\n",
1230       aa, GNUNET_i2s (peer));
1231
1232   GAS_scheduling_transmit_address_suggestion (peer,
1233                                               aa->session_id,
1234                                               GNUNET_BANDWIDTH_value_init (aa->assigned_bw_out),
1235                                               GNUNET_BANDWIDTH_value_init (aa->assigned_bw_in));
1236
1237   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval,
1238       ATS_BLOCKING_DELTA);
1239   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1240       aa->block_interval);
1241
1242   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1243       "Address %p ready for suggestion, block interval now %llu \n", aa,
1244       aa->block_interval);
1245 }
1246
1247 /**
1248  * Iterator to reset address blocking
1249  *
1250  * @param cls not used
1251  * @param key the peer
1252  * @param value the address to reset
1253  * @return #GNUNET_OK to continue
1254  */
1255 static int
1256 reset_address_it (void *cls,
1257                   const struct GNUNET_PeerIdentity *key,
1258                   void *value)
1259 {
1260   struct ATS_Address *aa = value;
1261
1262   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1263              "Resetting interval for peer `%s' address %p from %llu to 0\n",
1264              GNUNET_i2s (&aa->peer),
1265              aa,
1266              aa->block_interval);
1267   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
1268   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
1269   return GNUNET_OK;
1270 }
1271
1272
1273 /**
1274  * Reset suggestion backoff for a peer
1275  *
1276  * Suggesting addresses is blocked for ATS_BLOCKING_DELTA. Blocking can be
1277  * reset using this function
1278  *
1279  * @param peer the peer id
1280  */
1281 void
1282 GAS_addresses_handle_backoff_reset (const struct GNUNET_PeerIdentity *peer)
1283 {
1284   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1285              "Received `%s' for peer `%s'\n",
1286              "RESET BACKOFF",
1287              GNUNET_i2s (peer));
1288
1289   GNUNET_break(GNUNET_SYSERR !=
1290                GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
1291                                                            peer,
1292                                                            &reset_address_it,
1293                                                            NULL));
1294 }
1295
1296
1297 /**
1298  * Solver information callback
1299  *
1300  * @param cls the closure
1301  * @param op the operation
1302  * @param status operation status
1303  * @param add additional information
1304  */
1305 static void
1306 solver_info_cb (void *cls,
1307     enum GAS_Solver_Operation op,
1308     enum GAS_Solver_Status status,
1309     enum GAS_Solver_Additional_Information add)
1310 {
1311   char *add_info;
1312
1313   switch (add) {
1314     case GAS_INFO_NONE:
1315       add_info = "GAS_INFO_NONE";
1316       break;
1317     case GAS_INFO_FULL:
1318       add_info = "GAS_INFO_MLP_FULL";
1319       break;
1320     case GAS_INFO_UPDATED:
1321       add_info = "GAS_INFO_MLP_UPDATED";
1322       break;
1323     case GAS_INFO_PROP_ALL:
1324       add_info = "GAS_INFO_PROP_ALL";
1325       break;
1326     case GAS_INFO_PROP_SINGLE:
1327       add_info = "GAS_INFO_PROP_SINGLE";
1328       break;
1329     default:
1330       add_info = "INVALID";
1331       break;
1332   }
1333   switch (op)
1334   {
1335     case GAS_OP_SOLVE_START:
1336       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1337           "Solver notifies `%s' with result `%s' `%s'\n", "GAS_OP_SOLVE_START",
1338           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL", add_info);
1339       return;
1340     case GAS_OP_SOLVE_STOP:
1341       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1342           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_STOP",
1343           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL", add_info);
1344       return;
1345
1346     case GAS_OP_SOLVE_SETUP_START:
1347       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1348           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_START",
1349           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1350       return;
1351
1352     case GAS_OP_SOLVE_SETUP_STOP:
1353       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1354           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_SETUP_STOP",
1355           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1356       return;
1357
1358     case GAS_OP_SOLVE_MLP_LP_START:
1359       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1360           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_START",
1361           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1362       return;
1363     case GAS_OP_SOLVE_MLP_LP_STOP:
1364       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1365           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_LP_STOP",
1366           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1367       return;
1368
1369     case GAS_OP_SOLVE_MLP_MLP_START:
1370       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1371           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_START",
1372           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1373       return;
1374     case GAS_OP_SOLVE_MLP_MLP_STOP:
1375       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1376           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_MLP_STOP",
1377           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1378       return;
1379     case GAS_OP_SOLVE_UPDATE_NOTIFICATION_START:
1380       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1381           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_START",
1382           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1383       return;
1384     case GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP:
1385       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1386           "Solver notifies `%s' with result `%s'\n", "GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP",
1387           (GAS_STAT_SUCCESS == status) ? "SUCCESS" : "FAIL");
1388       return;
1389     default:
1390       break;
1391     }
1392 }
1393
1394
1395 /**
1396  * The preference changed for a peer
1397  *
1398  * @param cls NULL
1399  * @param peer the peer
1400  * @param kind the ATS kind
1401  * @param pref_rel the new relative preference value
1402  */
1403 static void
1404 normalized_preference_changed_cb (void *cls,
1405                                   const struct GNUNET_PeerIdentity *peer,
1406                                   enum GNUNET_ATS_PreferenceKind kind,
1407                                   double pref_rel)
1408 {
1409   /* Tell solver about update */
1410   env.sf.s_pref (solver, peer, kind, pref_rel);
1411 }
1412
1413
1414 /**
1415  * The relative value for a property changed
1416  *
1417  * @param cls NULL
1418  * @param address the peer
1419  * @param type the ATS type
1420  * @param prop_rel the new relative preference value
1421  */
1422 static void
1423 normalized_property_changed_cb (void *cls,
1424                                 struct ATS_Address *address,
1425                                 uint32_t type,
1426                                 double prop_rel)
1427 {
1428   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1429              "Normalized property %s for peer `%s' changed to %.3f \n",
1430              GNUNET_ATS_print_property_type (type),
1431              GNUNET_i2s (&address->peer),
1432              prop_rel);
1433   env.sf.s_address_update_property (solver,
1434                                     address,
1435                                     type,
1436                                     0,
1437                                     prop_rel);
1438 }
1439
1440
1441 static struct GAS_Addresses_Preference_Clients *
1442 find_preference_client (void *client)
1443 {
1444   struct GAS_Addresses_Preference_Clients *cur;
1445
1446   for (cur = preference_clients_head; NULL != cur; cur = cur->next)
1447     if (cur->client == client)
1448       return cur;
1449   return NULL;
1450 }
1451
1452
1453 /**
1454  * A performance client disconnected
1455  *
1456  * @param client the client
1457  */
1458 void
1459 GAS_addresses_preference_client_disconnect (void *client)
1460 {
1461   struct GAS_Addresses_Preference_Clients *pc;
1462
1463   if (NULL != (pc = find_preference_client (client)))
1464   {
1465     GNUNET_CONTAINER_DLL_remove (preference_clients_head,
1466                                  preference_clients_tail,
1467                                  pc);
1468     GNUNET_free (pc);
1469     GNUNET_assert (pref_clients > 0);
1470     pref_clients --;
1471     GNUNET_STATISTICS_set (stats,
1472                            "# active performance clients",
1473                            pref_clients,
1474                            GNUNET_NO);
1475   }
1476   GAS_normalization_preference_client_disconnect (client);
1477 }
1478
1479
1480 /**
1481  * Change the preference for a peer
1482  *
1483  * @param client the client sending this request
1484  * @param peer the peer id
1485  * @param kind the preference kind to change
1486  * @param score_abs the new preference score
1487  */
1488 void
1489 GAS_addresses_preference_change (void *client,
1490                                  const struct GNUNET_PeerIdentity *peer,
1491                                  enum GNUNET_ATS_PreferenceKind kind,
1492                                  float score_abs)
1493 {
1494   struct GAS_Addresses_Preference_Clients *pc;
1495
1496   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1497       "Received `%s' for peer `%s' for client %p\n", "CHANGE PREFERENCE",
1498       GNUNET_i2s (peer), client);
1499
1500   if (GNUNET_NO == running)
1501     return;
1502
1503   if (GNUNET_NO ==
1504       GNUNET_CONTAINER_multipeermap_contains (addresses,
1505                                               peer))
1506   {
1507     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1508         "Received `%s' for unknown peer `%s' from client %p\n",
1509         "CHANGE PREFERENCE", GNUNET_i2s (peer), client);
1510     return;
1511   }
1512
1513   if (NULL == find_preference_client (client))
1514   {
1515     pc = GNUNET_new (struct GAS_Addresses_Preference_Clients);
1516     pc->client = client;
1517     GNUNET_CONTAINER_DLL_insert (preference_clients_head,
1518                                  preference_clients_tail,
1519                                  pc);
1520     pref_clients ++;
1521     GNUNET_STATISTICS_set (stats,
1522                            "# active performance clients",
1523                            pref_clients,
1524                            GNUNET_NO);
1525   }
1526
1527   env.sf.s_bulk_start (solver);
1528   /* Tell normalization about change, normalization will call callback if preference changed */
1529   GAS_normalization_normalize_preference (client, peer, kind, score_abs);
1530   env.sf.s_bulk_stop (solver);
1531 }
1532
1533
1534 /**
1535  * Change the preference for a peer
1536  *
1537  * @param application the client sending this request
1538  * @param peer the peer id
1539  * @param scope the time interval for this feedback: [now - scope .. now]
1540  * @param kind the preference kind to change
1541  * @param score_abs the new preference score
1542  */
1543 void
1544 GAS_addresses_preference_feedback (void *application,
1545                                    const struct GNUNET_PeerIdentity *peer,
1546                                    const struct GNUNET_TIME_Relative scope,
1547                                    enum GNUNET_ATS_PreferenceKind kind,
1548                                    float score_abs)
1549 {
1550   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1551              "Received `%s' for peer `%s' for client %p\n",
1552              "PREFERENCE FEEDBACK",
1553              GNUNET_i2s (peer),
1554              application);
1555
1556   if (GNUNET_NO == running)
1557     return;
1558
1559   if (GNUNET_NO ==
1560       GNUNET_CONTAINER_multipeermap_contains (addresses,
1561                                               peer))
1562   {
1563     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1564         "Received `%s' for unknown peer `%s' from client %p\n",
1565         "PREFERENCE FEEDBACK", GNUNET_i2s (peer), application);
1566     return;
1567   }
1568
1569   env.sf.s_feedback (solver, application, peer, scope, kind,
1570                      score_abs);
1571 }
1572
1573
1574 /**
1575  * Load quotas for networks from configuration
1576  *
1577  * @param cfg configuration handle
1578  * @param out_dest where to write outbound quotas
1579  * @param in_dest where to write inbound quotas
1580  * @param dest_length length of inbound and outbound arrays
1581  * @return number of networks loaded
1582  */
1583 static unsigned int
1584 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg,
1585     unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
1586 {
1587   char * entry_in = NULL;
1588   char * entry_out = NULL;
1589   char * quota_out_str;
1590   char * quota_in_str;
1591   int c;
1592   int res;
1593
1594   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
1595   {
1596     in_dest[c] = 0;
1597     out_dest[c] = 0;
1598     GNUNET_asprintf (&entry_out,
1599                      "%s_QUOTA_OUT",
1600                      GNUNET_ATS_print_network_type (c));
1601     GNUNET_asprintf (&entry_in,
1602                      "%s_QUOTA_IN",
1603                      GNUNET_ATS_print_network_type (c));
1604
1605     /* quota out */
1606     if (GNUNET_OK
1607         == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", entry_out,
1608             &quota_out_str))
1609     {
1610       res = GNUNET_NO;
1611       if (0 == strcmp (quota_out_str, GNUNET_ATS_MaxBandwidthString))
1612       {
1613         out_dest[c] = GNUNET_ATS_MaxBandwidth;
1614         res = GNUNET_YES;
1615       }
1616       if ((GNUNET_NO == res)
1617           && (GNUNET_OK
1618               == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str,
1619                   &out_dest[c])))
1620         res = GNUNET_YES;
1621       if ((GNUNET_NO == res)
1622           && (GNUNET_OK
1623               == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_out,
1624                   &out_dest[c])))
1625         res = GNUNET_YES;
1626
1627       if (GNUNET_NO == res)
1628       {
1629         GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1630                    _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1631                    GNUNET_ATS_print_network_type (c),
1632                    quota_out_str,
1633                    GNUNET_ATS_DefaultBandwidth);
1634         out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1635       }
1636       else
1637       {
1638         GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1639                    _("Outbound quota configure for network `%s' is %llu\n"),
1640                    GNUNET_ATS_print_network_type (c),
1641                    out_dest[c]);
1642       }
1643       GNUNET_free(quota_out_str);
1644     }
1645     else
1646     {
1647       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1648                  _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"),
1649                  GNUNET_ATS_print_network_type (c),
1650                  GNUNET_ATS_DefaultBandwidth);
1651       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1652     }
1653
1654     /* quota in */
1655     if (GNUNET_OK
1656         == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", entry_in,
1657             &quota_in_str))
1658     {
1659       res = GNUNET_NO;
1660       if (0 == strcmp (quota_in_str, GNUNET_ATS_MaxBandwidthString))
1661       {
1662         in_dest[c] = GNUNET_ATS_MaxBandwidth;
1663         res = GNUNET_YES;
1664       }
1665       if ((GNUNET_NO == res)
1666           && (GNUNET_OK
1667               == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
1668         res = GNUNET_YES;
1669       if ((GNUNET_NO == res)
1670           && (GNUNET_OK
1671               == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_in,
1672                   &in_dest[c])))
1673         res = GNUNET_YES;
1674
1675       if (GNUNET_NO == res)
1676       {
1677         GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1678                    _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1679                    GNUNET_ATS_print_network_type (c),
1680                    quota_in_str,
1681                    GNUNET_ATS_DefaultBandwidth);
1682         in_dest[c] = GNUNET_ATS_DefaultBandwidth;
1683       }
1684       else
1685       {
1686         GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1687                    _("Inbound quota configured for network `%s' is %llu\n"),
1688                    GNUNET_ATS_print_network_type (c),
1689                    in_dest[c]);
1690       }
1691       GNUNET_free(quota_in_str);
1692     }
1693     else
1694     {
1695       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1696                  _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"),
1697                  GNUNET_ATS_print_network_type (c),
1698                  GNUNET_ATS_DefaultBandwidth);
1699       in_dest[c] = GNUNET_ATS_DefaultBandwidth;
1700     }
1701     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1702                "Loaded quota for network `%s' (in/out): %llu %llu\n",
1703                GNUNET_ATS_print_network_type (c),
1704                in_dest[c],
1705                out_dest[c]);
1706     GNUNET_free(entry_out);
1707     GNUNET_free(entry_in);
1708   }
1709   return GNUNET_ATS_NetworkTypeCount;
1710 }
1711
1712
1713 /**
1714  * Callback for solver to notify about assignment changes
1715  *
1716  * @param cls NULL
1717  * @param address the address with changes
1718  */
1719 static void
1720 bandwidth_changed_cb (void *cls, struct ATS_Address *address)
1721 {
1722   struct GAS_Addresses_Suggestion_Requests *cur;
1723   uint32_t diff_out;
1724   uint32_t diff_in;
1725
1726   GNUNET_assert(address != NULL);
1727   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1728               "Bandwidth assignment changed for peer %s \n",
1729               GNUNET_i2s (&address->peer));
1730
1731   /* Notify performance clients about changes to address */
1732   GAS_performance_notify_all_clients (&address->peer, address->plugin,
1733       address->addr, address->addr_len, address->active, address->atsi,
1734       address->atsi_count,
1735       GNUNET_BANDWIDTH_value_init (address->assigned_bw_out),
1736       GNUNET_BANDWIDTH_value_init (address->assigned_bw_in));
1737
1738   for (cur = pending_requests_head;NULL != cur; cur = cur->next)
1739     if (0 == memcmp (&address->peer, &cur->id, sizeof(cur->id)))
1740       break; /* we have an address request pending*/
1741   if (NULL == cur)
1742   {
1743     GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1744                "Nobody is interested in peer `%s' :(\n",
1745                GNUNET_i2s (&address->peer));
1746     return;
1747   }
1748
1749   if ((0 == address->assigned_bw_in) && (0 == address->assigned_bw_out))
1750   {
1751     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1752                "Telling transport to disconnect peer `%s'\n",
1753                 GNUNET_i2s (&address->peer));
1754
1755     /* Notify scheduling clients about suggestion */
1756     GAS_scheduling_transmit_address_suggestion (&address->peer,
1757                                                 address->session_id,
1758                                                 GNUNET_BANDWIDTH_value_init (0),
1759                                                 GNUNET_BANDWIDTH_value_init (0));
1760     return;
1761   }
1762
1763   /* Do bandwidth stability check */
1764   diff_out = abs (address->assigned_bw_out - address->last_notified_bw_out);
1765   diff_in = abs (address->assigned_bw_in - address->last_notified_bw_in);
1766
1767   if ( (diff_out < htonl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) &&
1768        (diff_in < htonl(GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)) )
1769     return;
1770
1771   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1772       "Sending bandwidth update for peer `%s': %u %u\n",
1773       GNUNET_i2s (&address->peer), address->assigned_bw_out,
1774       address->assigned_bw_out);
1775
1776   /* *Notify scheduling clients about suggestion */
1777   GAS_scheduling_transmit_address_suggestion (&address->peer,
1778                                               address->session_id,
1779                                               GNUNET_BANDWIDTH_value_init (address->assigned_bw_out),
1780                                               GNUNET_BANDWIDTH_value_init (address->assigned_bw_in));
1781
1782   address->last_notified_bw_out = address->assigned_bw_out;
1783   address->last_notified_bw_in = address->assigned_bw_in;
1784 }
1785
1786
1787 /**
1788  * Initialize address subsystem. The addresses subsystem manages the addresses
1789  * known and current performance information. It has a solver component
1790  * responsible for the resource allocation. It tells the solver about changes
1791  * and receives updates when the solver changes the resource allocation.
1792  *
1793  * @param cfg configuration to use
1794  * @param stats_ the statistics handle to use
1795  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error (failed to load
1796  *         solver plugin)
1797  */
1798 int
1799 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1800                     struct GNUNET_STATISTICS_Handle *stats_)
1801 {
1802   unsigned long long quotas_in[GNUNET_ATS_NetworkTypeCount];
1803   unsigned long long quotas_out[GNUNET_ATS_NetworkTypeCount];
1804   char *mode_str;
1805   char *plugin_short;
1806   int c;
1807
1808   running = GNUNET_NO;
1809   stats = stats_;
1810   /* Initialize the addresses database */
1811   addresses = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
1812   pref_clients = 0;
1813
1814   /* Figure out configured solution method */
1815   if (GNUNET_SYSERR ==
1816       GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1817   {
1818     GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1819                "No resource assignment method configured, using proportional approach\n");
1820     ats_mode = MODE_PROPORTIONAL;
1821   }
1822   else
1823   {
1824     for (c = 0; c < strlen (mode_str); c++)
1825       mode_str[c] = toupper (mode_str[c]);
1826     if (0 == strcmp (mode_str, "PROPORTIONAL"))
1827       ats_mode = MODE_PROPORTIONAL;
1828     else if (0 == strcmp (mode_str, "MLP"))
1829     {
1830       ats_mode = MODE_MLP;
1831 #if !HAVE_LIBGLPK
1832       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1833                  "Assignment method `%s' configured, but GLPK is not available, please install \n",
1834                  mode_str);
1835       ats_mode = MODE_PROPORTIONAL;
1836 #endif
1837     }
1838     else if (0 == strcmp (mode_str, "RIL"))
1839       ats_mode = MODE_RIL;
1840     else
1841     {
1842       GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1843                  "Invalid resource assignment method `%s' configured, using proportional approach\n",
1844                  mode_str);
1845       ats_mode = MODE_PROPORTIONAL;
1846     }
1847     GNUNET_free(mode_str);
1848   }
1849
1850   load_quotas (cfg, quotas_out, quotas_in, GNUNET_ATS_NetworkTypeCount);
1851   env.info_cb = &solver_info_cb;
1852   env.info_cb_cls = NULL;
1853   env.bandwidth_changed_cb = &bandwidth_changed_cb;
1854   env.bw_changed_cb_cls = NULL;
1855   env.get_preferences = &get_preferences_cb;
1856   env.get_preference_cls = NULL;
1857   env.get_property = &get_property_cb;
1858   env.get_property_cls = NULL;
1859   env.cfg = cfg;
1860   env.stats = stats;
1861   env.addresses = addresses;
1862
1863   env.network_count = GNUNET_ATS_NetworkTypeCount;
1864   int networks[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1865   for (c = 0; c < GNUNET_ATS_NetworkTypeCount; c++)
1866   {
1867     env.networks[c] = networks[c];
1868     env.out_quota[c] = quotas_out[c];
1869     env.in_quota[c] = quotas_in[c];
1870   }
1871
1872   switch (ats_mode) {
1873     case MODE_PROPORTIONAL:
1874       plugin_short = "proportional";
1875       break;
1876     case MODE_MLP:
1877       plugin_short = "mlp";
1878       break;
1879     case MODE_RIL:
1880       plugin_short = "ril";
1881       break;
1882     default:
1883       plugin_short = NULL;
1884       break;
1885   }
1886   GNUNET_asprintf (&plugin,
1887                    "libgnunet_plugin_ats_%s",
1888                    plugin_short);
1889   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
1890              _("Initializing solver `%s '`%s'\n"),
1891              plugin_short,
1892              plugin);
1893   if (NULL == (solver = GNUNET_PLUGIN_load (plugin, &env)))
1894   {
1895     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1896                 _("Failed to initialize solver `%s'!\n"),
1897                 plugin);
1898     return GNUNET_SYSERR;
1899   }
1900
1901   GNUNET_assert (NULL != env.sf.s_add);
1902   GNUNET_assert (NULL != env.sf.s_address_update_inuse);
1903   GNUNET_assert (NULL != env.sf.s_address_update_property);
1904   GNUNET_assert (NULL != env.sf.s_address_update_session);
1905   GNUNET_assert (NULL != env.sf.s_address_update_network);
1906   GNUNET_assert (NULL != env.sf.s_get);
1907   GNUNET_assert (NULL != env.sf.s_get_stop);
1908   GNUNET_assert (NULL != env.sf.s_pref);
1909   GNUNET_assert (NULL != env.sf.s_feedback);
1910   GNUNET_assert (NULL != env.sf.s_del);
1911   GNUNET_assert (NULL != env.sf.s_bulk_start);
1912   GNUNET_assert (NULL != env.sf.s_bulk_stop);
1913
1914
1915   GAS_normalization_start (&normalized_preference_changed_cb, NULL,
1916                            &normalized_property_changed_cb, NULL);
1917
1918   if (NULL == solver)
1919   {
1920     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1921                 _("Failed to initialize solver!\n"));
1922     return GNUNET_SYSERR;
1923   }
1924   /* up and running */
1925   running = GNUNET_YES;
1926
1927   GNUNET_STATISTICS_set (stats,
1928                          "# addresses",
1929                          GNUNET_CONTAINER_multipeermap_size (addresses),
1930                          GNUNET_NO);
1931
1932   return GNUNET_OK;
1933 }
1934
1935
1936 /**
1937  * Destroy all addresses iterator
1938  *
1939  * @param cls NULL
1940  * @param key peer identity (unused)
1941  * @param value the 'struct ATS_Address' to free
1942  * @return #GNUNET_OK (continue to iterate)
1943  */
1944 static int
1945 destroy_all_address_it (void *cls,
1946                         const struct GNUNET_PeerIdentity *key,
1947                         void *value)
1948 {
1949   struct ATS_Address *aa = value;
1950
1951   /* Remove */
1952   GNUNET_assert(GNUNET_YES ==
1953                 GNUNET_CONTAINER_multipeermap_remove (addresses,
1954                                                       key,
1955                                                       value));
1956   /* Notify */
1957   env.sf.s_del (solver, aa, GNUNET_NO);
1958   /* Destroy */
1959   GAS_performance_notify_all_clients (&aa->peer,
1960                                       aa->plugin,
1961                                       aa->addr,
1962                                       aa->addr_len,
1963                                       GNUNET_NO,
1964                                       NULL, 0,
1965                                       zero_bw,
1966                                       zero_bw);
1967   free_address (aa);
1968   return GNUNET_OK;
1969 }
1970
1971
1972 /**
1973  * Remove all addresses
1974  */
1975 void
1976 GAS_addresses_destroy_all ()
1977 {
1978   if (GNUNET_NO == running)
1979     return;
1980
1981   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1982               "Destroying all addresses\n");
1983   env.sf.s_bulk_start (solver);
1984   if (NULL != addresses)
1985     GNUNET_CONTAINER_multipeermap_iterate (addresses,
1986                                            &destroy_all_address_it,
1987                                            NULL);
1988   env.sf.s_bulk_start (solver);
1989 }
1990
1991
1992 /**
1993  * Shutdown address subsystem.
1994  */
1995 void
1996 GAS_addresses_done ()
1997 {
1998   struct GAS_Addresses_Suggestion_Requests *cur;
1999   struct GAS_Addresses_Preference_Clients *pcur;
2000
2001   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
2002              "Shutting down addresses\n");
2003  GAS_addresses_destroy_all ();
2004   running = GNUNET_NO;
2005   GNUNET_CONTAINER_multipeermap_destroy (addresses);
2006   addresses = NULL;
2007   while (NULL != (cur = pending_requests_head))
2008   {
2009     GNUNET_CONTAINER_DLL_remove (pending_requests_head,
2010                                  pending_requests_tail,
2011                                  cur);
2012     GNUNET_free(cur);
2013   }
2014
2015   while (NULL != (pcur = preference_clients_head))
2016   {
2017     GNUNET_CONTAINER_DLL_remove (preference_clients_head,
2018                                  preference_clients_tail,
2019                                  pcur);
2020     GNUNET_assert (pref_clients > 0);
2021     pref_clients --;
2022     GNUNET_STATISTICS_set (stats,
2023                            "# active performance clients",
2024                            pref_clients,
2025                            GNUNET_NO);
2026     GNUNET_free (pcur);
2027   }
2028   GNUNET_PLUGIN_unload (plugin,
2029                         solver);
2030   GNUNET_free (plugin);
2031   /* Stop configured solution method */
2032   GAS_normalization_stop ();
2033 }
2034
2035
2036 /**
2037  * Closure for #peerinfo_it().
2038  */
2039 struct PeerInfoIteratorContext
2040 {
2041   /**
2042    * Function to call for each address.
2043    */
2044   GNUNET_ATS_PeerInfo_Iterator it;
2045
2046   /**
2047    * Closure for @e it.
2048    */
2049   void *it_cls;
2050 };
2051
2052
2053 /**
2054  * Iterator to iterate over a peer's addresses
2055  *
2056  * @param cls a `struct PeerInfoIteratorContext`
2057  * @param key the peer id
2058  * @param value the `struct ATS_address`
2059  * @return #GNUNET_OK to continue
2060  */
2061 static int
2062 peerinfo_it (void *cls,
2063              const struct GNUNET_PeerIdentity *key,
2064              void *value)
2065 {
2066   struct PeerInfoIteratorContext *pi_ctx = cls;
2067   struct ATS_Address *addr = value;
2068
2069   pi_ctx->it (pi_ctx->it_cls,
2070               &addr->peer,
2071               addr->plugin,
2072               addr->addr,
2073               addr->addr_len,
2074               addr->active,
2075               addr->atsi, addr->atsi_count,
2076               GNUNET_BANDWIDTH_value_init (addr->assigned_bw_out),
2077               GNUNET_BANDWIDTH_value_init (addr->assigned_bw_in));
2078   return GNUNET_OK;
2079 }
2080
2081
2082 /**
2083  * Return information all peers currently known to ATS
2084  *
2085  * @param peer the respective peer, NULL for 'all' peers
2086  * @param pi_it the iterator to call for every peer
2087  * @param pi_it_cls the closure for @a pi_it
2088  */
2089 void
2090 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer,
2091                              GNUNET_ATS_PeerInfo_Iterator pi_it,
2092                              void *pi_it_cls)
2093 {
2094   struct PeerInfoIteratorContext pi_ctx;
2095
2096   if (NULL == pi_it)
2097   {
2098     /* does not make sense without callback */
2099     GNUNET_break (0);
2100     return;
2101   }
2102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2103               "Returning information for %s from a total of %u known addresses\n",
2104               (NULL == peer)
2105               ? "all peers"
2106               : GNUNET_i2s (peer),
2107               (unsigned int) GNUNET_CONTAINER_multipeermap_size (addresses));
2108   pi_ctx.it = pi_it;
2109   pi_ctx.it_cls = pi_it_cls;
2110   if (NULL == peer)
2111     GNUNET_CONTAINER_multipeermap_iterate (addresses,
2112                                            &peerinfo_it,
2113                                            &pi_ctx);
2114   else
2115     GNUNET_CONTAINER_multipeermap_get_multiple (addresses,
2116                                                 peer,
2117                                                 &peerinfo_it, &pi_ctx);
2118   pi_it (pi_it_cls,
2119          NULL, NULL, NULL, 0,
2120          GNUNET_NO,
2121          NULL, 0,
2122          zero_bw,
2123          zero_bw);
2124 }
2125
2126 /* end of gnunet-service-ats_addresses.c */