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