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