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