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