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