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