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