changes
[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_performance.h"
32 #include "gnunet-service-ats_scheduling.h"
33 #include "gnunet-service-ats_reservations.h"
34 #if HAVE_LIBGLPK
35 #include "gnunet-service-ats_addresses_mlp.h"
36 #endif
37 #include "gnunet-service-ats_addresses_simplistic.h"
38
39 /**
40  * NOTE: Do not change this documentation. This documentation is based on
41  * gnunet.org:/vcs/fsnsg/ats-paper.git/tech-doku/ats-tech-guide.tex
42  * use build_txt.sh to generate plaintext output
43  *
44  *   1 ATS addresses : ATS address management
45  *
46  *    This ATS addresses ("addresses") component manages the addresses known to
47  *    ATS service and suggests addresses to transport service when it is
48  *    interested in address suggestion for a peer. ATS addresses also
49  *    instantiates the bandwidth assignment mechanism (solver), notifies it
50  *    about changes to addresses and forwards changes to bandwidth assignments
51  *    to transport, depending if transport is interested in this change.
52  *
53  *     1.1 Input data
54  *
55  *       1.1.1 Addresses
56  *
57  *    Addresses are added by specifying peer ID, plugin, address, address length
58  *    and session, if available. ATS information can be specified if available.
59  *
60  *       1.1.2 Networks
61  *
62  *    ATS specifies a fix set of networks an address can belong to. For each
63  *    network an inbound and outbound quota will be specified. The available
64  *    networks and addtional helper varaibles are defined in
65  *    gnunet_ats_service.h. At the moment 5 networks are defined:
66  *      * GNUNET_ATS_NET_UNSPECIFIED
67  *      * GNUNET_ATS_NET_LOOPBACK
68  *      * GNUNET_ATS_NET_LAN
69  *      * GNUNET_ATS_NET_WAN
70  *      * GNUNET_ATS_NET_WLAN
71  *
72  *    The total number of networks defined is stored in
73  *    GNUNET_ATS_NetworkTypeCount GNUNET_ATS_NetworkType can be used array
74  *    initializer for an int array, while GNUNET_ATS_NetworkType is an
75  *    initializer for a char array containing a string description of all
76  *    networks
77  *
78  *       1.1.3 Quotas
79  *
80  *    An inbound and outbound quota for each of the networks mentioned in 1.1.2
81  *    is loaded from ats configuration during initialization. This quota defines
82  *    to total amount of inbound and outbound traffic allowed for a specific
83  *    network. The configuration values used are in section ats:
84  *      * "NETWORK"_QUOTA_IN = <value>
85  *      * "NETWORK"_QUOTA_IN = <value>
86  *
87  *    You can specify quotas by setting the <value> to a:
88  *      * unrestricted: unlimited
89  *      * number of bytes: e.g. 10240
90  *      * fancy value: e.g. 64 Kib
91  *
92  *    unlimited is defined as GNUNET_ATS_MaxBandwidthString and equivalent to
93  *    the value GNUNET_ATS_MaxBandwidth Important predefined values for quotas
94  *    are:
95  *      * GNUNET_ATS_DefaultBandwidth: 65536
96  *      * GNUNET_ATS_MaxBandwidth: UINT32_MAX
97  *      * GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT: 1024
98  *
99  *    Details of loading quotas and default values will be described on
100  *
101  *       1.1.4 Preference values
102  *
103  *     1.2 Data structures used
104  *
105  *    Addresse uses struct ATS_Address for each address. The structs are stored
106  *    in a linked list and provides a pointer void *solver_information for the
107  *    solver to store address specific information. It provides the int values
108  *    active which is set to GNUNET_YES if the address is select for transport
109  *    use and used, representing that transport service is actively using this
110  *    address. Address information are stored in peer, addr, addr_len, plugin.
111  *
112  *     1.3 Initialization
113  *
114  *    During initialization a hashmap to store addresses is created. The quotas
115  *    for all networks defined for ATS are loaded from configuration. For each
116  *    network first the logic will check if the string
117  *    GNUNET_ATS_MaxBandwidthString is configured, if not it will try to convert
118  *    the configured value as a fancy size and if this fails it will try to use
119  *    it as a value_number. If no configuration value is found it will assign
120  *    GNUNET_ATS_DefaultBandwidth. The most important step is to load the
121  *    configured solver using configuration "[ats]:MODE". Current solvers are
122  *    MODE_SIMPLISTIC, MODE_MLP. Interaction is done using a solver API
123  *
124  *     1.4 Solver API
125  *
126  *    Solver functions:
127  *      * s_init: init the solver with required information
128  *      * s_add: add a new address
129  *      * s_update: update ATS values or session for an address
130  *      * s_get: get prefered address for a peer
131  *      * s_del: delete an address
132  *      * s_pref: change preference value for a peer
133  *      * s_done: shutdown solver
134  *
135  *    Callbacks: addresses provides a bandwidth_changed_cb callback to the
136  *    solver which is called when bandwidth assigned to peer has changed
137  *
138  *     1.5 Shutdown
139  *
140  *    During shutdown all addresses are freed and the solver told to shutdown
141  *
142  *     1.6 Addresses and sessions
143  *
144  *    Addresses consist of the address itself and a numerical session. When a
145  *    new address without a session is added it has no session, so it gets
146  *    session 0 assigned. When an address with a session is added and an address
147  *    object with session 0 is found, this object is updated with the session
148  *    otherwise a new address object with this session assigned is created.
149  *
150  *       1.6.1 Terminology
151  *
152  *    Addresses a1,a2 with session s1, s2 are "exact" if:
153  *    (a1 == a2)&&(s1 == s2)
154  *    Addresses a1,a2 with session s1, s2 are "equivalent" if:
155  *    (a1 == a2)&&((s1 == s2)||(s1 == 0)||(s2 == 0)
156  *
157  *     1.7 Address management
158  *
159  *    Transport service notifies ATS about changes to the addresses known to
160  *    him.
161  *
162  *       1.7.1 Adding an address
163  *
164  *    When transport learns a new address it tells ATS and ATS is telling
165  *    addresses about it using GAS_address_add. If not known to addresses it
166  *    creates a new address object and calls solver's s_add. ATS information are
167  *    deserialized and solver is notified about the session and ATS information
168  *    using s_update.
169  *
170  *       1.7.2 Updating an address
171  *
172  *    Addresses does an lookup up for the existing address with the given
173  *    session. If disassembles included ATS information and notifies the solver
174  *    using s_update about the update.
175  *
176  *       1.7.3 Deleting an address
177  *
178  *    Addresses does an lookup for the exact address and session and if removes
179  *    this address. If session != 0 the session is set to 0 and the address is
180  *    kept. If session == 0, the addresses is removed.
181  *
182  *       1.7.4 Requesting an address suggestion
183  *
184  *    The address client issues a request address message to be notified about
185  *    address suggestions for a specific peer. Addresses asks the solver with
186  *    s_get. If no address is available, it will not send a response, otherwise
187  *    it will respond with the choosen address.
188  *
189  *       1.7.5 Address suggestions
190  *
191  *    Addresses will notify the client automatically on any bandwidth_changed_cb
192  *    by the solver if a address suggestion request is pending. If no address is
193  *    available it will not respond at all If the client is not interested
194  *    anymore, it has to cancel the address suggestion request.
195  *
196  *       1.7.6 Suggestions blocks and reset
197  *
198  *    After suggesting an address it is blocked for ATS_BLOCKING_DELTA sec. to
199  *    prevent the client from being thrashed. If the client requires immediately
200  *    it can reset this block using GAS_addresses_handle_backoff_reset.
201  *
202  *       1.7.7 Marking address in use
203  *
204  *    The client can notify addresses that it successfully uses an address and
205  *    wants this address to be kept by calling GSA_address_in_use. Adresses will
206  *    mark the address as used an notify the solver about the use.
207  *
208  *       1.7.8 Address lifecycle
209  *
210  *      * (add address)
211  *      * (updated address) || (address in use)
212  *      * (delete address)
213  *
214  *     1.8 Bandwidth assignment
215  *
216  *    The addresses are used to perform resource allocation operations. ATS
217  *    addresses takes care of instantiating the solver configured and notifies
218  *    the respective solver about address changes and receives changes to the
219  *    bandwidth assignment from the solver. The current bandwidth assignment is
220  *    sent to transport. The specific solvers will be described in the specific
221  *    section.
222  *
223  *     1.9 Changing peer preferences
224  *
225  *    The bandwidth assigned to a peer can be influenced by setting a preference
226  *    for a peer. The prefernce will be given to to the solver with s_pref which
227  *    has to take care of the preference value
228
229  */
230
231
232 /**
233  * Available ressource assignment modes
234  */
235 enum ATS_Mode
236 {
237   /*
238    * Simplistic mode:
239    *
240    * Assign each peer an equal amount of bandwidth (bw)
241    *
242    * bw_per_peer = bw_total / #active addresses
243    */
244   MODE_SIMPLISTIC,
245
246   /*
247    * MLP mode:
248    *
249    * Solve ressource assignment as an optimization problem
250    * Uses an mixed integer programming solver
251    */
252   MODE_MLP
253 };
254
255 /**
256  * Pending Address suggestion requests
257  */
258 struct GAS_Addresses_Suggestion_Requests
259 {
260   /**
261    * Next in DLL
262    */
263   struct GAS_Addresses_Suggestion_Requests *next;
264
265   /**
266    * Previous in DLL
267    */
268   struct GAS_Addresses_Suggestion_Requests *prev;
269
270   /**
271    * Peer ID
272    */
273   struct GNUNET_PeerIdentity id;
274 };
275
276 /**
277  * Handle for ATS address component
278  */
279 struct GAS_Addresses_Handle
280 {
281   /**
282    *
283    */
284   struct GNUNET_STATISTICS_Handle *stat;
285
286   /**
287    * A multihashmap to store all addresses
288    */
289   struct GNUNET_CONTAINER_MultiHashMap *addresses;
290
291   /**
292    * Configure WAN quota in
293    */
294   unsigned long long wan_quota_in;
295
296   /**
297    * Configure WAN quota out
298    */
299   unsigned long long wan_quota_out;
300
301   /**
302    * Is ATS addresses running
303    */
304   int running;
305
306   /**
307    * Configured ATS solver
308    */
309   int ats_mode;
310
311   /**
312    *  Solver handle
313    */
314   void *solver;
315
316   /**
317    * Address suggestion requests DLL head
318    */
319   struct GAS_Addresses_Suggestion_Requests *r_head;
320
321   /**
322    * Address suggestion requests DLL tail
323    */
324   struct GAS_Addresses_Suggestion_Requests *r_tail;
325
326   /* Solver functions */
327
328   /**
329    * Initialize solver
330    */
331   GAS_solver_init s_init;
332
333   /**
334    * Add an address to the solver
335    */
336   GAS_solver_address_add s_add;
337
338   /**
339    * Update address in solver
340    */
341   GAS_solver_address_update s_update;
342
343   /**
344    * Get address from solver
345    */
346   GAS_solver_get_preferred_address s_get;
347
348   /**
349    * Get address from solver
350    */
351   GAS_solver_stop_get_preferred_address s_get_stop;
352
353   /**
354    * Delete address in solver
355    */
356   GAS_solver_address_delete s_del;
357
358   /**
359    * Change preference for quality in solver
360    */
361   GAS_solver_address_change_preference s_pref;
362
363   /**
364    * Shutdown solver
365    */
366   GAS_solver_done s_done;
367 };
368
369
370 static unsigned int
371 assemble_ats_information (const struct ATS_Address *aa,  struct GNUNET_ATS_Information **dest)
372 {
373   unsigned int ats_count = GNUNET_ATS_PropertyCount - 1;
374   struct GNUNET_ATS_Information *ats = GNUNET_malloc (ats_count * sizeof (struct GNUNET_ATS_Information));
375   (*dest) = ats;
376
377   ats[0].type = ntohl(GNUNET_ATS_UTILIZATION_UP);
378   ats[0].value = aa->atsp_utilization_out.value__;
379   ats[1].type = ntohl(GNUNET_ATS_UTILIZATION_DOWN);
380   ats[1].value = aa->atsp_utilization_in.value__;
381   ats[2].type = ntohl(GNUNET_ATS_NETWORK_TYPE);
382   ats[2].value = ntohl(aa->atsp_network_type);
383   ats[3].type = ntohl(GNUNET_ATS_QUALITY_NET_DELAY);
384   ats[3].value = ntohl(aa->atsp_latency.rel_value);
385   ats[4].type = ntohl(GNUNET_ATS_QUALITY_NET_DISTANCE);
386   ats[4].value = ntohl(aa->atsp_distance);
387   ats[5].type = ntohl(GNUNET_ATS_COST_WAN);
388   ats[5].value = ntohl (aa->atsp_cost_wan);
389   ats[6].type = ntohl(GNUNET_ATS_COST_LAN);
390   ats[6].value = ntohl (aa->atsp_cost_lan);
391   ats[7].type = ntohl(GNUNET_ATS_COST_WLAN);
392   ats[7].value = ntohl (aa->atsp_cost_wlan);
393   return ats_count;
394 }
395
396 static unsigned int
397 disassemble_ats_information (const struct GNUNET_ATS_Information *src,
398                              uint32_t ats_count,
399                              struct ATS_Address *dest)
400 {
401   int i;
402   int change = GNUNET_NO;
403   int res = 0;
404   for (i = 0; i < ats_count; i++)
405     switch (ntohl (src[i].type))
406     {
407     case GNUNET_ATS_UTILIZATION_UP:
408         if (dest->atsp_utilization_out.value__ != src[i].value)
409                 change = GNUNET_YES;
410       dest->atsp_utilization_out.value__ = src[i].value;
411       res ++;
412       break;
413     case GNUNET_ATS_UTILIZATION_DOWN:
414         if (dest->atsp_utilization_in.value__ != src[i].value)
415                 change = GNUNET_YES;
416       dest->atsp_utilization_in.value__ = src[i].value;
417       res ++;
418       break;
419     case GNUNET_ATS_QUALITY_NET_DELAY:
420         if (dest->atsp_latency.rel_value  != src[i].value)
421                 change = GNUNET_YES;
422       dest->atsp_latency.rel_value = ntohl (src[i].value);
423       res ++;
424       break;
425     case GNUNET_ATS_QUALITY_NET_DISTANCE:
426         if (dest->atsp_distance!= src[i].value)
427                 change = GNUNET_YES;
428       dest->atsp_distance = ntohl (src[i].value);
429       res ++;
430       break;
431     case GNUNET_ATS_COST_WAN:
432         if (dest->atsp_cost_wan != src[i].value)
433                 change = GNUNET_YES;
434       dest->atsp_cost_wan = ntohl (src[i].value);
435       res ++;
436       break;
437     case GNUNET_ATS_COST_LAN:
438         if (dest->atsp_cost_lan != src[i].value)
439                 change = GNUNET_YES;
440       dest->atsp_cost_lan = ntohl (src[i].value);
441       res ++;
442       break;
443     case GNUNET_ATS_COST_WLAN:
444         if (dest->atsp_cost_wlan != src[i].value)
445                 change = GNUNET_YES;
446       dest->atsp_cost_wlan = ntohl (src[i].value);
447       res ++;
448       break;
449     case GNUNET_ATS_NETWORK_TYPE:
450         if (dest->atsp_network_type != src[i].value)
451                 change = GNUNET_YES;
452       dest->atsp_network_type = ntohl (src[i].value);
453       res ++;
454       break;
455     case GNUNET_ATS_ARRAY_TERMINATOR:
456       break;
457     default:
458       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
459                   "Received unsupported ATS type %u\n", ntohl (src[i].type));
460       GNUNET_break (0);
461       break;
462     }
463   if (GNUNET_YES == change)
464   {
465                 struct GNUNET_ATS_Information *destats;
466                 int ats_count;
467                 ats_count = assemble_ats_information (dest, &destats);
468                 GAS_handle_performance_update (&dest->peer, destats, ats_count);
469                 GNUNET_free (destats);
470   }
471   return res;
472 }
473
474 /**
475  * Free the given address
476  * @param addr address to destroy
477  */
478 static void
479 free_address (struct ATS_Address *addr)
480 {
481   GNUNET_free (addr->plugin);
482   GNUNET_free (addr);
483 }
484
485 /**
486  * Create a ATS_address with the given information
487  * @param peer peer
488  * @param plugin_name plugin
489  * @param plugin_addr address
490  * @param plugin_addr_len address length
491  * @param session_id session
492  * @return the ATS_Address
493  */
494 static struct ATS_Address *
495 create_address (const struct GNUNET_PeerIdentity *peer,
496                 const char *plugin_name,
497                 const void *plugin_addr, size_t plugin_addr_len,
498                 uint32_t session_id)
499 {
500   struct ATS_Address *aa = NULL;
501
502   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
503   aa->peer = *peer;
504   aa->addr_len = plugin_addr_len;
505   aa->addr = &aa[1];
506   memcpy (&aa[1], plugin_addr, plugin_addr_len);
507   aa->plugin = GNUNET_strdup (plugin_name);
508   aa->session_id = session_id;
509   aa->active = GNUNET_NO;
510   aa->used = GNUNET_NO;
511   aa->solver_information = NULL;
512   aa->assigned_bw_in = GNUNET_BANDWIDTH_value_init(0);
513   aa->assigned_bw_out = GNUNET_BANDWIDTH_value_init(0);
514   return aa;
515 }
516
517
518 /**
519  * Destroy the given address.
520  *
521  * @param handle the address handle
522  * @param addr address to destroy
523  * @return GNUNET_YES if bandwidth allocations should be recalcualted
524  */
525 static int
526 destroy_address (struct GAS_Addresses_Handle *handle, struct ATS_Address *addr)
527 {
528   int ret;
529
530   ret = GNUNET_NO;
531   GNUNET_assert (GNUNET_YES ==
532                  GNUNET_CONTAINER_multihashmap_remove (handle->addresses,
533                                                        &addr->peer.hashPubKey,
534                                                        addr));
535   free_address (addr);
536   return ret;
537 }
538
539
540 struct CompareAddressContext
541 {
542   const struct ATS_Address *search;
543
544   /* exact_address != NULL if address and session is equal */
545   struct ATS_Address *exact_address;
546   /* exact_address != NULL if address and session is 0 */
547   struct ATS_Address *base_address;
548 };
549
550
551 static int
552 compare_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
553 {
554   struct CompareAddressContext *cac = cls;
555   struct ATS_Address *aa = value;
556
557   /* Find an matching exact address:
558    *
559    * Compare by:
560    * aa->addr_len == cac->search->addr_len
561    * aa->plugin == cac->search->plugin
562    * aa->addr == cac->search->addr
563    * aa->session == cac->search->session
564    *
565    * return as exact address
566    */
567   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
568   {
569       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == cac->search->session_id))
570         cac->exact_address = aa;
571   }
572
573   /* Find an matching base address:
574    *
575    * Properties:
576    *
577    * aa->session_id == 0
578    *
579    * Compare by:
580    * aa->addr_len == cac->search->addr_len
581    * aa->plugin == cac->search->plugin
582    * aa->addr == cac->search->addr
583    *
584    * return as base address
585    */
586   if ((aa->addr_len == cac->search->addr_len) && (0 == strcmp (aa->plugin, cac->search->plugin)))
587   {
588       if ((0 == memcmp (aa->addr, cac->search->addr, aa->addr_len)) && (aa->session_id == 0))
589         cac->base_address = aa;
590   }
591
592   /* Find an matching exact address based on session:
593    *
594    * Properties:
595    *
596    * cac->search->addr_len == 0
597    *
598    * Compare by:
599    * aa->plugin == cac->search->plugin
600    * aa->session_id == cac->search->session_id
601    *
602    * return as exact address
603    */
604   if (0 == cac->search->addr_len)
605   {
606       if ((0 == strcmp (aa->plugin, cac->search->plugin)) && (aa->session_id == cac->search->session_id))
607         cac->exact_address = aa;
608   }
609
610   if (cac->exact_address == NULL)
611     return GNUNET_YES; /* Continue iteration to find exact address */
612   else
613     return GNUNET_NO; /* Stop iteration since we have an exact address */
614 }
615
616
617 /**
618  * Find an existing equivalent address record.
619  * Compares by peer identity and network address OR by session ID
620  * (one of the two must match).
621  *
622  * @param handle the address handle
623  * @param peer peer to lookup addresses for
624  * @param addr existing address record
625  * @return existing address record, NULL for none
626  */
627 struct ATS_Address *
628 find_equivalent_address (struct GAS_Addresses_Handle *handle,
629                          const struct GNUNET_PeerIdentity *peer,
630                          const struct ATS_Address *addr)
631 {
632   struct CompareAddressContext cac;
633
634   cac.exact_address = NULL;
635   cac.base_address = NULL;
636   cac.search = addr;
637   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
638                                               &compare_address_it, &cac);
639
640   if (cac.exact_address == NULL)
641     return cac.base_address;
642   return cac.exact_address;
643 }
644
645
646 static struct ATS_Address *
647 lookup_address (struct GAS_Addresses_Handle *handle,
648                 const struct GNUNET_PeerIdentity *peer,
649                 const char *plugin_name,
650                 const void *plugin_addr,
651                 size_t plugin_addr_len,
652                 uint32_t session_id,
653                 const struct GNUNET_ATS_Information *atsi,
654                 uint32_t atsi_count)
655 {
656   struct ATS_Address *aa;
657   struct ATS_Address *ea;
658
659   aa = create_address (peer,
660                        plugin_name,
661                        plugin_addr, plugin_addr_len,
662                        session_id);
663
664   /* Get existing address or address with session == 0 */
665   ea = find_equivalent_address (handle, peer, aa);
666   free_address (aa);
667   if (ea == NULL)
668   {
669     return NULL;
670   }
671   else if (ea->session_id != session_id)
672   {
673     return NULL;
674   }
675   return ea;
676 }
677
678
679 void
680 GAS_addresses_add (struct GAS_Addresses_Handle *handle,
681                    const struct GNUNET_PeerIdentity *peer,
682                    const char *plugin_name, const void *plugin_addr,
683                    size_t plugin_addr_len, uint32_t session_id,
684                    const struct GNUNET_ATS_Information *atsi,
685                    uint32_t atsi_count)
686 {
687   struct ATS_Address *aa;
688   struct ATS_Address *ea;
689   unsigned int ats_res;
690
691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
692               "Received `%s' for peer `%s'\n",
693               "ADDRESS ADD",
694               GNUNET_i2s (peer));
695
696   if (GNUNET_NO == handle->running)
697     return;
698
699   GNUNET_assert (NULL != handle->addresses);
700
701   aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len,
702                        session_id);
703   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, aa)))
704   {
705       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
706                 "While adding address: had %u ATS elements to add, could only add %u\n",
707                 atsi_count, ats_res);
708   }
709
710   /* Get existing address or address with session == 0 */
711   ea = find_equivalent_address (handle, peer, aa);
712   if (ea == NULL)
713   {
714     /* We have a new address */
715     GNUNET_assert (GNUNET_OK ==
716                    GNUNET_CONTAINER_multihashmap_put (handle->addresses,
717                                                       &peer->hashPubKey, aa,
718                                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
719     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Added new address for peer `%s' session id %u, %p\n",
720                 GNUNET_i2s (peer), session_id, aa);
721     /* Tell solver about new address */
722     handle->s_add (handle->solver, handle->addresses, aa);
723     return;
724   }
725   GNUNET_free (aa->plugin);
726   GNUNET_free (aa);
727
728   if (ea->session_id != 0)
729   {
730       /* This address with the same session is already existing
731        * Should not happen */
732       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
733                 "Added already existing address for peer `%s' `%s' %p with new session %u\n",
734                 GNUNET_i2s (peer), plugin_name, session_id);
735       GNUNET_break (0);
736       return;
737   }
738
739   /* We have an address without an session, update this address */
740
741   /* Notify solver about update with atsi information and session */
742   handle->s_update (handle->solver, handle->addresses, ea, session_id, ea->used, atsi, atsi_count);
743
744   /* Do the update */
745   ea->session_id = session_id;
746   if (atsi_count != (ats_res = disassemble_ats_information(atsi, atsi_count, ea)))
747   {
748       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
749                   "While updating address: had %u ATS elements to add, could only add %u\n",
750                   atsi_count, ats_res);
751   }
752   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
753            "Updated existing address for peer `%s' %p with new session %u\n",
754            GNUNET_i2s (peer), ea, session_id);
755 }
756
757
758 void
759 GAS_addresses_update (struct GAS_Addresses_Handle *handle,
760                       const struct GNUNET_PeerIdentity *peer,
761                       const char *plugin_name, const void *plugin_addr,
762                       size_t plugin_addr_len, uint32_t session_id,
763                       const struct GNUNET_ATS_Information *atsi,
764                       uint32_t atsi_count)
765 {
766   struct ATS_Address *aa;
767   uint32_t ats_res;
768
769   if (GNUNET_NO == handle->running)
770     return;
771
772   GNUNET_assert (NULL != handle->addresses);
773
774   /* Get existing address */
775   aa = lookup_address (handle, peer, plugin_name, plugin_addr, plugin_addr_len,
776                        session_id, atsi, atsi_count);
777   if (aa == NULL)
778   {
779     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Tried to update unknown address for peer `%s' `%s' session id %u\n",
780                 GNUNET_i2s (peer), plugin_name, session_id);
781     GNUNET_break (0);
782     return;
783   }
784
785   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
786                 "Received `%s' for peer `%s' address \n",
787                 "ADDRESS UPDATE",
788                 GNUNET_i2s (peer), aa);
789
790   /* Tell solver about update */
791   handle->s_update (handle->solver, handle->addresses, aa, session_id, aa->used, atsi, atsi_count);
792
793   /* Update address */
794   if (atsi_count != (ats_res = disassemble_ats_information (atsi, atsi_count, aa)))
795   {
796       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
797                 "While adding address: had %u ATS elements to add, could only add %u\n",
798                 atsi_count, ats_res);
799   }
800   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
801             "Updated %u ATS elements for address %p\n",
802             ats_res, aa);
803 }
804
805
806 struct DestroyContext
807 {
808   struct ATS_Address *aa;
809
810   struct GAS_Addresses_Handle *handle;
811
812   /**
813    * GNUNET_NO  : full address
814    * GNUNET_YES : just session
815    */
816   int result;
817 };
818
819
820 /**
821  * Delete an address
822  *
823  * If session != 0, just the session is deleted, the address itself still exists
824  * If session == 0, remove full address
825  * If session == 0 and addrlen == 0, destroy inbound address
826  *
827  * @param cls unused
828  * @param key unused
829  * @param value the 'struct ATS_Address'
830  * @return GNUNET_OK (continue to iterate)
831  */
832 static int
833 destroy_by_session_id (void *cls, const struct GNUNET_HashCode * key, void *value)
834 {
835   struct DestroyContext *dc = cls;
836   struct GAS_Addresses_Handle *handle = dc->handle;
837   const struct ATS_Address *des = dc->aa;
838   struct ATS_Address *aa = value;
839
840   GNUNET_assert (0 == memcmp (&aa->peer, &des->peer,
841                               sizeof (struct GNUNET_PeerIdentity)));
842
843
844   if (des->session_id == 0)
845   {
846     /* Session == 0, remove full address  */
847     if ((0 == strcmp (des->plugin, aa->plugin)) &&
848         (aa->addr_len == des->addr_len) &&
849         (0 == memcmp (des->addr, aa->addr, aa->addr_len)))
850     {
851
852       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
853                   "Deleting full address for peer `%s' session %u %p\n",
854                   GNUNET_i2s (&aa->peer), aa->session_id, aa);
855
856       /* Notify solver about deletion */
857       handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
858       destroy_address (handle, aa);
859       dc->result = GNUNET_NO;
860       return GNUNET_OK; /* Continue iteration */
861     }
862   }
863   else
864   {
865     /* Session != 0, just remove session */
866     if (aa->session_id != des->session_id)
867       return GNUNET_OK; /* irrelevant */
868
869     if ((aa->session_id != 0) &&
870         (0 != strcmp (des->plugin, aa->plugin)))
871     {
872         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
873                     "Different plugins during removal: `%s' vs `%s' \n",
874                     des->plugin, aa->plugin);
875         GNUNET_break (0);
876         return GNUNET_OK;
877     }
878
879     if (aa->addr_len == 0)
880     {
881         /* Inbound connection died, delete full address */
882         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
883                     "Deleting inbound address for peer `%s': `%s' session %u\n",
884                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
885
886         /* Notify solver about deletion */
887         handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
888         destroy_address (handle, aa);
889         dc->result = GNUNET_NO;
890         return GNUNET_OK; /* Continue iteration */
891     }
892     else
893     {
894         /* Session died */
895         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
896                     "Deleting session for peer `%s': `%s' %u\n",
897                     GNUNET_i2s (&aa->peer), aa->plugin, aa->session_id);
898         /* Notify solver to delete session */
899         handle->s_del (handle->solver, handle->addresses, aa, GNUNET_YES);
900         aa->session_id = 0;
901         return GNUNET_OK;
902     }
903   }
904   return GNUNET_OK;
905 }
906
907 void
908 GAS_addresses_destroy (struct GAS_Addresses_Handle *handle,
909                        const struct GNUNET_PeerIdentity *peer,
910                        const char *plugin_name, const void *plugin_addr,
911                        size_t plugin_addr_len, uint32_t session_id)
912 {
913   struct ATS_Address *ea;
914   struct DestroyContext dc;
915
916   if (GNUNET_NO == handle->running)
917     return;
918
919   /* Get existing address */
920   ea = lookup_address (handle, peer, plugin_name, plugin_addr, plugin_addr_len,
921                        session_id, NULL, 0);
922
923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
924               "Received `%s' for peer `%s' address %p session %u\n",
925               "ADDRESS DESTROY",
926               GNUNET_i2s (peer), ea, session_id);
927
928   if (ea == NULL)
929   {
930     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Tried to destroy unknown address for peer `%s' `%s' session id %u\n",
931                 GNUNET_i2s (peer), plugin_name, session_id);
932     return;
933   }
934
935   GNUNET_break (0 < strlen (plugin_name));
936   dc.handle = handle;
937   dc.aa = create_address (peer, plugin_name, plugin_addr, plugin_addr_len, session_id);
938
939   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey,
940                                               &destroy_by_session_id, &dc);
941   free_address (dc.aa);
942 }
943
944
945 int
946 GAS_addresses_in_use (struct GAS_Addresses_Handle *handle,
947                       const struct GNUNET_PeerIdentity *peer,
948                       const char *plugin_name, const void *plugin_addr,
949                       size_t plugin_addr_len, uint32_t session_id, int in_use)
950 {
951   struct ATS_Address *ea;
952
953   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
954                 "Received `%s' for peer `%s'\n",
955                 "ADDRESS IN USE",
956                 GNUNET_i2s (peer));
957
958   if (GNUNET_NO == handle->running)
959     return GNUNET_SYSERR;
960
961   ea = lookup_address (handle, peer, plugin_name,
962                         plugin_addr, plugin_addr_len,
963                         session_id, NULL, 0);
964   if (NULL == ea)
965   {
966     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
967                 "Trying to set unknown address `%s', %s %u %s \n",
968                 GNUNET_i2s (peer),
969                 plugin_name, session_id,
970                 (GNUNET_NO == in_use) ? "NO" : "YES");
971     GNUNET_break (0);
972     return GNUNET_SYSERR;
973   }
974   if (ea->used == in_use)
975   {
976     GNUNET_break (0);
977     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
978                 "Address in use called multiple times for peer `%s': %s -> %s \n",
979                 GNUNET_i2s (peer),
980                 (GNUNET_NO == ea->used) ? "NO" : "YES",
981                 (GNUNET_NO == in_use) ? "NO" : "YES");
982     return GNUNET_SYSERR;
983   }
984
985   /* Tell solver about update */
986   handle->s_update (handle->solver, handle->addresses, ea, session_id, in_use, NULL, 0);
987   ea->used = in_use;
988
989   return GNUNET_OK;
990 }
991
992
993 /**
994  * Cancel address suggestions for a peer
995  *
996  * @param handle the address handle
997  * @param peer the respective peer
998  */
999 void
1000 GAS_addresses_request_address_cancel (struct GAS_Addresses_Handle *handle,
1001                                       const struct GNUNET_PeerIdentity *peer)
1002 {
1003   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
1004
1005   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006               "Received request: `%s' for peer %s\n", "request_address_cancel", GNUNET_i2s (peer));
1007
1008   while (NULL != cur)
1009   {
1010       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
1011         break; /* found */
1012       cur = cur->next;
1013   }
1014
1015   if (NULL == cur)
1016   {
1017       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1018                   "No address requests pending for peer `%s', cannot remove!\n", GNUNET_i2s (peer));
1019       return;
1020   }
1021   handle->s_get_stop (handle->solver, handle->addresses, peer);
1022   GAS_addresses_handle_backoff_reset (handle, peer);
1023   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1024               "Removed request pending for peer `%s\n", GNUNET_i2s (peer));
1025   GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1026   GNUNET_free (cur);
1027 }
1028
1029
1030 /**
1031  * Add an address suggestions for a peer
1032  *
1033  * @param handle the address handle
1034  * @param peer the respective peer
1035  */
1036 void
1037 GAS_addresses_request_address (struct GAS_Addresses_Handle *handle,
1038                                const struct GNUNET_PeerIdentity *peer)
1039 {
1040   struct GAS_Addresses_Suggestion_Requests *cur = handle->r_head;
1041   struct ATS_Address *aa;
1042   struct GNUNET_ATS_Information *ats;
1043   unsigned int ats_count;
1044
1045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046               "Received `%s' for peer `%s'\n",
1047               "REQUEST ADDRESS",
1048               GNUNET_i2s (peer));
1049
1050   if (GNUNET_NO == handle->running)
1051     return;
1052   while (NULL != cur)
1053   {
1054       if (0 == memcmp (peer, &cur->id, sizeof (cur->id)))
1055         break; /* already suggesting */
1056       cur = cur->next;
1057   }
1058   if (NULL == cur)
1059   {
1060       cur = GNUNET_malloc (sizeof (struct GAS_Addresses_Suggestion_Requests));
1061       cur->id = (*peer);
1062       GNUNET_CONTAINER_DLL_insert (handle->r_head, handle->r_tail, cur);
1063   }
1064
1065   /* Get prefered address from solver */
1066   aa = (struct ATS_Address *) handle->s_get (handle->solver, handle->addresses, peer);
1067   if (NULL == aa)
1068   {
1069     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1070                 "Cannot suggest address for peer `%s'\n", GNUNET_i2s (peer));
1071     return;
1072   }
1073
1074   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1075               "Suggesting address %p for peer `%s'\n", aa, GNUNET_i2s (peer));
1076
1077   ats_count = assemble_ats_information (aa, &ats);
1078   GAS_scheduling_transmit_address_suggestion (peer,
1079                                               aa->plugin,
1080                                               aa->addr, aa->addr_len,
1081                                               aa->session_id,
1082                                               ats, ats_count,
1083                                               aa->assigned_bw_out,
1084                                               aa->assigned_bw_in);
1085
1086   aa->block_interval = GNUNET_TIME_relative_add (aa->block_interval, ATS_BLOCKING_DELTA);
1087   aa->blocked_until = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), aa->block_interval);
1088
1089   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1090        "Address %p ready for suggestion, block interval now %llu \n",
1091        aa, aa->block_interval);
1092
1093   GNUNET_free (ats);
1094 }
1095
1096
1097 static int
1098 reset_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1099 {
1100   struct ATS_Address *aa = value;
1101
1102   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1103               "Resetting interval for peer `%s' address %p from %llu to 0\n",
1104               GNUNET_i2s (&aa->peer), aa, aa->block_interval);
1105
1106   aa->blocked_until = GNUNET_TIME_UNIT_ZERO_ABS;
1107   aa->block_interval = GNUNET_TIME_UNIT_ZERO;
1108   return GNUNET_OK;
1109 }
1110
1111
1112 void
1113 GAS_addresses_handle_backoff_reset (struct GAS_Addresses_Handle *handle,
1114                                     const struct GNUNET_PeerIdentity *peer)
1115 {
1116   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1117               "Received `%s' for peer `%s'\n",
1118               "RESET BACKOFF",
1119               GNUNET_i2s (peer));
1120
1121   GNUNET_break (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses,
1122                                               &peer->hashPubKey,
1123                                               &reset_address_it,
1124                                               NULL));
1125 }
1126
1127
1128 void
1129 GAS_addresses_change_preference (struct GAS_Addresses_Handle *handle,
1130                                  void *client,
1131                                  const struct GNUNET_PeerIdentity *peer,
1132                                  enum GNUNET_ATS_PreferenceKind kind,
1133                                  float score)
1134 {
1135   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1136               "Received `%s' for peer `%s' for client %p\n",
1137               "CHANGE PREFERENCE",
1138               GNUNET_i2s (peer), client);
1139
1140   if (GNUNET_NO == handle->running)
1141     return;
1142
1143   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (handle->addresses,
1144                                                           &peer->hashPubKey))
1145   {
1146       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1147                   "Received `%s' for unknown peer `%s' from client %p\n",
1148                   "CHANGE PREFERENCE",
1149                   GNUNET_i2s (peer), client);
1150       return;
1151   }
1152
1153   /* Tell solver about update */
1154   handle->s_pref (handle->solver, client, peer, kind, score);
1155 }
1156
1157
1158 /**
1159  * Load quotas for networks from configuration
1160  *
1161  * @param cfg configuration handle
1162  * @param out_dest where to write outbound quotas
1163  * @param in_dest where to write inbound quotas
1164  * @param dest_length length of inbound and outbound arrays
1165  * @return number of networks loaded
1166  */
1167 static unsigned int
1168 load_quotas (const struct GNUNET_CONFIGURATION_Handle *cfg, unsigned long long *out_dest, unsigned long long *in_dest, int dest_length)
1169 {
1170   char *network_str[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkTypeString;
1171   char * entry_in = NULL;
1172   char * entry_out = NULL;
1173   char * quota_out_str;
1174   char * quota_in_str;
1175   int c;
1176   int res;
1177
1178   for (c = 0; (c < GNUNET_ATS_NetworkTypeCount) && (c < dest_length); c++)
1179   {
1180     in_dest[c] = 0;
1181     out_dest[c] = 0;
1182     GNUNET_asprintf (&entry_out, "%s_QUOTA_OUT", network_str[c]);
1183     GNUNET_asprintf (&entry_in, "%s_QUOTA_IN", network_str[c]);
1184
1185     /* quota out */
1186     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_out, &quota_out_str))
1187     {
1188       res = GNUNET_NO;
1189       if (0 == strcmp(quota_out_str, GNUNET_ATS_MaxBandwidthString))
1190       {
1191         out_dest[c] = GNUNET_ATS_MaxBandwidth;
1192         res = GNUNET_YES;
1193       }
1194       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_out_str, &out_dest[c])))
1195         res = GNUNET_YES;
1196       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_out,  &out_dest[c])))
1197          res = GNUNET_YES;
1198
1199       if (GNUNET_NO == res)
1200       {
1201           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1202               network_str[c], quota_out_str, GNUNET_ATS_DefaultBandwidth);
1203           out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1204       }
1205       else
1206       {
1207           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Outbound quota configure for network `%s' is %llu\n"),
1208               network_str[c], out_dest[c]);
1209       }
1210       GNUNET_free (quota_out_str);
1211     }
1212     else
1213     {
1214       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configured for network `%s', assigning default bandwidth %llu\n"),
1215           network_str[c], GNUNET_ATS_DefaultBandwidth);
1216       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1217     }
1218
1219     /* quota in */
1220     if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "ats", entry_in, &quota_in_str))
1221     {
1222       res = GNUNET_NO;
1223       if (0 == strcmp(quota_in_str, GNUNET_ATS_MaxBandwidthString))
1224       {
1225         in_dest[c] = GNUNET_ATS_MaxBandwidth;
1226         res = GNUNET_YES;
1227       }
1228       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_STRINGS_fancy_size_to_bytes (quota_in_str, &in_dest[c])))
1229         res = GNUNET_YES;
1230       if ((GNUNET_NO == res) && (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cfg, "ats", entry_in,  &in_dest[c])))
1231          res = GNUNET_YES;
1232
1233       if (GNUNET_NO == res)
1234       {
1235           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not load quota for network `%s':  `%s', assigning default bandwidth %llu\n"),
1236               network_str[c], quota_in_str, GNUNET_ATS_DefaultBandwidth);
1237           in_dest[c] = GNUNET_ATS_DefaultBandwidth;
1238       }
1239       else
1240       {
1241           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Inbound quota configured for network `%s' is %llu\n"),
1242               network_str[c], in_dest[c]);
1243       }
1244       GNUNET_free (quota_in_str);
1245     }
1246     else
1247     {
1248       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _("No outbound quota configure for network `%s', assigning default bandwidth %llu\n"),
1249           network_str[c], GNUNET_ATS_DefaultBandwidth);
1250       out_dest[c] = GNUNET_ATS_DefaultBandwidth;
1251     }
1252     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]);
1253     GNUNET_free (entry_out);
1254     GNUNET_free (entry_in);
1255   }
1256   return GNUNET_ATS_NetworkTypeCount;
1257 }
1258
1259
1260 static void
1261 bandwidth_changed_cb (void *cls, struct ATS_Address *address)
1262 {
1263   struct GAS_Addresses_Handle *handle = cls;
1264   struct GAS_Addresses_Suggestion_Requests *cur;
1265
1266   GNUNET_assert (handle != NULL);
1267   GNUNET_assert (address != NULL);
1268
1269   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Bandwidth assignment changed for peer %s \n", GNUNET_i2s(&address->peer));
1270   struct GNUNET_ATS_Information *ats;
1271   unsigned int ats_count;
1272
1273   cur = handle->r_head;
1274   while (NULL != cur)
1275   {
1276       if (0 == memcmp (&address->peer, &cur->id, sizeof (cur->id)))
1277         break; /* we have an address request pending*/
1278       cur = cur->next;
1279   }
1280   if (NULL == cur)
1281   {
1282       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283                   "Nobody is interested in peer `%s' :(\n",GNUNET_i2s (&address->peer));
1284       return;
1285   }
1286
1287   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288               "Sending bandwidth update for peer `%s'\n",GNUNET_i2s (&address->peer));
1289
1290   ats_count = assemble_ats_information (address, &ats);
1291   GAS_scheduling_transmit_address_suggestion (&address->peer,
1292                                               address->plugin,
1293                                               address->addr, address->addr_len,
1294                                               address->session_id,
1295                                               ats, ats_count,
1296                                               address->assigned_bw_out,
1297                                               address->assigned_bw_in);
1298   GNUNET_free (ats);
1299 }
1300
1301
1302 /**
1303  * Initialize address subsystem.
1304  *
1305  * @param cfg configuration to use
1306  * @param stats the statistics handle to use
1307  */
1308 struct GAS_Addresses_Handle *
1309 GAS_addresses_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1310                     const struct GNUNET_STATISTICS_Handle *stats)
1311 {
1312   struct GAS_Addresses_Handle *ah;
1313   int quotas[GNUNET_ATS_NetworkTypeCount] = GNUNET_ATS_NetworkType;
1314   unsigned long long  quotas_in[GNUNET_ATS_NetworkTypeCount];
1315   unsigned long long  quotas_out[GNUNET_ATS_NetworkTypeCount];
1316   int quota_count;
1317   char *mode_str;
1318   int c;
1319
1320   ah = GNUNET_malloc (sizeof (struct GAS_Addresses_Handle));
1321   ah->running = GNUNET_NO;
1322
1323   ah->stat = (struct GNUNET_STATISTICS_Handle *) stats;
1324   /* Initialize the addresses database */
1325   ah->addresses = GNUNET_CONTAINER_multihashmap_create (128, GNUNET_NO);
1326   GNUNET_assert (NULL != ah->addresses);
1327
1328   /* Figure out configured solution method */
1329   if (GNUNET_SYSERR == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "MODE", &mode_str))
1330   {
1331       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "No ressource assignment method configured, using simplistic approch\n");
1332       ah->ats_mode = MODE_SIMPLISTIC;
1333   }
1334   else
1335   {
1336       for (c = 0; c < strlen (mode_str); c++)
1337         mode_str[c] = toupper (mode_str[c]);
1338       if (0 == strcmp (mode_str, "SIMPLISTIC"))
1339       {
1340           ah->ats_mode = MODE_SIMPLISTIC;
1341       }
1342       else if (0 == strcmp (mode_str, "MLP"))
1343       {
1344           ah->ats_mode = MODE_MLP;
1345 #if !HAVE_LIBGLPK
1346           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Assignment method `%s' configured, but GLPK is not availabe, please install \n", mode_str);
1347           ah->ats_mode = MODE_SIMPLISTIC;
1348 #endif
1349       }
1350       else
1351       {
1352           GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Invalid ressource assignment method `%s' configured, using simplistic approch\n", mode_str);
1353           ah->ats_mode = MODE_SIMPLISTIC;
1354       }
1355       GNUNET_free (mode_str);
1356   }
1357   /* Start configured solution method */
1358   switch (ah->ats_mode)
1359   {
1360     case MODE_MLP:
1361       /* Init the MLP solver with default values */
1362 #if HAVE_LIBGLPK
1363       ah->ats_mode = MODE_MLP;
1364       ah->s_init = &GAS_mlp_init;
1365       ah->s_add = &GAS_mlp_address_add;
1366       ah->s_update = &GAS_mlp_address_update;
1367       ah->s_get = &GAS_mlp_get_preferred_address;
1368       ah->s_get_stop = &GAS_mlp_stop_get_preferred_address;
1369       ah->s_pref = &GAS_mlp_address_change_preference;
1370       ah->s_del =  &GAS_mlp_address_delete;
1371       ah->s_done = &GAS_mlp_done;
1372 #else
1373       GNUNET_free (ah);
1374       return NULL;
1375 #endif
1376       break;
1377     case MODE_SIMPLISTIC:
1378       /* Init the simplistic solver with default values */
1379       ah->ats_mode = MODE_SIMPLISTIC;
1380       ah->s_init = &GAS_simplistic_init;
1381       ah->s_add = &GAS_simplistic_address_add;
1382       ah->s_update = &GAS_simplistic_address_update;
1383       ah->s_get = &GAS_simplistic_get_preferred_address;
1384       ah->s_get_stop = &GAS_simplistic_stop_get_preferred_address;
1385       ah->s_pref = &GAS_simplistic_address_change_preference;
1386       ah->s_del  = &GAS_simplistic_address_delete;
1387       ah->s_done = &GAS_simplistic_done;
1388       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ATS started in %s mode\n", "SIMPLISTIC");
1389       break;
1390     default:
1391       return NULL;
1392       break;
1393   }
1394
1395   GNUNET_assert (NULL != ah->s_init);
1396   GNUNET_assert (NULL != ah->s_add);
1397   GNUNET_assert (NULL != ah->s_update);
1398   GNUNET_assert (NULL != ah->s_get);
1399   GNUNET_assert (NULL != ah->s_get_stop);
1400   GNUNET_assert (NULL != ah->s_pref);
1401   GNUNET_assert (NULL != ah->s_del);
1402   GNUNET_assert (NULL != ah->s_done);
1403
1404   quota_count = load_quotas(cfg, quotas_in, quotas_out, GNUNET_ATS_NetworkTypeCount);
1405
1406   ah->solver = ah->s_init (cfg, stats, quotas, quotas_in, quotas_out, quota_count, &bandwidth_changed_cb, ah);
1407   if (NULL == ah->solver)
1408   {
1409     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to initialize solver!\n");
1410     GNUNET_free (ah);
1411     return NULL;
1412   }
1413
1414   /* up and running */
1415   ah->running = GNUNET_YES;
1416   return ah;
1417 }
1418
1419
1420 /**
1421  * Free memory of address.
1422  *
1423  * @param cls NULL
1424  * @param key peer identity (unused)
1425  * @param value the 'struct ATS_Address' to free
1426  * @return GNUNET_OK (continue to iterate)
1427  */
1428 static int
1429 free_address_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1430 {
1431   struct GAS_Addresses_Handle *handle = cls;
1432   struct ATS_Address *aa = value;
1433   handle->s_del (handle->solver, handle->addresses, aa, GNUNET_NO);
1434   destroy_address (handle, aa);
1435   return GNUNET_OK;
1436 }
1437
1438
1439 void
1440 GAS_addresses_destroy_all (struct GAS_Addresses_Handle *handle)
1441 {
1442   if (GNUNET_NO == handle->running)
1443     return;
1444
1445   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1446               "Received `%s'\n",
1447               "DESTROY ALL");
1448
1449   if (handle->addresses != NULL)
1450     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &free_address_it, handle);
1451 }
1452
1453
1454 /**
1455  * Shutdown address subsystem.
1456  */
1457 void
1458 GAS_addresses_done (struct GAS_Addresses_Handle *handle)
1459 {
1460   struct GAS_Addresses_Suggestion_Requests *cur;
1461
1462   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463               "Shutting down addresses\n");
1464   GNUNET_assert (NULL != handle);
1465   GAS_addresses_destroy_all (handle);
1466   handle->running = GNUNET_NO;
1467   GNUNET_CONTAINER_multihashmap_destroy (handle->addresses);
1468   handle->addresses = NULL;
1469   while (NULL != (cur = handle->r_head))
1470   {
1471       GNUNET_CONTAINER_DLL_remove (handle->r_head, handle->r_tail, cur);
1472       GNUNET_free (cur);
1473   }
1474   handle->s_done (handle->solver);
1475   GNUNET_free (handle);
1476   /* Stop configured solution method */
1477
1478 }
1479
1480 struct PeerIteratorContext
1481 {
1482   GNUNET_ATS_Peer_Iterator it;
1483   void *it_cls;
1484   struct GNUNET_CONTAINER_MultiHashMap *peers_returned;
1485 };
1486
1487 static int
1488 peer_it (void *cls,
1489          const struct GNUNET_HashCode * key,
1490          void *value)
1491 {
1492   struct PeerIteratorContext *ip_ctx = cls;
1493   struct GNUNET_PeerIdentity tmp;
1494
1495   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(ip_ctx->peers_returned, key))
1496   {
1497       GNUNET_CONTAINER_multihashmap_put(ip_ctx->peers_returned, key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1498       tmp.hashPubKey = (*key);
1499       ip_ctx->it (ip_ctx->it_cls, &tmp);
1500   }
1501
1502   return GNUNET_OK;
1503 }
1504
1505 /**
1506  * Return all peers currently known to ATS
1507  *
1508  * @param handle the address handle
1509  * @param p_it the iterator to call for every peer, callbach with id == NULL
1510  *        when done
1511  * @param p_it_cls the closure for the iterator
1512  */
1513 void
1514 GAS_addresses_iterate_peers (struct GAS_Addresses_Handle *handle, GNUNET_ATS_Peer_Iterator p_it, void *p_it_cls)
1515 {
1516   struct PeerIteratorContext ip_ctx;
1517   unsigned int size;
1518
1519   if (NULL == p_it)
1520       return;
1521   GNUNET_assert (NULL != handle->addresses);
1522
1523   size = GNUNET_CONTAINER_multihashmap_size(handle->addresses);
1524   if (0 != size)
1525   {
1526     ip_ctx.it = p_it;
1527     ip_ctx.it_cls = p_it_cls;
1528     ip_ctx.peers_returned = GNUNET_CONTAINER_multihashmap_create (size, GNUNET_NO);
1529     GNUNET_CONTAINER_multihashmap_iterate (handle->addresses, &peer_it, &ip_ctx);
1530     GNUNET_CONTAINER_multihashmap_destroy (ip_ctx.peers_returned);
1531   }
1532   p_it (p_it_cls, NULL);
1533 }
1534
1535 struct PeerInfoIteratorContext
1536 {
1537   GNUNET_ATS_PeerInfo_Iterator it;
1538   void *it_cls;
1539 };
1540
1541
1542 static int 
1543 peerinfo_it (void *cls,
1544              const struct GNUNET_HashCode * key,
1545              void *value)
1546 {
1547   struct PeerInfoIteratorContext *pi_ctx = cls;
1548   struct ATS_Address *addr = (struct ATS_Address *)  value;
1549   struct GNUNET_ATS_Information *ats;
1550   uint32_t ats_count;
1551
1552   if (NULL != pi_ctx->it)
1553   {
1554     ats_count = assemble_ats_information (addr, &ats);
1555
1556     pi_ctx->it (pi_ctx->it_cls,
1557                 &addr->peer,
1558                 addr->plugin,
1559                 addr->addr, addr->addr_len,
1560                 addr->active,
1561                 ats, ats_count,
1562                 addr->assigned_bw_out,
1563                 addr->assigned_bw_in);
1564     GNUNET_free (ats);
1565   }
1566   return GNUNET_YES;
1567 }
1568
1569
1570 /**
1571  * Return all peers currently known to ATS
1572  *
1573  * @param handle the address handle
1574  * @param peer the respective peer
1575  * @param pi_it the iterator to call for every peer
1576  * @param pi_it_cls the closure for the iterator
1577  */
1578 void
1579 GAS_addresses_get_peer_info (struct GAS_Addresses_Handle *handle,
1580                              const struct GNUNET_PeerIdentity *peer,
1581                              GNUNET_ATS_PeerInfo_Iterator pi_it,
1582                              void *pi_it_cls)
1583 {
1584   struct PeerInfoIteratorContext pi_ctx;
1585   struct GNUNET_BANDWIDTH_Value32NBO zero_bw;
1586   GNUNET_assert (NULL != peer);
1587   GNUNET_assert (NULL != handle->addresses);
1588   if (NULL == pi_it)
1589     return; /* does not make sense without callback */
1590
1591   zero_bw = GNUNET_BANDWIDTH_value_init (0);
1592   pi_ctx.it = pi_it;
1593   pi_ctx.it_cls = pi_it_cls;
1594
1595   GNUNET_CONTAINER_multihashmap_get_multiple (handle->addresses, &peer->hashPubKey, &peerinfo_it, &pi_ctx);
1596
1597   if (NULL != pi_it)
1598     pi_it (pi_it_cls, NULL, NULL, NULL, 0, GNUNET_NO, NULL, 0, zero_bw, zero_bw);
1599
1600 }
1601
1602
1603 /* end of gnunet-service-ats_addresses.c */