address was no set to inactive
[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-service-ats.h"
30 #include "gnunet-service-ats_addresses.h"
31 #include "gnunet-service-ats_normalization.h"
32 #include "gnunet-service-ats_performance.h"
33 #include "gnunet-service-ats_scheduling.h"
34 #include "gnunet-service-ats_reservations.h"
35 #if HAVE_LIBGLPK
36 #include "gnunet-service-ats-solver_mlp.h"
37 #endif
38 #include "gnunet-service-ats-solver_proportional.h"
39 #include "gnunet-service-ats-solver_ril.h"
40
41 /**
42  * NOTE: Do not change this documentation. This documentation is based on
43  * gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
44  * use build_txt.sh to generate plaintext output
45  *
46  *   1 ATS addresses : ATS address management
47  *
48  *    This ATS addresses ("addresses") component manages the addresses known to
49  *    ATS service and suggests addresses to transport service when it is
50  *    interested in address suggestion for a peer. ATS addresses also
51  *    instantiates the bandwidth assignment mechanism (solver), notifies it
52  *    about changes to addresses and forwards changes to bandwidth assignments
53  *    to transport, depending if transport is interested in this change.
54  *
55  *     1.1 Input data
56  *
57  *       1.1.1 Addresses
58  *
59  *    Addresses are added by specifying peer ID, plugin, address, address length
60  *    and session, if available. ATS information can be specified if available.
61  *
62  *       1.1.2 Networks
63  *
64  *    ATS specifies a fix set of networks an address can belong to. For each
65  *    network an inbound and outbound quota will be specified. The available
66  *    networks and addtional helper varaibles are defined in
67  *    gnunet_ats_service.h. At the moment 5 networks are defined:
68  *      * GNUNET_ATS_NET_UNSPECIFIED
69  *      * GNUNET_ATS_NET_LOOPBACK
70  *      * GNUNET_ATS_NET_LAN
71  *      * GNUNET_ATS_NET_WAN
72  *      * GNUNET_ATS_NET_WLAN
73  *
74  *    The total number of networks defined is stored in
75  *    GNUNET_ATS_NetworkTypeCount GNUNET_ATS_NetworkType can be used array
76  *    initializer for an int array, while GNUNET_ATS_NetworkType is an
77  *    initializer for a char array containing a string description of all
78  *    networks
79  *
80  *       1.1.3 Quotas
81  *
82  *    An inbound and outbound quota for each of the networks mentioned in 1.1.2
83  *    is loaded from ats configuration during initialization. This quota defines
84  *    to total amount of inbound and outbound traffic allowed for a specific
85  *    network. The configuration values used are in section ats:
86  *      * "NETWORK"_QUOTA_IN = <value>
87  *      * "NETWORK"_QUOTA_IN = <value>
88  *
89  *    You can specify quotas by setting the <value> to a:
90  *      * unrestricted: unlimited
91  *      * number of bytes: e.g. 10240
92  *      * fancy value: e.g. 64 Kib
93  *
94  *    unlimited is defined as GNUNET_ATS_MaxBandwidthString and equivalent to
95  *    the value GNUNET_ATS_MaxBandwidth Important predefined values for quotas
96  *    are:
97  *      * GNUNET_ATS_DefaultBandwidth: 65536
98  *      * GNUNET_ATS_MaxBandwidth: UINT32_MAX
99  *      * GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT: 1024
100  *
101  *    Details of loading quotas and default values will be described on
102  *
103  *       1.1.4 Preference values
104  *
105  *     1.2 Data structures used
106  *
107  *    Addresse uses struct ATS_Address for each address. The structs are stored
108  *    in a linked list and provides a pointer void *solver_information for the
109  *    solver to store address specific information. It provides the int values
110  *    active which is set to GNUNET_YES if the address is select for transport
111  *    use and used, representing that transport service is actively using this
112  *    address. Address information are stored in peer, addr, addr_len, plugin.
113  *
114  *     1.3 Initialization
115  *
116  *    During initialization a hashmap to store addresses is created. The quotas
117  *    for all networks defined for ATS are loaded from configuration. For each
118  *    network first the logic will check if the string
119  *    GNUNET_ATS_MaxBandwidthString is configured, if not it will try to convert
120  *    the configured value as a fancy size and if this fails it will try to use
121  *    it as a value_number. If no configuration value is found it will assign
122  *    GNUNET_ATS_DefaultBandwidth. The most important step is to load the
123  *    configured solver using configuration "[ats]:MODE". Current solvers are
124  *    MODE_PROPORTIONAL, MODE_MLP. Interaction is done using a solver API
125  *
126  *     1.4 Solver API
127  *
128  *    Solver functions:
129  *      * s_init: init the solver with required information
130  *      * s_add: add a new address
131  *      * s_update: update ATS values or session for an address
132  *      * s_get: get prefered address for a peer
133  *      * s_del: delete an address
134  *      * s_pref: change preference value for a peer
135  *      * s_done: shutdown solver
136  *
137  *    Callbacks: addresses provides a bandwidth_changed_cb callback to the
138  *    solver which is called when bandwidth assigned to peer has changed
139  *
140  *     1.5 Shutdown
141  *
142  *    During shutdown all addresses are freed and the solver told to shutdown
143  *
144  *     1.6 Addresses and sessions
145  *
146  *    Addresses consist of the address itself and a numerical session. When a
147  *    new address without a session is added it has no session, so it gets
148  *    session 0 assigned. When an address with a session is added and an address
149  *    object with session 0 is found, this object is updated with the session
150  *    otherwise a new address object with this session assigned is created.
151  *
152  *       1.6.1 Terminology
153  *
154  *    Addresses a1,a2 with session s1, s2 are "exact" if:
155  *    (a1 == a2)&&(s1 == s2)
156  *    Addresses a1,a2 with session s1, s2 are "equivalent" if:
157  *    (a1 == a2)&&((s1 == s2)||(s1 == 0)||(s2 == 0)
158  *
159  *     1.7 Address management
160  *
161  *    Transport service notifies ATS about changes to the addresses known to
162  *    him.
163  *
164  *       1.7.1 Adding an address
165  *
166  *    When transport learns a new address it tells ATS and ATS is telling
167  *    addresses about it using GAS_address_add. If not known to addresses it
168  *    creates a new address object and calls solver's s_add. ATS information are
169  *    deserialized and solver is notified about the session and ATS information
170  *    using s_update.
171  *
172  *       1.7.2 Updating an address
173  *
174  *    Addresses does an lookup up for the existing address with the given
175  *    session. If disassembles included ATS information and notifies the solver
176  *    using s_update about the update.
177  *
178  *       1.7.3 Deleting an address
179  *
180  *    Addresses does an lookup for the exact address and session and if removes
181  *    this address. If session != 0 the session is set to 0 and the address is
182  *    kept. If session == 0, the addresses is removed.
183  *
184  *       1.7.4 Requesting an address suggestion
185  *
186  *    The address client issues a request address message to be notified about
187  *    address suggestions for a specific peer. Addresses asks the solver with
188  *    s_get. If no address is available, it will not send a response, otherwise
189  *    it will respond with the choosen address.
190  *
191  *       1.7.5 Address suggestions
192  *
193  *    Addresses will notify the client automatically on any bandwidth_changed_cb
194  *    by the solver if a address suggestion request is pending. If no address is
195  *    available it will not respond at all If the client is not interested
196  *    anymore, it has to cancel the address suggestion request.
197  *
198  *       1.7.6 Suggestions blocks and reset
199  *
200  *    After suggesting an address it is blocked for ATS_BLOCKING_DELTA sec. to
201  *    prevent the client from being thrashed. If the client requires immediately
202  *    it can reset this block using GAS_addresses_handle_backoff_reset.
203  *
204  *       1.7.7 Marking address in use
205  *
206  *    The client can notify addresses that it successfully uses an address and
207  *    wants this address to be kept by calling GSA_address_in_use. Adresses will
208  *    mark the address as used an notify the solver about the use.
209  *
210  *       1.7.8 Address lifecycle
211  *
212  *      * (add address)
213  *      * (updated address) || (address in use)
214  *      * (delete address)
215  *
216  *     1.8 Bandwidth assignment
217  *
218  *    The addresses are used to perform resource allocation operations. ATS
219  *    addresses takes care of instantiating the solver configured and notifies
220  *    the respective solver about address changes and receives changes to the
221  *    bandwidth assignment from the solver. The current bandwidth assignment is
222  *    sent to transport. The specific solvers will be described in the specific
223  *    section.
224  *
225  *     1.9 Changing peer preferences
226  *
227  *    The bandwidth assigned to a peer can be influenced by setting a preference
228  *    for a peer. The prefernce will be given to to the solver with s_pref which
229  *    has to take care of the preference value
230
231  */
232
233
234 /**
235  * Available ressource assignment modes
236  */
237 enum ATS_Mode
238 {
239   /*
240    * proportional mode:
241    *
242    * Assign each peer an equal amount of bandwidth (bw)
243    *
244    * bw_per_peer = bw_total / #active addresses
245    */
246   MODE_PROPORTIONAL,
247
248   /*
249    * MLP mode:
250    *
251    * Solve ressource assignment as an optimization problem
252    * Uses an mixed integer programming solver
253    */
254   MODE_MLP,
255
256   /*
257    * Reinforcement Learning mode:
258    *
259    * Solve resource assignment using a learning agent
260    */
261   MODE_RIL
262 };
263
264
265 /**
266  * Pending Address suggestion requests
267  */
268 struct GAS_Addresses_Suggestion_Requests
269 {
270   /**
271    * Next in DLL
272    */
273   struct GAS_Addresses_Suggestion_Requests *next;
274
275   /**
276    * Previous in DLL
277    */
278   struct GAS_Addresses_Suggestion_Requests *prev;
279
280   /**
281    * Peer ID
282    */
283   struct GNUNET_PeerIdentity id;
284 };
285
286
287 /**
288  * Handle for ATS address component
289  */
290 struct GAS_Addresses_Handle
291 {
292   /**
293    *
294    */
295   struct GNUNET_STATISTICS_Handle *stat;
296
297   /**
298    * A multihashmap to store all addresses
299    */
300   struct GNUNET_CONTAINER_MultiHashMap *addresses;
301
302   /**
303    * Configure WAN quota in
304    */
305   unsigned long long wan_quota_in;
306
307   /**
308    * Configure WAN quota out
309    */
310   unsigned long long wan_quota_out;
311
312   /**
313    * Is ATS addresses running
314    */
315   int running;
316
317   /**
318    * Configured ATS solver
319    */
320   int ats_mode;
321
322   /**
323    *  Solver handle
324    */
325   void *solver;
326
327   /**
328    * Address suggestion requests DLL head
329    */
330   struct GAS_Addresses_Suggestion_Requests *r_head;
331
332   /**
333    * Address suggestion requests DLL tail
334    */
335   struct GAS_Addresses_Suggestion_Requests *r_tail;
336
337   /* Solver functions */
338
339   /**
340    * Initialize solver
341    */
342   GAS_solver_init s_init;
343
344   /**
345    * Add an address to the solver
346    */
347   GAS_solver_address_add s_add;
348
349
350   GAS_solver_address_property_changed s_address_update_property;
351
352   GAS_solver_address_session_changed s_address_update_session;
353
354   GAS_solver_address_inuse_changed s_address_update_inuse;
355
356   GAS_solver_address_network_changed s_address_update_network;
357
358   /**
359    * Get address from solver
360    */
361   GAS_solver_get_preferred_address s_get;
362
363   /**
364    * Get address from solver
365    */
366   GAS_solver_stop_get_preferred_address s_get_stop;
367
368   /**
369    * Delete address in solver
370    */
371   GAS_solver_address_delete s_del;
372
373   /**
374    * Change relative preference for quality in solver
375    */
376   GAS_solver_address_change_preference s_pref;
377
378   /**
379    * Give feedback about the current assignment
380    */
381   GAS_solver_address_feedback_preference s_feedback;
382
383   /**
384    * Start a bulk operation
385    */
386   GAS_solver_bulk_start s_bulk_start;
387
388   /**
389    * Bulk operation done
390    */
391   GAS_solver_bulk_stop s_bulk_stop;
392
393   /**
394    * Shutdown solver
395    */
396   GAS_solver_done s_done;
397 };
398
399
400 /**
401  * Disassemble ATS information and update performance information in address
402  *
403  * Updates existing information and adds new information
404  *
405  * @param dest destination address
406  * @param update source ATS information
407  * @param update_count number of ATS information
408  * @param delta_dest ats performance information which were updated
409  *                              including previous value
410  * @param delta_count number of ATS information in the delta
411  * @return GNUNET_YES if address was address updated, GNUNET_NO otherwise
412  */
413 static unsigned int
414 disassemble_ats_information (struct ATS_Address *dest,
415                                                                                                                  const struct GNUNET_ATS_Information *update,
416                              uint32_t update_count,
417                              struct GNUNET_ATS_Information **delta_dest,
418                              uint32_t *delta_count)
419 {
420
421   int c1;
422   int c2;
423   int found;
424   int change;
425
426   struct GNUNET_ATS_Information add_atsi[update_count];
427   struct GNUNET_ATS_Information delta_atsi[update_count];
428   struct GNUNET_ATS_Information *tmp_atsi;
429   uint32_t add_atsi_count;
430   uint32_t delta_atsi_count;
431
432   change = GNUNET_NO;
433   add_atsi_count = 0;
434   delta_atsi_count = 0;
435
436   if (0 == update_count)
437         return GNUNET_NO;
438
439   if (NULL == dest->atsi)
440   {
441                 /* Create performance information */
442                 dest->atsi = GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
443                 dest->atsi_count = update_count;
444                 memcpy (dest->atsi, update, update_count * sizeof (struct GNUNET_ATS_Information));
445                 (*delta_dest) = GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
446                 for (c1 = 0; c1 < update_count; c1 ++)
447                 {
448                         (*delta_dest)[c1].type = update[c1].type;
449                         (*delta_dest)[c1].value = htonl(GNUNET_ATS_VALUE_UNDEFINED);
450                 }
451                 (*delta_count) = update_count;
452                 return GNUNET_YES;
453   }
454
455   for (c1 = 0; c1 < update_count; c1++)
456   {
457         /* Update existing performance information */
458         found = GNUNET_NO;
459         for (c2 = 0; c2 < dest->atsi_count; c2++)
460         {
461                         if (update[c1].type == dest->atsi[c2].type)
462                         {
463                                 if (update[c1].value != dest->atsi[c2].value)
464                                 {
465                                                 /* Save previous value in delta */
466                                                 delta_atsi[delta_atsi_count] = dest->atsi[c2];
467                                                 delta_atsi_count ++;
468                                                 /* Set new value */
469                                                 dest->atsi[c2].value = update[c1].value;
470                                                 change = GNUNET_YES;
471                                 }
472                                 found = GNUNET_YES;
473                                 break;
474                         }
475         }
476                 if (GNUNET_NO == found)
477                 {
478                                 add_atsi[add_atsi_count] = update[c1];
479                                 add_atsi_count ++;
480                                 delta_atsi[delta_atsi_count].type = update[c1].type;
481                                 delta_atsi[delta_atsi_count].value = htonl (GNUNET_ATS_VALUE_UNDEFINED);
482                                 delta_atsi_count ++;
483                 }
484   }
485
486   if (add_atsi_count > 0)
487   {
488                 /* Extend ats performance information */
489
490                 tmp_atsi = GNUNET_malloc ((dest->atsi_count + add_atsi_count) *
491                                                                                                                         (sizeof (struct GNUNET_ATS_Information)));
492                 memcpy (tmp_atsi, dest->atsi, dest->atsi_count * sizeof (struct GNUNET_ATS_Information));
493                 memcpy (&tmp_atsi[dest->atsi_count], add_atsi, add_atsi_count * sizeof (struct GNUNET_ATS_Information));
494                 GNUNET_free (dest->atsi);
495                 dest->atsi = tmp_atsi;
496                 dest->atsi_count = dest->atsi_count + add_atsi_count;
497                         change = GNUNET_YES;
498   }
499
500   if (delta_atsi_count > 0)
501   {
502                 /* Copy delta */
503                 (*delta_dest) = GNUNET_malloc (delta_atsi_count * sizeof (struct GNUNET_ATS_Information));
504                 memcpy ((*delta_dest), delta_atsi, delta_atsi_count * sizeof (struct GNUNET_ATS_Information));
505                 (*delta_count) = delta_atsi_count;
506   }
507
508   return change;
509 }
510
511 /**
512  * Free the given address
513  *
514  * @param addr address to destroy
515  */
516 static void
517 free_address (struct ATS_Address *addr)
518 {
519   GNUNET_free (addr->plugin);
520   GNUNET_free_non_null (addr->atsi);
521   GNUNET_free (addr);
522 }
523
524 /**
525  * Create a ATS_address with the given information
526  *
527  * @param peer peer
528  * @param plugin_name plugin
529  * @param plugin_addr address
530  * @param plugin_addr_len address length
531  * @param session_id session
532  * @return the ATS_Address
533  */
534 static struct ATS_Address *
535 create_address (const struct GNUNET_PeerIdentity *peer,
536                 const char *plugin_name,
537                 const void *plugin_addr, size_t plugin_addr_len,
538                 uint32_t session_id)
539 {
540   struct ATS_Address *aa = NULL;
541   int c1;
542   int c2;
543
544   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
545   aa->peer = *peer;
546   aa->addr_len = plugin_addr_len;
547   aa->addr = &aa[1];
548   memcpy (&aa[1], plugin_addr, plugin_addr_len);
549   aa->plugin = GNUNET_strdup (plugin_name);
550   aa->session_id = session_id;
551   aa->active = GNUNET_NO;
552   aa->used = GNUNET_NO;
553   aa->solver_information = NULL;
554   aa->atsi = NULL;
555   aa->atsi_count = 0;
556   aa->assigned_bw_in = GNUNET_BANDWIDTH_value_init(0);
557   aa->assigned_bw_out = GNUNET_BANDWIDTH_value_init(0);
558
559   for (c1 = 0; c1 < GNUNET_ATS_QualityPropertiesCount; c1 ++)
560   {
561         aa->atsin[c1].avg_queue_index = 0;
562         for (c2 = 0; c2 < GAS_normalization_queue_length; c2++)
563                 aa->atsin[c1].atsi_abs[c2] = GNUNET_ATS_VALUE_UNDEFINED;
564   }
565
566   return aa;
567 }
568
569
570 struct CompareAddressContext
571 {
572   const struct ATS_Address *search;
573
574   /* exact_address != NULL if address and session is equal */
575   struct ATS_Address *exact_address;
576   /* exact_address != NULL if address and session is 0 */
577   struct ATS_Address *base_address;
578 };
579
580 /**
581  * Comapre addresses
582  *
583  * @param cls a CompareAddressContext containin the source address
584  * @param key peer id
585  * @param value the address to compare with
586  * @return GNUNET_YES to continue, GNUNET_NO if address is founce
587  */
588
589 static int
590 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
591 {
592   struct CompareAddressContext *cac = cls;
593   struct ATS_Address *aa = value;
594
595   /* Find an matching exact address:
596    *
597    * Compare by:
598    * aa->addr_len == cac->search->addr_len
599    * aa->plugin == cac->search->plugin
600    * aa->addr == cac->search->addr
601    * aa->session == cac->search->session
602    *
603    * return as exact address
604    */
605   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
606   {
607       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
608         cac->exact_address = aa;
609   }
610
611   /* Find an matching base address:
612    *
613    * Properties:
614    *
615    * aa->session_id == 0
616    *
617    * Compare by:
618    * aa->addr_len == cac->search->addr_len
619    * aa->plugin == cac->search->plugin
620    * aa->addr == cac->search->addr
621    *
622    * return as base address
623    */
624   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
625   {
626       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == 0))
627         cac->base_address = aa;
628   }
629
630   /* Find an matching exact address based on session:
631    *
632    * Properties:
633    *
634    * cac->search->addr_len == 0
635    *
636    * Compare by:
637    * aa->plugin == cac->search->plugin
638    * aa->session_id == cac->search->session_id
639    *
640    * return as exact address
641    */
642   if (0 == cac->search->addr_len)
643   {
644       if ((0 == strcmp (aa->plugin, cac->search->plugin)) && (aa->session_id == cac->search->session_id))
645         cac->exact_address = aa;
646   }
647
648   if (cac->exact_address == NULL)
649     return GNUNET_YES; /* Continue iteration to find exact address */
650   else
651     return GNUNET_NO; /* Stop iteration since we have an exact address */
652 }
653
654
655 /**
656  * Find an existing equivalent address record.
657  * Compares by peer identity and network address OR by session ID
658  * (one of the two must match).
659  *
660  * @param handle the address handle
661  * @param peer peer to lookup addresses for
662  * @param addr existing address record
663  * @return existing address record, NULL for none
664  */
665 struct ATS_Address *
666 find_equivalent_address (struct GAS_Addresses_Handle *handle,
667                          const struct GNUNET_PeerIdentity *peer,
668                          const struct ATS_Address *addr)
669 {
670   struct CompareAddressContext cac;
671
672   cac.exact_address = NULL;
673   cac.base_address = NULL;
674   cac.search = addr;
675   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
676                                               &compare_address_it, &cac);
677
678   if (cac.exact_address == NULL)
679     return cac.base_address;
680   return cac.exact_address;
681 }
682
683
684 /**
685  * Find the exact address
686  *
687  * @param handle the address handle to use
688  * @param peer peer
689  * @param plugin_name transport plugin name
690  * @param plugin_addr plugin address
691  * @param plugin_addr_len length of the plugin address
692  * @param session_id session id, can be 0
693  * @return an ATS_address or NULL
694  */
695
696 static struct ATS_Address *
697 find_exact_address (struct GAS_Addresses_Handle *handle,
698                 const struct GNUNET_PeerIdentity *peer,
699                 const char *plugin_name,
700                 const void *plugin_addr,
701                 size_t plugin_addr_len,
702                 uint32_t session_id)
703 {
704   struct ATS_Address *aa;
705   struct ATS_Address *ea;
706
707   aa = create_address (peer,
708                        plugin_name,
709                        plugin_addr, plugin_addr_len,
710                        session_id);
711
712   /* Get existing address or address with session == 0 */
713   ea = find_equivalent_address (handle, peer, aa);
714   free_address (aa);
715   if (ea == NULL)
716     return NULL;
717   else if (ea->session_id != session_id)
718     return NULL;
719   return ea;
720 }
721
722
723 /**
724  * Extract an ATS performance info from an address
725  *
726  * @param address the address
727  * @param type the type to extract in HBO
728  * @return the value in HBO or GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
729  */
730 static int
731 get_performance_info (struct ATS_Address *address, uint32_t type)
732 {
733         int c1;
734         GNUNET_assert (NULL != address);
735
736         if ((NULL == address->atsi) || (0 == address->atsi_count))
737                         return GNUNET_ATS_VALUE_UNDEFINED;
738
739         for (c1 = 0; c1 < address->atsi_count; c1++)
740         {
741                         if (ntohl(address->atsi[c1].type) == type)
742                                 return ntohl(address->atsi[c1].value);
743         }
744         return GNUNET_ATS_VALUE_UNDEFINED;
745 }
746
747
748 /**
749  * Add a new address for a peer.
750  *
751  * @param handle the address handle to use
752  * @param peer peer
753  * @param plugin_name transport plugin name
754  * @param plugin_addr plugin address
755  * @param plugin_addr_len length of the plugin address
756  * @param session_id session id, can be 0
757  * @param atsi performance information for this address
758  * @param atsi_count number of performance information contained
759  */
760 void
761 GAS_addresses_add (struct GAS_Addresses_Handle *handle,
762                    const struct GNUNET_PeerIdentity *peer,
763                    const char *plugin_name,
764                    const void *plugin_addr,
765                    size_t plugin_addr_len,
766                    uint32_t session_id,
767                    const struct GNUNET_ATS_Information *atsi,
768                    uint32_t atsi_count)
769 {
770   struct ATS_Address *new_address;
771   struct ATS_Address *existing_address;
772   struct GNUNET_ATS_Information *atsi_delta;
773   uint32_t atsi_delta_count;
774   uint32_t addr_net;
775   uint32_t previous_session;
776   int c1;
777
778   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
779               "Received `%s' for peer `%s'\n",
780               "ADDRESS ADD",
781               GNUNET_i2s (peer));
782
783   if (GNUNET_NO == handle->running)
784     return;
785
786   GNUNET_assert (NULL != handle->addresses);
787
788   new_address = create_address (peer, plugin_name, plugin_addr, plugin_addr_len,
789                        session_id);
790   atsi_delta = NULL;
791   disassemble_ats_information (new_address, atsi, atsi_count, &atsi_delta, &atsi_delta_count);
792   GNUNET_free_non_null (atsi_delta);
793   addr_net = get_performance_info (new_address, GNUNET_ATS_NETWORK_TYPE);
794   if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
795                 addr_net = GNUNET_ATS_NET_UNSPECIFIED;
796
797   /* Get existing address or address with session == 0 */
798   existing_address = find_equivalent_address (handle, peer, new_address);
799   if (existing_address == NULL)
800   {
801     /* Add a new address */
802     GNUNET_assert (GNUNET_OK ==
803                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
804                       &peer->hashPubKey, new_address,
805                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
806
807     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Adding new address %p for peer `%s', length %u, session id %u, %s\n",
808                 new_address, GNUNET_i2s (peer), plugin_addr_len, session_id, GNUNET_ATS_print_network_type(addr_net));
809
810     /* Tell solver about new address */
811     handle->s_add (handle->solver, new_address, addr_net);
812
813     handle->s_bulk_start (handle->solver);
814     GAS_normalization_normalize_property (handle->addresses, new_address, atsi, atsi_count);
815     handle->s_bulk_stop (handle->solver);
816
817     /* Notify performance clients about new address */
818     GAS_performance_notify_all_clients (&new_address->peer,
819         new_address->plugin,
820         new_address->addr, new_address->addr_len,
821         new_address->session_id,
822         new_address->atsi, new_address->atsi_count,
823         new_address->assigned_bw_out,
824         new_address->assigned_bw_in);
825     return;
826   }
827
828   /* We have an existing address we can use, clean up new */
829   GNUNET_free (new_address->plugin);
830   GNUNET_free_non_null (new_address->atsi);
831   GNUNET_free (new_address);
832   new_address = NULL;
833
834   if (0 != existing_address->session_id)
835   {
836       /* Should not happen */
837       GNUNET_break (0);
838       return;
839   }
840
841   addr_net = get_performance_info (existing_address, GNUNET_ATS_NETWORK_TYPE);
842   if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
843                 addr_net = GNUNET_ATS_NET_UNSPECIFIED;
844
845   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
846            "Found existing address for peer `%s' %p with new session %u in network %s\n",
847            GNUNET_i2s (peer),
848            existing_address,
849            session_id,
850            GNUNET_ATS_print_network_type (addr_net));
851   /* We have an address without an session, update this address */
852   atsi_delta = NULL;
853   atsi_delta_count = 0;
854   if (GNUNET_YES == disassemble_ats_information (existing_address, atsi, atsi_count, &atsi_delta, &atsi_delta_count))
855   {
856         /* Notify performance clients about properties */
857                 GAS_performance_notify_all_clients (&existing_address->peer,
858                                 existing_address->plugin,
859                                 existing_address->addr, existing_address->addr_len,
860                                 existing_address->session_id,
861                                 existing_address->atsi, existing_address->atsi_count,
862                                 existing_address->assigned_bw_out,
863                                 existing_address->assigned_bw_in);
864
865                 for (c1 = 0; c1 < atsi_delta_count; c1++)
866                 {
867                         if ((GNUNET_ATS_NETWORK_TYPE == ntohl (atsi_delta[c1].type)) &&
868                                         (addr_net != ntohl (atsi_delta[c1].value)))
869                         {
870                                 /* Network type changed */
871                                 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Address for peer `%s' %p changed from network %s to %s\n",
872                    GNUNET_i2s (peer),
873                    existing_address,
874                    GNUNET_ATS_print_network_type (addr_net),
875                    GNUNET_ATS_print_network_type (ntohl (atsi_delta[c1].value)));
876                         handle->s_address_update_network (handle->solver, existing_address,
877                                         ntohl (atsi_delta[c1].value),
878                                         get_performance_info (existing_address, GNUNET_ATS_NETWORK_TYPE));
879                         addr_net = get_performance_info (existing_address, GNUNET_ATS_NETWORK_TYPE);
880                         }
881                 }
882
883                 /* Notify solver about update with atsi information and session */
884           handle->s_bulk_start (handle->solver);
885           GAS_normalization_normalize_property (handle->addresses, existing_address, atsi, atsi_count);
886           handle->s_bulk_stop (handle->solver);
887   }
888   GNUNET_free_non_null (atsi_delta);
889
890   /* Notify solver about new session */
891   if (existing_address->session_id == session_id)
892         return; /* possible, can both be 0 since address is revalidated */
893
894   previous_session = existing_address->session_id;
895   existing_address->session_id = session_id;
896   handle->s_address_update_session (handle->solver, existing_address,
897                 previous_session, session_id);
898
899   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
900            "Updated existing address for peer `%s' %p length %u with new session %u in network %s\n",
901            GNUNET_i2s (peer),
902            existing_address,
903            existing_address->addr_len,
904            session_id,
905            GNUNET_ATS_print_network_type(addr_net));
906 }
907
908
909 /**
910  * Update an address with a session or performance information for a peer.
911  *
912  * If an address was added without a session it will be updated with the
913  * session
914  *
915  * @param handle the address handle to use
916  * @param peer peer
917  * @param plugin_name transport plugin name
918  * @param plugin_addr plugin address
919  * @param plugin_addr_len length of the plugin address
920  * @param session_id session id, can be 0
921  * @param atsi performance information for this address
922  * @param atsi_count number of performance information contained
923  */
924 void
925 GAS_addresses_update (struct GAS_Addresses_Handle *handle,
926                       const struct GNUNET_PeerIdentity *peer,
927                       const char *plugin_name, const void *plugin_addr,
928                       size_t plugin_addr_len, uint32_t session_id,
929                       const struct GNUNET_ATS_Information *atsi,
930                       uint32_t atsi_count)
931 {
932   struct ATS_Address *aa;
933   struct GNUNET_ATS_Information *atsi_delta;
934   uint32_t atsi_delta_count;
935   uint32_t prev_session;
936   int c1;
937
938   if (GNUNET_NO == handle->running)
939     return;
940
941   GNUNET_assert (NULL != handle->addresses);
942
943   /* Get existing address */
944   aa = find_exact_address (handle, peer, plugin_name,
945                                                                                                  plugin_addr, plugin_addr_len, session_id);
946   if (aa == NULL)
947   {
948     /* GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n", */
949     /*             GNUNET_i2s (peer), plugin_name, session_id); */
950     /* GNUNET_break (0); */
951     return;
952   }
953
954   if (NULL == aa->solver_information)
955   {
956     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
957                  GNUNET_i2s (peer), plugin_name, session_id);
958     return;
959   }
960
961   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
962                 "Received `%s' for peer `%s' address \n",
963                 "ADDRESS UPDATE",
964                 GNUNET_i2s (peer), aa);
965
966   /* Update address */
967   if (session_id != aa->session_id)
968   {
969         /* Session changed */
970     prev_session = aa->session_id;
971     aa->session_id = session_id;
972     handle->s_address_update_session (handle->solver, aa, prev_session, aa->session_id);
973   }
974
975   atsi_delta = NULL;
976   atsi_delta_count = 0;
977   if (GNUNET_YES == disassemble_ats_information (aa, atsi, atsi_count, &atsi_delta, &atsi_delta_count))
978   {
979         /* ATS properties changed */
980         for (c1 = 0; c1 < atsi_delta_count; c1++)
981         {
982                 if (GNUNET_ATS_NETWORK_TYPE == ntohl (atsi_delta[c1].type))
983                 {
984                         /* Network type changed */
985                         handle->s_address_update_network (handle->solver, aa,
986                                         ntohl (atsi_delta[c1].value),
987                                         get_performance_info (aa, GNUNET_ATS_NETWORK_TYPE));
988                 }
989         }
990
991                 /* Notify performance clients about updated address */
992                 GAS_performance_notify_all_clients (&aa->peer,
993                                 aa->plugin,
994                                 aa->addr, aa->addr_len,
995                                 aa->session_id,
996                                 aa->atsi, aa->atsi_count,
997                                 aa->assigned_bw_out,
998                                 aa->assigned_bw_in);
999
1000                 handle->s_bulk_start (handle->solver);
1001                 GAS_normalization_normalize_property (handle->addresses, aa, atsi, atsi_count);
1002                 handle->s_bulk_stop (handle->solver);
1003   }
1004   GNUNET_free_non_null (atsi_delta);
1005 }
1006
1007
1008 struct DestroyContext
1009 {
1010   struct ATS_Address *aa;
1011
1012   struct GAS_Addresses_Handle *handle;
1013
1014   /**
1015    * GNUNET_NO  : full address
1016    * GNUNET_YES : just session
1017    */
1018   int result;
1019 };
1020
1021
1022 /**
1023  * Delete an address
1024  *
1025  * If session != 0, just the session is deleted, the address itself still exists
1026  * If session == 0, remove full address
1027  * If session == 0 and addrlen == 0, destroy inbound address
1028  *
1029  * @param cls unused
1030  * @param key unused
1031  * @param value the 'struct ATS_Address'
1032  * @return GNUNET_OK (continue to iterate)
1033  */
1034 static int
1035 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
1036 {
1037   struct DestroyContext *dc = cls;
1038   struct GAS_Addresses_Handle *handle = dc->handle;
1039   const struct ATS_Address *des = dc->aa;
1040   struct ATS_Address *aa = value;
1041
1042   GNUNET_assert (0 == memcmp (&aa->peer, &des->peer,
1043                               sizeof (struct GNUNET_PeerIdentity)));
1044
1045
1046   if (des->session_id == 0)
1047   {
1048     /* Session == 0, remove full address  */
1049     if ((0 == strcmp (des->plugin, aa->plugin)) &&
1050         (aa->addr_len == des->addr_len) &&
1051         (0 == memcmp (des->addr, aa->addr, aa->addr_len)))
1052     {
1053
1054       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1055                   "Deleting full address for peer `%s' session %u %p\n",
1056                   GNUNET_i2s (&aa->peer), aa->session_id, aa);
1057
1058       /* Notify solver about deletion */
1059       GNUNET_assert (GNUNET_YES ==
1060                 GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
1061                         &aa->peer.hashPubKey, aa));
1062       handle->s_del (handle->solver, aa, GNUNET_NO);
1063       free_address (aa);
1064       dc->result = GNUNET_NO;
1065       return GNUNET_OK; /* Continue iteration */
1066     }
1067   }
1068   else
1069   {
1070     /* Session != 0, just remove session */
1071     if (aa->session_id != des->session_id)
1072       return GNUNET_OK; /* irrelevant */
1073
1074     if ((aa->session_id != 0) &&
1075         (0 != strcmp (des->plugin, aa->plugin)))
1076     {
1077         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1078                     "Different plugins during removal: `%s' vs `%s' \n",
1079                     des->plugin, aa->plugin);
1080         GNUNET_break (0);
1081         return GNUNET_OK;
1082     }
1083
1084     if (aa->addr_len == 0)
1085     {
1086         /* Inbound connection died, delete full address */
1087         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1088                     "Deleting inbound address for peer `%s': `%s' session %u\n",
1089                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
1090
1091         /* Notify solver about deletion */
1092         GNUNET_assert (GNUNET_YES ==
1093                         GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
1094                         &aa->peer.hashPubKey, aa));
1095         handle->s_del (handle->solver, aa, GNUNET_NO);
1096         free_address (aa);
1097         dc->result = GNUNET_NO;
1098         return GNUNET_OK; /* Continue iteration */
1099     }
1100     else
1101     {
1102         /* Session died */
1103         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1104                     "Deleting session for peer `%s': `%s' %u\n",
1105                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
1106         /* Notify solver to delete session */
1107         handle->s_del (handle->solver, aa, GNUNET_YES);
1108         aa->session_id = 0;
1109         aa->active = GNUNET_NO;
1110         return GNUNET_OK;
1111     }
1112   }
1113   return GNUNET_OK;
1114 }
1115
1116
1117 /**
1118  * Remove an address or just a session for a peer.
1119  *
1120  * @param handle the address handle to use
1121  * @param peer peer
1122  * @param plugin_name transport plugin name
1123  * @param plugin_addr plugin address
1124  * @param plugin_addr_len length of the plugin address
1125  * @param session_id session id, can be 0
1126  */
1127 void
1128 GAS_addresses_destroy (struct GAS_Addresses_Handle *handle,
1129                        const struct GNUNET_PeerIdentity *peer,
1130                        const char *plugin_name,
1131                        const void *plugin_addr,
1132                        size_t plugin_addr_len,
1133                        uint32_t session_id)
1134 {
1135   struct ATS_Address *ea;
1136   struct DestroyContext dc;
1137   if (GNUNET_NO == handle->running)
1138     return;
1139
1140   /* Get existing address */
1141   ea = find_exact_address (handle, peer, plugin_name, plugin_addr,
1142                 plugin_addr_len, session_id);
1143   if (ea == NULL)
1144   {
1145     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
1146                 GNUNET_i2s (peer), plugin_name, session_id);
1147     return;
1148   }
1149
1150   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151               "Received `%s' for peer `%s' address %p session %u\n",
1152               "ADDRESS DESTROY",
1153               GNUNET_i2s (peer), ea, session_id);
1154
1155   GNUNET_break (0 < strlen (plugin_name));
1156   dc.handle = handle;
1157   dc.aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
1158
1159   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
1160                                               &destroy_by_session_id, &dc);
1161   free_address (dc.aa);
1162 }
1163
1164
1165 /**
1166  * Notification about active use of an address.
1167  * in_use == GNUNET_YES:
1168  *      This address is used to maintain an active connection with a peer.
1169  * in_use == GNUNET_NO:
1170  *      This address is no longer used to maintain an active connection with a peer.
1171  *
1172  * Note: can only be called with in_use == GNUNET_NO if called with GNUNET_YES
1173  * before
1174  *
1175  * @param handle the address handle to use
1176  * @param peer peer
1177  * @param plugin_name transport plugin name
1178  * @param plugin_addr plugin address
1179  * @param plugin_addr_len length of the plugin address
1180  * @param session_id session id, can be 0
1181  * @param in_use GNUNET_YES if GNUNET_NO
1182  * @return GNUNET_SYSERR on failure (address unknown ...)
1183  */
1184 int
1185 GAS_addresses_in_use (struct GAS_Addresses_Handle *handle,
1186                       const struct GNUNET_PeerIdentity *peer,
1187                       const char *plugin_name,
1188                       const void *plugin_addr,
1189                       size_t plugin_addr_len,
1190                       uint32_t session_id,
1191                       int in_use)
1192 {
1193   struct ATS_Address *ea;
1194   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                 "Received `%s' for peer `%s'\n",
1196                 "ADDRESS IN USE",
1197                 GNUNET_i2s (peer));
1198
1199   if (GNUNET_NO == handle->running)
1200     return GNUNET_SYSERR;
1201
1202   ea = find_exact_address (handle, peer, plugin_name,
1203                 plugin_addr, plugin_addr_len, session_id);
1204   if (NULL == ea)
1205   {
1206     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1207                 "Trying to set unknown address `%s' `%s' `%u' to %s \n",
1208                 GNUNET_i2s (peer),
1209                 plugin_name, session_id,
1210                 (GNUNET_NO == in_use) ? "NO" : "YES");
1211     GNUNET_break (0);
1212     return GNUNET_SYSERR;
1213   }
1214   if (ea->used == in_use)
1215   {
1216     GNUNET_break (0);
1217     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1218                 "Address in use called multiple times for peer `%s': %s -> %s \n",
1219                 GNUNET_i2s (peer),
1220                 (GNUNET_NO == ea->used) ? "NO" : "YES",
1221                 (GNUNET_NO == in_use) ? "NO" : "YES");
1222     return GNUNET_SYSERR;
1223   }
1224
1225   /* Tell solver about update */
1226   ea->used = in_use;
1227   handle->s_address_update_inuse (handle->solver, ea, ea->used);
1228   return GNUNET_OK;
1229 }
1230
1231
1232 /**
1233  * Cancel address suggestions for a peer
1234  *
1235  * @param handle the address handle
1236  * @param peer the peer id
1237  */
1238 void
1239 GAS_addresses_request_address_cancel (struct GAS_Addresses_Handle *handle,
1240                                       const struct GNUNET_PeerIdentity *peer)
1241 {
1242   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
1243
1244   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1245               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
1246
1247   while (NULL != cur)
1248   {
1249       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
1250         break; /* found */
1251       cur = cur->next;
1252   }
1253
1254   if (NULL == cur)
1255   {
1256       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1257                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
1258       return;
1259   }
1260   handle->s_get_stop (handle->solver, peer);
1261   GAS_addresses_handle_backoff_reset (handle, peer);
1262   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1263               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
1264   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1265   GNUNET_free (cur);
1266 }
1267
1268 /*
1269 static int
1270 addrinfo_it (void *cls, const struct GNUNET_HashCode *key, void *value)
1271 {
1272         static int count = 0;
1273         struct GNUNET_PeerIdentity *id = cls;
1274         struct ATS_Address *aa = value;
1275
1276   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1277               "[%u] Peer `%s' %s length %u session %u active %s\n",
1278               count, GNUNET_i2s (id), aa->plugin, aa->addr_len, aa->session_id,
1279               (GNUNET_YES == aa->active) ? "active" : "inactive");
1280
1281   count ++;
1282         return GNUNET_OK;
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->r_head;
1297   struct ATS_Address *aa;
1298
1299   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1300               "Received `%s' for peer `%s'\n",
1301               "REQUEST ADDRESS",
1302               GNUNET_i2s (peer));
1303
1304   if (GNUNET_NO == handle->running)
1305     return;
1306   while (NULL != cur)
1307   {
1308       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
1309         break; /* already suggesting */
1310       cur = cur->next;
1311   }
1312   if (NULL == cur)
1313   {
1314       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
1315       cur->id = (*peer);
1316       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
1317   }
1318
1319   /*
1320    * Debuging information about addresses
1321    *
1322    * GNUNET_CONTAINER_multihashmap_get_multiple(handle->addresses,
1323    *  &peer->hashPubKey, &addrinfo_it, (void *) peer);
1324    */
1325
1326   /* Get prefered address from solver */
1327   aa = (struct ATS_Address *) handle->s_get (handle->solver, peer);
1328   if (NULL == aa)
1329   {
1330     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1331                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
1332     return;
1333   }
1334
1335   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1336               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
1337
1338   GAS_scheduling_transmit_address_suggestion (peer,
1339                                               aa->plugin,
1340                                               aa->addr, aa->addr_len,
1341                                               aa->session_id,
1342                                               aa->atsi, aa->atsi_count,
1343                                               aa->assigned_bw_out,
1344                                               aa->assigned_bw_in);
1345
1346   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
1347   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), aa->block_interval);
1348
1349   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1350        "Address %p ready for suggestion, block interval now %llu \n",
1351        aa, aa->block_interval);
1352 }
1353
1354
1355 /**
1356  * Iterator to reset address blocking
1357  *
1358  * @param cls not used
1359  * @param key the peer
1360  * @param value the address to reset
1361  * @return GNUNET_OK to continue
1362  */
1363 static int
1364 reset_address_it (void *cls, const struct GNUNET_HashCode *key, void *value)
1365 {
1366   struct ATS_Address *aa = value;
1367
1368   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1369               "Resetting interval for peer `%s' address %p from %llu to 0\n",
1370               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
1371
1372   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
1373   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
1374   return GNUNET_OK;
1375 }
1376
1377
1378 /**
1379  * Reset suggestion backoff for a peer
1380  *
1381  * Suggesting addresses is blocked for ATS_BLOCKING_DELTA. Blocking can be
1382  * reset using this function
1383  *
1384  * @param handle the address handle
1385  * @param peer the peer id
1386  */
1387 void
1388 GAS_addresses_handle_backoff_reset (struct GAS_Addresses_Handle *handle,
1389                                     const struct GNUNET_PeerIdentity *peer)
1390 {
1391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1392               "Received `%s' for peer `%s'\n",
1393               "RESET BACKOFF",
1394               GNUNET_i2s (peer));
1395
1396   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
1397                                               &peer->hashPubKey,
1398                                               &reset_address_it,
1399                                               NULL));
1400 }
1401
1402
1403 /**
1404  * The preference changed for a peer
1405  *
1406  * @param cls the address handle
1407  * @param peer the peer
1408  * @param kind the ATS kind
1409  * @param pref_rel the new relative preference value
1410  */
1411 static void
1412 normalized_preference_changed_cb (void *cls,
1413                                                                   const struct GNUNET_PeerIdentity *peer,
1414                                                                   enum GNUNET_ATS_PreferenceKind kind,
1415                                                                   double pref_rel)
1416 {
1417         GNUNET_assert (NULL != cls);
1418         struct GAS_Addresses_Handle *handle = cls;
1419   /* Tell solver about update */
1420   handle->s_pref (handle->solver, peer, kind, pref_rel);
1421 }
1422
1423
1424 /**
1425  * The relative value for a property changed
1426  *
1427  * @param cls the address handle
1428  * @param address the peer
1429  * @param type the ATS type
1430  * @param prop_rel the new relative preference value
1431  */
1432 static void
1433 normalized_property_changed_cb (void *cls,
1434                                                                                                                   struct ATS_Address *address,
1435                                                                                                                   uint32_t type,
1436                                                                                                                   double prop_rel)
1437 {
1438         struct GAS_Addresses_Handle *ah = (struct GAS_Addresses_Handle *) cls;
1439         GNUNET_assert (NULL != ah);
1440
1441         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1442               "Normalized property %s for peer `%s' changed to %.3f \n",
1443               GNUNET_ATS_print_property_type (type),
1444               GNUNET_i2s (&address->peer),
1445               prop_rel);
1446
1447         ah->s_address_update_property (ah->solver,
1448                                                                                                                                 address,
1449                                                                                                                                 type,
1450                                                                                                                                 0,
1451                                                                                                                                 prop_rel);
1452 }
1453
1454
1455 /**
1456  * Function allowing the solver to obtain normalized preference
1457  * values from solver
1458  *
1459  * @param cls unused
1460  * @param id the peer to return the normalized properties for
1461  * @return array of double values with |GNUNET_ATS_PreferenceCount| elements
1462  */
1463 const double *
1464 get_preferences_cb (void *cls, const struct GNUNET_PeerIdentity *id)
1465 {
1466         return GAS_normalization_get_preferences (id);
1467 }
1468
1469 /**
1470  * Function allowing the solver to obtain normalized property
1471  * values for an address from solver
1472  *
1473  * @param cls unused
1474  * @param address the address
1475  * @return array of double values with |GNUNET_ATS_QualityPropertiesCount| elements
1476  */
1477 const double *
1478 get_property_cb (void *cls, const struct ATS_Address *address)
1479 {
1480         return GAS_normalization_get_properties ((struct ATS_Address *) address);
1481 }
1482
1483 /**
1484  * Change the preference for a peer
1485  *
1486  * @param handle the address handle
1487  * @param client the client sending this request
1488  * @param peer the peer id
1489  * @param kind the preference kind to change
1490  * @param score_abs the new preference score
1491  */
1492 void
1493 GAS_addresses_change_preference (struct GAS_Addresses_Handle *handle,
1494                                  void *client,
1495                                  const struct GNUNET_PeerIdentity *peer,
1496                                  enum GNUNET_ATS_PreferenceKind kind,
1497                                  float score_abs)
1498 {
1499         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1500               "Received `%s' for peer `%s' for client %p\n",
1501               "CHANGE PREFERENCE",
1502               GNUNET_i2s (peer), client);
1503
1504   if (GNUNET_NO == handle->running)
1505     return;
1506
1507   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->addresses,
1508                                                           &peer->hashPubKey))
1509   {
1510       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1511                   "Received `%s' for unknown peer `%s' from client %p\n",
1512                   "CHANGE PREFERENCE",
1513                   GNUNET_i2s (peer), client);
1514       return;
1515   }
1516
1517   handle->s_bulk_start (handle->solver);
1518   /* Tell normalization about change, normalization will call callback if preference changed */
1519   GAS_normalization_normalize_preference (client, peer, kind, score_abs);
1520   handle->s_bulk_stop (handle->solver);
1521 }
1522
1523
1524 /**
1525  * Change the preference for a peer
1526  *
1527  * @param handle the address handle
1528  * @param application the client sending this request
1529  * @param peer the peer id
1530  * @param scope the time interval for this feedback: [now - scope .. now]
1531  * @param kind the preference kind to change
1532  * @param score_abs the new preference score
1533  */
1534 void
1535 GAS_addresses_preference_feedback (struct GAS_Addresses_Handle *handle,
1536                                                                                                                                                 void *application,
1537                                                                                                                                                 const struct GNUNET_PeerIdentity *peer,
1538                                                                                                                                                 const struct GNUNET_TIME_Relative scope,
1539                                                                                                                                                 enum GNUNET_ATS_PreferenceKind kind,
1540                                                                                                                                                 float score_abs)
1541 {
1542         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1543               "Received `%s' for peer `%s' for client %p\n",
1544               "PREFERENCE FEEDBACK",
1545               GNUNET_i2s (peer), application);
1546
1547   if (GNUNET_NO == handle->running)
1548     return;
1549
1550   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->addresses,
1551                                                           &peer->hashPubKey))
1552   {
1553       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1554                   "Received `%s' for unknown peer `%s' from client %p\n",
1555                   "PREFERENCE FEEDBACK",
1556                   GNUNET_i2s (peer), application);
1557       return;
1558   }
1559
1560   handle->s_feedback (handle->solver, application, peer, scope, kind, score_abs);
1561 }
1562
1563
1564 /**
1565  * Load quotas for networks from configuration
1566  *
1567  * @param cfg configuration handle
1568  * @param out_dest where to write outbound quotas
1569  * @param in_dest where to write inbound quotas
1570  * @param dest_length length of inbound and outbound arrays
1571  * @return number of networks loaded
1572  */
1573 static unsigned int
1574 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
1575 {
1576   char *network_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1577   char * entry_in = NULL;
1578   char * entry_out = NULL;
1579   char * quota_out_str;
1580   char * quota_in_str;
1581   int c;
1582   int res;
1583
1584   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
1585   {
1586     in_dest[c] = 0;
1587     out_dest[c] = 0;
1588     GNUNET_asprintf (&entry_out, "%s_QUOTA_OUT", network_str[c]);
1589     GNUNET_asprintf (&entry_in, "%s_QUOTA_IN", network_str[c]);
1590
1591     /* quota out */
1592     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
1593     {
1594       res = GNUNET_NO;
1595       if (0 == strcmp(quota_out_str, GNUNET_ATS_MaxBandwidthString))
1596       {
1597         out_dest[c] = GNUNET_ATS_MaxBandwidth;
1598         res = GNUNET_YES;
1599       }
1600       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
1601         res = GNUNET_YES;
1602       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_out,  &out_dest[c])))
1603          res = GNUNET_YES;
1604
1605       if (GNUNET_NO == res)
1606       {
1607           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1608               network_str[c], quota_out_str, GNUNET_ATS_DefaultBandwidth);
1609           out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1610       }
1611       else
1612       {
1613           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Outbound quota configure for network `%s' is %llu\n"),
1614               network_str[c], out_dest[c]);
1615       }
1616       GNUNET_free (quota_out_str);
1617     }
1618     else
1619     {
1620       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"),
1621           network_str[c], GNUNET_ATS_DefaultBandwidth);
1622       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1623     }
1624
1625     /* quota in */
1626     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
1627     {
1628       res = GNUNET_NO;
1629       if (0 == strcmp(quota_in_str, GNUNET_ATS_MaxBandwidthString))
1630       {
1631         in_dest[c] = GNUNET_ATS_MaxBandwidth;
1632         res = GNUNET_YES;
1633       }
1634       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
1635         res = GNUNET_YES;
1636       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_in,  &in_dest[c])))
1637          res = GNUNET_YES;
1638
1639       if (GNUNET_NO == res)
1640       {
1641           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1642               network_str[c], quota_in_str, GNUNET_ATS_DefaultBandwidth);
1643           in_dest[c] = GNUNET_ATS_DefaultBandwidth;
1644       }
1645       else
1646       {
1647           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Inbound quota configured for network `%s' is %llu\n"),
1648               network_str[c], in_dest[c]);
1649       }
1650       GNUNET_free (quota_in_str);
1651     }
1652     else
1653     {
1654       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"),
1655           network_str[c], GNUNET_ATS_DefaultBandwidth);
1656       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1657     }
1658     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Loaded quota for network `%s' (in/out): %llu %llu\n", network_str[c], in_dest[c], out_dest[c]);
1659     GNUNET_free (entry_out);
1660     GNUNET_free (entry_in);
1661   }
1662   return GNUNET_ATS_NetworkTypeCount;
1663 }
1664
1665
1666 /**
1667  * Callback for solver to notify about assignment changes
1668  *
1669  * @param cls the GAS_Addresses_Handle
1670  * @param address the address with changes
1671  */
1672 static void
1673 bandwidth_changed_cb (void *cls, struct ATS_Address *address)
1674 {
1675   struct GAS_Addresses_Handle *handle = cls;
1676   struct GAS_Addresses_Suggestion_Requests *cur;
1677
1678   GNUNET_assert (handle != NULL);
1679   GNUNET_assert (address != NULL);
1680
1681   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Bandwidth assignment changed for peer %s \n", GNUNET_i2s(&address->peer));
1682
1683   /* Notify performance clients about changes to address */
1684   GAS_performance_notify_all_clients (&address->peer,
1685       address->plugin,
1686       address->addr, address->addr_len,
1687       address->session_id,
1688       address->atsi, address->atsi_count,
1689       address->assigned_bw_out,
1690       address->assigned_bw_in);
1691   cur = handle->r_head;
1692   while (NULL != cur)
1693   {
1694       if (0 == memcmp (&address->peer, &cur->id, sizeof (cur->id)))
1695         break; /* we have an address request pending*/
1696       cur = cur->next;
1697   }
1698   if (NULL == cur)
1699   {
1700       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1701                   "Nobody is interested in peer `%s' :(\n",GNUNET_i2s (&address->peer));
1702       return;
1703   }
1704
1705   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1706               "Sending bandwidth update for peer `%s'\n",GNUNET_i2s (&address->peer));
1707
1708   /* *Notify scheduling clients about suggestion */
1709   GAS_scheduling_transmit_address_suggestion (&address->peer,
1710                                               address->plugin,
1711                                               address->addr, address->addr_len,
1712                                               address->session_id,
1713                                               address->atsi, address->atsi_count,
1714                                               address->assigned_bw_out,
1715                                               address->assigned_bw_in);
1716 }
1717
1718
1719 /**
1720  * Initialize address subsystem. The addresses subsystem manages the addresses
1721  * known and current performance information. It has a solver component
1722  * responsible for the resource allocation. It tells the solver about changes
1723  * and receives updates when the solver changes the resource allocation.
1724  *
1725  * @param cfg configuration to use
1726  * @param stats the statistics handle to use
1727  * @return an address handle
1728  */
1729 struct GAS_Addresses_Handle *
1730 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1731                     const struct GNUNET_STATISTICS_Handle *stats)
1732 {
1733   struct GAS_Addresses_Handle *ah;
1734   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1735   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
1736   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
1737   int quota_count;
1738   char *mode_str;
1739   int c;
1740
1741   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
1742   ah->running = GNUNET_NO;
1743
1744   ah->stat = (struct GNUNET_STATISTICS_Handle *) stats;
1745   /* Initialize the addresses database */
1746   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1747   GNUNET_assert (NULL != ah->addresses);
1748
1749   /* Figure out configured solution method */
1750   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1751   {
1752       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No resource assignment method configured, using proportional approach\n");
1753       ah->ats_mode = MODE_PROPORTIONAL;
1754   }
1755   else
1756   {
1757       for (c = 0; c < strlen (mode_str); c++)
1758         mode_str[c] = toupper (mode_str[c]);
1759       if (0 == strcmp (mode_str, "PROPORTIONAL"))
1760       {
1761           ah->ats_mode = MODE_PROPORTIONAL;
1762       }
1763       else if (0 == strcmp (mode_str, "MLP"))
1764       {
1765           ah->ats_mode = MODE_MLP;
1766 #if !HAVE_LIBGLPK
1767           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not available, please install \n", mode_str);
1768           ah->ats_mode = MODE_PROPORTIONAL;
1769 #endif
1770       }
1771       else if (0 == strcmp (mode_str, "RIL"))
1772       {
1773           ah->ats_mode = MODE_RIL;
1774       }
1775       else
1776       {
1777           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid resource assignment method `%s' configured, using proportional approach\n", mode_str);
1778           ah->ats_mode = MODE_PROPORTIONAL;
1779       }
1780       GNUNET_free (mode_str);
1781   }
1782   /* Start configured solution method */
1783   switch (ah->ats_mode)
1784   {
1785     case MODE_MLP:
1786       /* Init the MLP solver with default values */
1787 #if HAVE_LIBGLPK
1788       ah->s_init = &GAS_mlp_init;
1789       ah->s_add = &GAS_mlp_address_add;
1790       ah->s_address_update_property = &GAS_mlp_address_property_changed;
1791       ah->s_address_update_session = &GAS_mlp_address_session_changed;
1792       ah->s_address_update_inuse = &GAS_mlp_address_inuse_changed;
1793       ah->s_address_update_network = &GAS_mlp_address_change_network;
1794       ah->s_get = &GAS_mlp_get_preferred_address;
1795       ah->s_get_stop = &GAS_mlp_stop_get_preferred_address;
1796       ah->s_pref = &GAS_mlp_address_change_preference;
1797       ah->s_feedback = &GAS_mlp_address_preference_feedback;
1798       ah->s_del =  &GAS_mlp_address_delete;
1799       ah->s_bulk_start = &GAS_mlp_bulk_start;
1800       ah->s_bulk_stop = &GAS_mlp_bulk_stop;
1801       ah->s_done = &GAS_mlp_done;
1802 #else
1803       GNUNET_free (ah);
1804       return NULL;
1805 #endif
1806       break;
1807     case MODE_PROPORTIONAL:
1808       /* Init the proportional solver with default values */
1809       ah->s_init = &GAS_proportional_init;
1810       ah->s_add = &GAS_proportional_address_add;
1811       ah->s_address_update_property = &GAS_proportional_address_property_changed;
1812       ah->s_address_update_session = &GAS_proportional_address_session_changed;
1813       ah->s_address_update_inuse = &GAS_proportional_address_inuse_changed;
1814       ah->s_address_update_network = &GAS_proportional_address_change_network;
1815       ah->s_get = &GAS_proportional_get_preferred_address;
1816       ah->s_get_stop = &GAS_proportional_stop_get_preferred_address;
1817       ah->s_pref = &GAS_proportional_address_change_preference;
1818       ah->s_feedback = &GAS_proportional_address_preference_feedback;
1819       ah->s_del  = &GAS_proportional_address_delete;
1820       ah->s_bulk_start = &GAS_proportional_bulk_start;
1821       ah->s_bulk_stop = &GAS_proportional_bulk_stop;
1822       ah->s_done = &GAS_proportional_done;
1823       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "PROPORTIONAL");
1824       break;
1825     case MODE_RIL:
1826       /* Init the ril solver with default values */
1827           ah->s_init = &GAS_ril_init;
1828           ah->s_add = &GAS_ril_address_add;
1829           ah->s_address_update_property = &GAS_ril_address_property_changed;
1830           ah->s_address_update_session = &GAS_ril_address_session_changed;
1831           ah->s_address_update_inuse = &GAS_ril_address_inuse_changed;
1832           ah->s_address_update_network = &GAS_ril_address_change_network;
1833           ah->s_get = &GAS_ril_get_preferred_address;
1834           ah->s_get_stop = &GAS_ril_stop_get_preferred_address;
1835           ah->s_pref = &GAS_ril_address_change_preference;
1836           ah->s_feedback = &GAS_ril_address_preference_feedback;
1837           ah->s_del  = &GAS_ril_address_delete;
1838           ah->s_bulk_start = &GAS_ril_bulk_start;
1839           ah->s_bulk_stop = &GAS_ril_bulk_stop;
1840           ah->s_done = &GAS_ril_done;
1841           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "RIL");
1842           break;
1843     default:
1844       return NULL;
1845       break;
1846   }
1847
1848   GNUNET_assert (NULL != ah->s_init);
1849   GNUNET_assert (NULL != ah->s_add);
1850   GNUNET_assert (NULL != ah->s_address_update_inuse);
1851   GNUNET_assert (NULL != ah->s_address_update_property);
1852   GNUNET_assert (NULL != ah->s_address_update_session);
1853   GNUNET_assert (NULL != ah->s_address_update_network);
1854   GNUNET_assert (NULL != ah->s_get);
1855   GNUNET_assert (NULL != ah->s_get_stop);
1856   GNUNET_assert (NULL != ah->s_pref);
1857   GNUNET_assert (NULL != ah->s_feedback);
1858   GNUNET_assert (NULL != ah->s_del);
1859   GNUNET_assert (NULL != ah->s_done);
1860   GNUNET_assert (NULL != ah->s_bulk_start);
1861   GNUNET_assert (NULL != ah->s_bulk_stop);
1862
1863   GAS_normalization_start (&normalized_preference_changed_cb, ah,
1864                                                                                                  &normalized_property_changed_cb, ah);
1865   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1866
1867   ah->solver = ah->s_init (cfg, stats, ah->addresses,
1868                   quotas, quotas_in, quotas_out, quota_count,
1869                   &bandwidth_changed_cb, ah,
1870                   &get_preferences_cb, NULL,
1871                   &get_property_cb, NULL);
1872   if (NULL == ah->solver)
1873   {
1874     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Failed to initialize solver!\n"));
1875     GNUNET_free (ah);
1876     return NULL;
1877   }
1878
1879   /* up and running */
1880   ah->running = GNUNET_YES;
1881   return ah;
1882 }
1883
1884
1885 /**
1886  * Destroy all addresses iterator
1887  *
1888  * @param cls NULL
1889  * @param key peer identity (unused)
1890  * @param value the 'struct ATS_Address' to free
1891  * @return GNUNET_OK (continue to iterate)
1892  */
1893 static int
1894 destroy_all_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1895 {
1896   struct GAS_Addresses_Handle *handle = cls;
1897   struct ATS_Address *aa = value;
1898
1899   /* Remove */
1900   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (handle->addresses, key, value));
1901   /* Notify */
1902   handle->s_del (handle->solver, aa, GNUNET_NO);
1903   /* Destroy */
1904   free_address (aa);
1905
1906   return GNUNET_OK;
1907 }
1908
1909
1910 /**
1911  * Remove all addresses
1912  *
1913  * @param handle the address handle to use
1914  */
1915 void
1916 GAS_addresses_destroy_all (struct GAS_Addresses_Handle *handle)
1917 {
1918   if (GNUNET_NO == handle->running)
1919     return;
1920
1921   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1922               "Destroying all addresses\n");
1923   handle->s_bulk_start (handle->solver);
1924   if (handle->addresses != NULL)
1925     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &destroy_all_address_it, handle);
1926   handle->s_bulk_start (handle->solver);
1927 }
1928
1929
1930 /**
1931  * Shutdown address subsystem.
1932  *
1933  * @param handle the address handle to shutdown
1934  */
1935 void
1936 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1937 {
1938   struct GAS_Addresses_Suggestion_Requests *cur;
1939
1940   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1941               "Shutting down addresses\n");
1942   GNUNET_assert (NULL != handle);
1943   GAS_addresses_destroy_all (handle);
1944   handle->running = GNUNET_NO;
1945   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1946   handle->addresses = NULL;
1947   while (NULL != (cur = handle->r_head))
1948   {
1949       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1950       GNUNET_free (cur);
1951   }
1952   handle->s_done (handle->solver);
1953   GNUNET_free (handle);
1954   /* Stop configured solution method */
1955   GAS_normalization_stop ();
1956 }
1957
1958
1959 struct PeerIteratorContext
1960 {
1961   GNUNET_ATS_Peer_Iterator it;
1962   void *it_cls;
1963   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1964 };
1965
1966
1967 /**
1968  * Iterator to iterate over all peers
1969  *
1970  * @param cls a PeerIteratorContext
1971  * @param key the peer id
1972  * @param value the ATS_address
1973  * @return GNUNET_OK to continue
1974  */
1975 static int
1976 peer_it (void *cls,
1977          const struct GNUNET_HashCode * key,
1978          void *value)
1979 {
1980   struct PeerIteratorContext *ip_ctx = cls;
1981   struct GNUNET_PeerIdentity tmp;
1982
1983   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1984   {
1985       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1986       tmp.hashPubKey = (*key);
1987       ip_ctx->it (ip_ctx->it_cls, &tmp);
1988   }
1989
1990   return GNUNET_OK;
1991 }
1992
1993
1994 /**
1995  * Return information all peers currently known to ATS
1996  *
1997  * @param handle the address handle to use
1998  * @param p_it the iterator to call for every peer
1999  * @param p_it_cls the closure for the iterator
2000  */
2001 void
2002 GAS_addresses_iterate_peers (struct GAS_Addresses_Handle *handle,
2003                                                                                                                  GNUNET_ATS_Peer_Iterator p_it,
2004                                                                                                                  void *p_it_cls)
2005 {
2006   struct PeerIteratorContext ip_ctx;
2007   unsigned int size;
2008
2009   if (NULL == p_it)
2010       return;
2011   GNUNET_assert (NULL != handle->addresses);
2012
2013   size = GNUNET_CONTAINER_multihashmap_size(handle->addresses);
2014   if (0 != size)
2015   {
2016     ip_ctx.it = p_it;
2017     ip_ctx.it_cls = p_it_cls;
2018     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
2019     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &peer_it, &ip_ctx);
2020     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
2021   }
2022   p_it (p_it_cls, NULL);
2023 }
2024
2025
2026 struct PeerInfoIteratorContext
2027 {
2028   GNUNET_ATS_PeerInfo_Iterator it;
2029   void *it_cls;
2030 };
2031
2032
2033 /**
2034  * Iterator to iterate over a peer's addresses
2035  *
2036  * @param cls a PeerInfoIteratorContext
2037  * @param key the peer id
2038  * @param value the ATS_address
2039  * @return GNUNET_OK to continue
2040  */
2041 static int 
2042 peerinfo_it (void *cls,
2043              const struct GNUNET_HashCode * key,
2044              void *value)
2045 {
2046   struct PeerInfoIteratorContext *pi_ctx = cls;
2047   struct ATS_Address *addr = (struct ATS_Address *)  value;
2048
2049   if (NULL != pi_ctx->it)
2050   {
2051     pi_ctx->it (pi_ctx->it_cls,
2052                 &addr->peer,
2053                 addr->plugin,
2054                 addr->addr, addr->addr_len,
2055                 addr->active,
2056                 addr->atsi, addr->atsi_count,
2057                 addr->assigned_bw_out,
2058                 addr->assigned_bw_in);
2059   }
2060   return GNUNET_YES;
2061 }
2062
2063
2064 /**
2065  * Return information all peers currently known to ATS
2066  *
2067  * @param handle the address handle to use
2068  * @param peer the respective peer
2069  * @param pi_it the iterator to call for every peer
2070  * @param pi_it_cls the closure for the iterator
2071  */
2072 void
2073 GAS_addresses_get_peer_info (struct GAS_Addresses_Handle *handle,
2074                              const struct GNUNET_PeerIdentity *peer,
2075                              GNUNET_ATS_PeerInfo_Iterator pi_it,
2076                              void *pi_it_cls)
2077 {
2078   struct PeerInfoIteratorContext pi_ctx;
2079   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
2080   GNUNET_assert (NULL != peer);
2081   GNUNET_assert (NULL != handle->addresses);
2082   if (NULL == pi_it)
2083     return; /* does not make sense without callback */
2084
2085   zero_bw = GNUNET_BANDWIDTH_value_init (0);
2086   pi_ctx.it = pi_it;
2087   pi_ctx.it_cls = pi_it_cls;
2088
2089   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
2090
2091   if (NULL != pi_it)
2092     pi_it (pi_it_cls, NULL, NULL, NULL, 0, GNUNET_NO, NULL, 0, zero_bw, zero_bw);
2093
2094 }
2095
2096
2097 /* end of gnunet-service-ats_addresses.c */