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