78bde6ec264d4a5d07b153ac06d10d250b0e367b
[oweals/gnunet.git] / src / ats / gnunet-service-ats_addresses.c
1 /*
2  This file is part of GNUnet.
3  (C) 2011-2015 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-service-ats_addresses.h"
29 #include "gnunet-service-ats_performance.h"
30 #include "gnunet-service-ats_normalization.h"
31 #include "gnunet-service-ats_plugins.h"
32
33
34 /**
35  * NOTE: Do not change this documentation. This documentation is based on
36  * gnunet.org:/vcs/fsnsg/2014-p2p-ats.git/tech-doku/ats-tech-guide.tex
37  * use build_txt.sh to generate plaintext output
38  *
39  *   1 ATS addresses : ATS address management
40  *
41  *    This ATS addresses ("addresses") component manages the addresses known to
42  *    ATS service and suggests addresses to transport service when it is
43  *    interested in address suggestion for a peer. ATS addresses also
44  *    instantiates the bandwidth assignment mechanism (solver), notifies it
45  *    about changes to addresses and forwards changes to bandwidth assignments
46  *    to transport, depending if transport is interested in this change.
47  *
48  *     1.1 Input data
49  *
50  *       1.1.1 Addresses
51  *
52  *    Addresses are added by specifying peer ID, plugin, address, address length
53  *    and session, if available. ATS information can be specified if available.
54  *
55  *       1.1.2 Networks
56  *
57  *    ATS specifies a fix set of networks an address can belong to. For each
58  *    network an inbound and outbound quota will be specified. The available
59  *    networks and addtional helper varaibles are defined in
60  *    gnunet_ats_service.h. At the moment 5 networks are defined:
61  *      * GNUNET_ATS_NET_UNSPECIFIED
62  *      * GNUNET_ATS_NET_LOOPBACK
63  *      * GNUNET_ATS_NET_LAN
64  *      * GNUNET_ATS_NET_WAN
65  *      * GNUNET_ATS_NET_WLAN
66  *
67  *    The total number of networks defined is stored in
68  *    GNUNET_ATS_NetworkTypeCount GNUNET_ATS_NetworkType can be used array
69  *    initializer for an int array, while GNUNET_ATS_NetworkType is an
70  *    initializer for a char array containing a string description of all
71  *    networks
72  *
73  *       1.1.3 Quotas
74  *
75  *    An inbound and outbound quota for each of the networks mentioned in 1.1.2
76  *    is loaded from ats configuration during initialization. This quota defines
77  *    to total amount of inbound and outbound traffic allowed for a specific
78  *    network. The configuration values used are in section ats:
79  *      * "NETWORK"_QUOTA_IN = <value>
80  *      * "NETWORK"_QUOTA_IN = <value>
81  *
82  *    You can specify quotas by setting the <value> to a:
83  *      * unrestricted: unlimited
84  *      * number of bytes: e.g. 10240
85  *      * fancy value: e.g. 64 Kib
86  *
87  *    unlimited is defined as GNUNET_ATS_MaxBandwidthString and equivalent to
88  *    the value GNUNET_ATS_MaxBandwidth Important predefined values for quotas
89  *    are:
90  *      * GNUNET_ATS_DefaultBandwidth: 65536
91  *      * GNUNET_ATS_MaxBandwidth: UINT32_MAX
92  *      * GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT: 1024
93  *
94  *    Details of loading quotas and default values will be described on
95  *
96  *       1.1.4 Preference values
97  *
98  *     1.2 Data structures used
99  *
100  *    Addresse uses struct ATS_Address for each address. The structs are stored
101  *    in a linked list and provides a pointer void *solver_information for the
102  *    solver to store address specific information. It provides the int values
103  *    active which is set to GNUNET_YES if the address is select for transport
104  *    use and used, representing that transport service is actively using this
105  *    address. Address information are stored in peer, addr, addr_len, plugin.
106  *
107  *     1.3 Initialization
108  *
109  *    During initialization a hashmap to store addresses is created. The quotas
110  *    for all networks defined for ATS are loaded from configuration. For each
111  *    network first the logic will check if the string
112  *    GNUNET_ATS_MaxBandwidthString is configured, if not it will try to convert
113  *    the configured value as a fancy size and if this fails it will try to use
114  *    it as a value_number. If no configuration value is found it will assign
115  *    GNUNET_ATS_DefaultBandwidth. The most important step is to load the
116  *    configured solver using configuration "[ats]:MODE". Current solvers are
117  *    MODE_PROPORTIONAL, MODE_MLP. Interaction is done using a solver API
118  *
119  *     1.4 Solver API
120  *
121  *    Solver functions:
122  *      * s_init: init the solver with required information
123  *      * s_add: add a new address
124  *      * s_update: update ATS values or session for an address
125  *      * s_get: get prefered address for a peer
126  *      * s_del: delete an address
127  *      * s_pref: change preference value for a peer
128  *      * s_done: shutdown solver
129  *
130  *    Callbacks: addresses provides a bandwidth_changed_cb callback to the
131  *    solver which is called when bandwidth assigned to peer has changed
132  *
133  *     1.5 Shutdown
134  *
135  *    During shutdown all addresses are freed and the solver told to shutdown
136  *
137  *     1.6 Addresses and sessions
138  *
139  *    Addresses consist of the address itself and a numerical session. When a
140  *    new address without a session is added it has no session, so it gets
141  *    session 0 assigned. When an address with a session is added and an address
142  *    object with session 0 is found, this object is updated with the session
143  *    otherwise a new address object with this session assigned is created.
144  *
145  *       1.6.1 Terminology
146  *
147  *    Addresses a1,a2 with session s1, s2 are "exact" if:
148  *    (a1 == a2)&&(s1 == s2)
149  *    Addresses a1,a2 with session s1, s2 are "equivalent" if:
150  *    (a1 == a2)&&((s1 == s2)||(s1 == 0)||(s2 == 0)
151  *
152  *     1.7 Address management
153  *
154  *    Transport service notifies ATS about changes to the addresses known to
155  *    him.
156  *
157  *       1.7.1 Adding an address
158  *
159  *    When transport learns a new address it tells ATS and ATS is telling
160  *    addresses about it using GAS_address_add. If not known to addresses it
161  *    creates a new address object and calls solver's s_add. ATS information are
162  *    deserialized and solver is notified about the session and ATS information
163  *    using s_update.
164  *
165  *       1.7.2 Updating an address
166  *
167  *    Addresses does an lookup up for the existing address with the given
168  *    session. If disassembles included ATS information and notifies the solver
169  *    using s_update about the update.
170  *
171  *       1.7.3 Deleting an address
172  *
173  *    Addresses does an lookup for the exact address and session and if removes
174  *    this address. If session != 0 the session is set to 0 and the address is
175  *    kept. If session == 0, the addresses is removed.
176  *
177  *       1.7.4 Requesting an address suggestion
178  *
179  *    The address client issues a request address message to be notified about
180  *    address suggestions for a specific peer. Addresses asks the solver with
181  *    s_get. If no address is available, it will not send a response, otherwise
182  *    it will respond with the choosen address.
183  *
184  *       1.7.5 Address suggestions
185  *
186  *    Addresses will notify the client automatically on any bandwidth_changed_cb
187  *    by the solver if a address suggestion request is pending. If no address is
188  *    available it will not respond at all If the client is not interested
189  *    anymore, it has to cancel the address suggestion request.
190  *
191  *       1.7.6 Address lifecycle
192  *
193  *      * (add address)
194  *      * (updated address)
195  *      * (delete address)
196  *
197  *     1.8 Bandwidth assignment
198  *
199  *    The addresses are used to perform resource allocation operations. ATS
200  *    addresses takes care of instantiating the solver configured and notifies
201  *    the respective solver about address changes and receives changes to the
202  *    bandwidth assignment from the solver. The current bandwidth assignment is
203  *    sent to transport. The specific solvers will be described in the specific
204  *    section.
205  *
206  *     1.9 Changing peer preferences
207  *
208  *    The bandwidth assigned to a peer can be influenced by setting a preference
209  *    for a peer. The prefernce will be given to to the solver with s_pref which
210  *    has to take care of the preference value
211  */
212
213
214 /**
215  * A multihashmap to store all addresses
216  */
217 struct GNUNET_CONTAINER_MultiPeerMap *GSA_addresses;
218
219
220 /**
221  * Update statistic on number of addresses.
222  */
223 static void
224 update_addresses_stat ()
225 {
226   GNUNET_STATISTICS_set (GSA_stats,
227                          "# addresses",
228                          GNUNET_CONTAINER_multipeermap_size (GSA_addresses),
229                          GNUNET_NO);
230 }
231
232
233 /**
234  * Disassemble ATS information and update performance information in address
235  *
236  * Updates existing information and adds new information
237  *
238  * @param dest destination address
239  * @param update source ATS information
240  * @param update_count number of ATS information in @a update
241  * @param delta_dest ats performance information which were updated
242  *                              including previous value
243  * @param delta_count number of ATS information in the @a delta_dest
244  * @return #GNUNET_YES if address was address updated, GNUNET_NO otherwise
245  */
246 static unsigned int
247 disassemble_ats_information (struct ATS_Address *dest,
248                              const struct GNUNET_ATS_Information *update,
249                              uint32_t update_count,
250                              struct GNUNET_ATS_Information **delta_dest,
251                              uint32_t *delta_count)
252 {
253   int c1;
254   int c2;
255   int found;
256   int change;
257   struct GNUNET_ATS_Information add_atsi[update_count];
258   struct GNUNET_ATS_Information delta_atsi[update_count];
259   struct GNUNET_ATS_Information *tmp_atsi;
260   uint32_t add_atsi_count;
261   uint32_t delta_atsi_count;
262
263   change = GNUNET_NO;
264   add_atsi_count = 0;
265   delta_atsi_count = 0;
266
267   if (0 == update_count)
268     return GNUNET_NO;
269
270   if (NULL == dest->atsi)
271   {
272     /* Create performance information */
273     dest->atsi =
274         GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
275     dest->atsi_count = update_count;
276     memcpy (dest->atsi,
277             update,
278             update_count * sizeof(struct GNUNET_ATS_Information));
279     *delta_dest =
280         GNUNET_malloc (update_count * sizeof (struct GNUNET_ATS_Information));
281     for (c1 = 0; c1 < update_count; c1++)
282     {
283       (*delta_dest)[c1].type = update[c1].type;
284       (*delta_dest)[c1].value = htonl (GNUNET_ATS_VALUE_UNDEFINED);
285     }
286     (*delta_count) = update_count;
287     return GNUNET_YES;
288   }
289
290   for (c1 = 0; c1 < update_count; c1++)
291   {
292     /* Update existing performance information */
293     found = GNUNET_NO;
294     for (c2 = 0; c2 < dest->atsi_count; c2++)
295     {
296       if (update[c1].type == dest->atsi[c2].type)
297       {
298         if (update[c1].value != dest->atsi[c2].value)
299         {
300           /* Save previous value in delta */
301           delta_atsi[delta_atsi_count] = dest->atsi[c2];
302           delta_atsi_count++;
303           /* Set new value */
304           dest->atsi[c2].value = update[c1].value;
305           change = GNUNET_YES;
306         }
307         found = GNUNET_YES;
308         break;
309       }
310     }
311     if (GNUNET_NO == found)
312     {
313       add_atsi[add_atsi_count] = update[c1];
314       add_atsi_count++;
315       delta_atsi[delta_atsi_count].type = update[c1].type;
316       delta_atsi[delta_atsi_count].value = htonl (GNUNET_ATS_VALUE_UNDEFINED);
317       delta_atsi_count++;
318     }
319   }
320
321   if (add_atsi_count > 0)
322   {
323     /* Extend ats performance information */
324
325     tmp_atsi = GNUNET_malloc ((dest->atsi_count + add_atsi_count) *
326         (sizeof (struct GNUNET_ATS_Information)));
327     memcpy (tmp_atsi, dest->atsi,
328         dest->atsi_count * sizeof(struct GNUNET_ATS_Information));
329     memcpy (&tmp_atsi[dest->atsi_count], add_atsi,
330         add_atsi_count * sizeof(struct GNUNET_ATS_Information));
331     GNUNET_free (dest->atsi);
332     dest->atsi = tmp_atsi;
333     dest->atsi_count = dest->atsi_count + add_atsi_count;
334     change = GNUNET_YES;
335   }
336
337   if (delta_atsi_count > 0)
338   {
339     /* Copy delta */
340     (*delta_dest) =
341         GNUNET_malloc (delta_atsi_count * sizeof (struct GNUNET_ATS_Information));
342     memcpy ((*delta_dest), delta_atsi,
343         delta_atsi_count * sizeof(struct GNUNET_ATS_Information));
344     (*delta_count) = delta_atsi_count;
345   }
346
347   return change;
348 }
349
350
351 /**
352  * Free the given address
353  *
354  * @param addr address to destroy
355  */
356 static void
357 free_address (struct ATS_Address *addr)
358 {
359   GNUNET_CONTAINER_multipeermap_remove (GSA_addresses,
360                                         &addr->peer,
361                                         addr);
362   update_addresses_stat ();
363   GAS_plugin_delete_address (addr);
364   GAS_performance_notify_all_clients (&addr->peer,
365                                       addr->plugin,
366                                       addr->addr,
367                                       addr->addr_len,
368                                       GNUNET_NO,
369                                       NULL, 0,
370                                       GNUNET_BANDWIDTH_ZERO,
371                                       GNUNET_BANDWIDTH_ZERO);
372   GNUNET_free (addr->plugin);
373   GNUNET_free_non_null (addr->atsi);
374   GNUNET_free (addr);
375 }
376
377
378 /**
379  * Create a ATS_address with the given information
380  *
381  * @param peer peer
382  * @param plugin_name plugin
383  * @param plugin_addr address
384  * @param plugin_addr_len address length
385  * @param local_address_info additional local info for the address
386  * @param session_id session identifier, can never be 0
387  * @return the ATS_Address
388  */
389 static struct ATS_Address *
390 create_address (const struct GNUNET_PeerIdentity *peer,
391                 const char *plugin_name,
392                 const void *plugin_addr,
393                 size_t plugin_addr_len,
394                 uint32_t local_address_info,
395                 uint32_t session_id)
396 {
397   struct ATS_Address *aa;
398   unsigned int c1;
399   unsigned int c2;
400
401   aa = GNUNET_malloc (sizeof (struct ATS_Address) + plugin_addr_len);
402   aa->peer = *peer;
403   aa->addr_len = plugin_addr_len;
404   aa->addr = &aa[1];
405   memcpy (&aa[1],
406           plugin_addr,
407           plugin_addr_len);
408   aa->plugin = GNUNET_strdup (plugin_name);
409   aa->session_id = session_id;
410   aa->local_address_info = local_address_info;
411
412   for (c1 = 0; c1 < GNUNET_ATS_QualityPropertiesCount; c1++)
413   {
414     aa->atsin[c1].avg_queue_index = 0;
415     for (c2 = 0; c2 < GAS_normalization_queue_length; c2++)
416       aa->atsin[c1].atsi_abs[c2] = GNUNET_ATS_VALUE_UNDEFINED;
417   }
418   return aa;
419 }
420
421
422 /**
423  * Closure for #find_address_cb()
424  */
425 struct FindAddressContext
426 {
427   /**
428    * Session Id to look for.
429    */
430   uint32_t session_id;
431
432   /**
433    * Where to store matching address result.
434    */
435   struct ATS_Address *exact_address;
436
437 };
438
439
440 /**
441  * Find session matching given session ID.
442  *
443  * @param cls a `struct FindAddressContext`
444  * @param key peer id
445  * @param value the address to compare with
446  * @return #GNUNET_YES to continue, #GNUNET_NO if address is found
447  */
448 static int
449 find_address_cb (void *cls,
450                  const struct GNUNET_PeerIdentity *key,
451                  void *value)
452 {
453   struct FindAddressContext *fac = cls;
454   struct ATS_Address *aa = value;
455
456   if (aa->session_id == fac->session_id)
457   {
458     fac->exact_address = aa;
459     return GNUNET_NO;
460   }
461   return GNUNET_YES;
462 }
463
464
465 /**
466  * Find the exact address
467  *
468  * @param peer peer
469  * @param session_id session id, can never be 0
470  * @return an ATS_address or NULL
471  */
472 static struct ATS_Address *
473 find_exact_address (const struct GNUNET_PeerIdentity *peer,
474                     uint32_t session_id)
475 {
476   struct FindAddressContext fac;
477
478   fac.exact_address = NULL;
479   fac.session_id = session_id;
480   GNUNET_CONTAINER_multipeermap_get_multiple (GSA_addresses,
481                                               peer,
482                                               &find_address_cb, &fac);
483   return fac.exact_address;
484 }
485
486
487 /**
488  * Extract an ATS performance info from an address
489  *
490  * @param address the address
491  * @param type the type to extract in HBO
492  * @return the value in HBO or #GNUNET_ATS_VALUE_UNDEFINED in HBO if value does not exist
493  */
494 static int
495 get_performance_info (struct ATS_Address *address,
496                       uint32_t type)
497 {
498   uint32_t c1;
499
500   if ((NULL == address->atsi) || (0 == address->atsi_count))
501     return GNUNET_ATS_VALUE_UNDEFINED;
502
503   for (c1 = 0; c1 < address->atsi_count; c1++)
504   {
505     if (ntohl (address->atsi[c1].type) == type)
506       return ntohl (address->atsi[c1].value);
507   }
508   return GNUNET_ATS_VALUE_UNDEFINED;
509 }
510
511
512 /**
513  * Add a new address for a peer.
514  *
515  * @param peer peer
516  * @param plugin_name transport plugin name
517  * @param plugin_addr plugin address
518  * @param plugin_addr_len length of the plugin address in @a plugin_addr
519  * @param local_address_info the local address for the address
520  * @param session_id session id, can be 0
521  * @param atsi performance information for this address
522  * @param atsi_count number of performance information contained in @a atsi
523  */
524 void
525 GAS_addresses_add (const struct GNUNET_PeerIdentity *peer,
526                    const char *plugin_name,
527                    const void *plugin_addr,
528                    size_t plugin_addr_len,
529                    uint32_t local_address_info,
530                    uint32_t session_id,
531                    const struct GNUNET_ATS_Information *atsi,
532                    uint32_t atsi_count)
533 {
534   struct ATS_Address *new_address;
535   struct GNUNET_ATS_Information *atsi_delta;
536   uint32_t atsi_delta_count;
537   uint32_t addr_net;
538
539   if (NULL != find_exact_address (peer, session_id))
540   {
541     GNUNET_break (0);
542     return;
543   }
544   new_address = create_address (peer,
545                                 plugin_name,
546                                 plugin_addr,
547                                 plugin_addr_len,
548                                 local_address_info,
549                                 session_id);
550   atsi_delta = NULL;
551   disassemble_ats_information (new_address,
552                                atsi, atsi_count,
553                                &atsi_delta,
554                                &atsi_delta_count);
555   GNUNET_free_non_null (atsi_delta);
556   addr_net = get_performance_info (new_address, GNUNET_ATS_NETWORK_TYPE);
557   if (GNUNET_ATS_VALUE_UNDEFINED == addr_net)
558     addr_net = GNUNET_ATS_NET_UNSPECIFIED;
559
560   /* Add a new address */
561   new_address->t_added = GNUNET_TIME_absolute_get();
562   new_address->t_last_activity = GNUNET_TIME_absolute_get();
563   GNUNET_assert(GNUNET_OK ==
564                 GNUNET_CONTAINER_multipeermap_put (GSA_addresses,
565                                                    peer,
566                                                    new_address,
567                                                    GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
568   update_addresses_stat ();
569   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
570               "Adding new address for peer `%s' slot %u\n",
571               GNUNET_i2s (peer),
572               session_id);
573   /* Tell solver about new address */
574   GAS_plugin_new_address (new_address,
575                           addr_net,
576                           atsi,
577                           atsi_count);
578   /* Notify performance clients about new address */
579   GAS_performance_notify_all_clients (&new_address->peer,
580                                       new_address->plugin,
581                                       new_address->addr,
582                                       new_address->addr_len,
583                                       new_address->active,
584                                       new_address->atsi,
585                                       new_address->atsi_count,
586                                       GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_out),
587                                       GNUNET_BANDWIDTH_value_init (new_address->assigned_bw_in));
588 }
589
590
591 /**
592  * Update an address with new performance information for a peer.
593  *
594  * @param peer peer
595  * @param session_id session id, never 0
596  * @param atsi performance information for this address
597  * @param atsi_count number of performance information contained in @a atsi
598  */
599 void
600 GAS_addresses_update (const struct GNUNET_PeerIdentity *peer,
601                       uint32_t session_id,
602                       const struct GNUNET_ATS_Information *atsi,
603                       uint32_t atsi_count)
604 {
605   struct ATS_Address *aa;
606   struct GNUNET_ATS_Information *atsi_delta;
607   uint32_t atsi_delta_count;
608
609   /* Get existing address */
610   aa = find_exact_address (peer,
611                            session_id);
612   if (NULL == aa)
613   {
614     GNUNET_break (0);
615     return;
616   }
617   if (NULL == aa->solver_information)
618   {
619     GNUNET_break (0);
620     return;
621   }
622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
623               "Received ADDRESS_UPDATE for peer `%s' slot %u\n",
624               GNUNET_i2s (peer),
625               (unsigned int) session_id);
626
627   /* Update address */
628   aa->t_last_activity = GNUNET_TIME_absolute_get();
629   atsi_delta = NULL;
630   atsi_delta_count = 0;
631   if (GNUNET_YES ==
632       disassemble_ats_information (aa, atsi,
633                                    atsi_count,
634                                    &atsi_delta,
635                                    &atsi_delta_count))
636   {
637     /* Notify performance clients about updated address */
638     GAS_performance_notify_all_clients (&aa->peer,
639                                         aa->plugin,
640                                         aa->addr,
641                                         aa->addr_len,
642                                         aa->active,
643                                         aa->atsi,
644                                         aa->atsi_count,
645                                         GNUNET_BANDWIDTH_value_init (aa->assigned_bw_out),
646                                         GNUNET_BANDWIDTH_value_init (aa->assigned_bw_in));
647
648     GAS_normalization_normalize_property (aa,
649                                           atsi,
650                                           atsi_count);
651   }
652   GNUNET_free_non_null (atsi_delta);
653 }
654
655
656 /**
657  * Remove an address for a peer.
658  *
659  * @param peer peer
660  * @param session_id session id, can never be 0
661  */
662 void
663 GAS_addresses_destroy (const struct GNUNET_PeerIdentity *peer,
664                        uint32_t session_id)
665 {
666   struct ATS_Address *ea;
667
668   /* Get existing address */
669   ea = find_exact_address (peer,
670                            session_id);
671   if (NULL == ea)
672   {
673     GNUNET_break (0);
674     return;
675   }
676   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
677               "Received ADDRESS_DESTROYED for peer `%s' session %u\n",
678               GNUNET_i2s (peer),
679               session_id);
680   free_address (ea);
681 }
682
683
684 /**
685  * Initialize address subsystem. The addresses subsystem manages the addresses
686  * known and current performance information. It has a solver component
687  * responsible for the resource allocation. It tells the solver about changes
688  * and receives updates when the solver changes the resource allocation.
689  *
690  * @param server handle to our server
691  */
692 void
693 GAS_addresses_init (struct GNUNET_SERVER_Handle *server)
694 {
695   GSA_addresses = GNUNET_CONTAINER_multipeermap_create (128, GNUNET_NO);
696   update_addresses_stat ();
697 }
698
699
700 /**
701  * Destroy all addresses iterator
702  *
703  * @param cls NULL
704  * @param key peer identity (unused)
705  * @param value the 'struct ATS_Address' to free
706  * @return #GNUNET_OK (continue to iterate)
707  */
708 static int
709 destroy_all_address_it (void *cls,
710                         const struct GNUNET_PeerIdentity *key,
711                         void *value)
712 {
713   struct ATS_Address *aa = value;
714
715   free_address (aa);
716   return GNUNET_OK;
717 }
718
719
720 /**
721  * Remove all addresses
722  */
723 void
724 GAS_addresses_destroy_all ()
725 {
726   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
727               "Destroying all addresses\n");
728   GAS_plugin_solver_lock ();
729   GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses,
730                                          &destroy_all_address_it,
731                                          NULL);
732   GAS_plugin_solver_unlock ();
733 }
734
735
736 /**
737  * Shutdown address subsystem.
738  */
739 void
740 GAS_addresses_done ()
741 {
742   GNUNET_log(GNUNET_ERROR_TYPE_INFO,
743              "Shutting down addresses\n");
744   GAS_addresses_destroy_all ();
745   GNUNET_CONTAINER_multipeermap_destroy (GSA_addresses);
746   GSA_addresses = NULL;
747 }
748
749
750 /**
751  * Closure for #peerinfo_it().
752  */
753 struct PeerInfoIteratorContext
754 {
755   /**
756    * Function to call for each address.
757    */
758   GNUNET_ATS_PeerInfo_Iterator it;
759
760   /**
761    * Closure for @e it.
762    */
763   void *it_cls;
764 };
765
766
767 /**
768  * Iterator to iterate over a peer's addresses
769  *
770  * @param cls a `struct PeerInfoIteratorContext`
771  * @param key the peer id
772  * @param value the `struct ATS_address`
773  * @return #GNUNET_OK to continue
774  */
775 static int
776 peerinfo_it (void *cls,
777              const struct GNUNET_PeerIdentity *key,
778              void *value)
779 {
780   struct PeerInfoIteratorContext *pi_ctx = cls;
781   struct ATS_Address *addr = value;
782
783   pi_ctx->it (pi_ctx->it_cls,
784               &addr->peer,
785               addr->plugin,
786               addr->addr,
787               addr->addr_len,
788               addr->active,
789               addr->atsi, addr->atsi_count,
790               GNUNET_BANDWIDTH_value_init (addr->assigned_bw_out),
791               GNUNET_BANDWIDTH_value_init (addr->assigned_bw_in));
792   return GNUNET_OK;
793 }
794
795
796 /**
797  * Return information all peers currently known to ATS
798  *
799  * @param peer the respective peer, NULL for 'all' peers
800  * @param pi_it the iterator to call for every peer
801  * @param pi_it_cls the closure for @a pi_it
802  */
803 void
804 GAS_addresses_get_peer_info (const struct GNUNET_PeerIdentity *peer,
805                              GNUNET_ATS_PeerInfo_Iterator pi_it,
806                              void *pi_it_cls)
807 {
808   struct PeerInfoIteratorContext pi_ctx;
809
810   if (NULL == pi_it)
811   {
812     /* does not make sense without callback */
813     GNUNET_break (0);
814     return;
815   }
816   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
817               "Returning information for %s from a total of %u known addresses\n",
818               (NULL == peer)
819               ? "all peers"
820               : GNUNET_i2s (peer),
821               (unsigned int) GNUNET_CONTAINER_multipeermap_size (GSA_addresses));
822   pi_ctx.it = pi_it;
823   pi_ctx.it_cls = pi_it_cls;
824   if (NULL == peer)
825     GNUNET_CONTAINER_multipeermap_iterate (GSA_addresses,
826                                            &peerinfo_it,
827                                            &pi_ctx);
828   else
829     GNUNET_CONTAINER_multipeermap_get_multiple (GSA_addresses,
830                                                 peer,
831                                                 &peerinfo_it, &pi_ctx);
832   pi_it (pi_it_cls,
833          NULL, NULL, NULL, 0,
834          GNUNET_NO,
835          NULL, 0,
836          GNUNET_BANDWIDTH_ZERO,
837          GNUNET_BANDWIDTH_ZERO);
838 }
839
840
841 /**
842  * Information we need for the callbacks to return a list of addresses
843  * back to the client.
844  */
845 struct AddressIteration
846 {
847   /**
848    * Actual handle to the client.
849    */
850   struct GNUNET_SERVER_Client *client;
851
852   /**
853    * Are we sending all addresses, or only those that are active?
854    */
855   int all;
856
857   /**
858    * Which ID should be included in the response?
859    */
860   uint32_t id;
861
862 };
863
864
865 /**
866  * Send a #GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE with the
867  * given address details to the client identified in @a ai.
868  *
869  * @param ai our address information context (identifies the client)
870  * @param id the peer id this address is for
871  * @param plugin_name name of the plugin that supports this address
872  * @param plugin_addr address
873  * @param plugin_addr_len length of @a plugin_addr
874  * @param active #GNUNET_YES if this address is actively used
875  * @param atsi ats performance information
876  * @param atsi_count number of ats performance elements in @a atsi
877  * @param bandwidth_out current outbound bandwidth assigned to address
878  * @param bandwidth_in current inbound bandwidth assigned to address
879  */
880 static void
881 transmit_req_addr (struct AddressIteration *ai,
882                    const struct GNUNET_PeerIdentity *id,
883                    const char *plugin_name,
884                    const void *plugin_addr,
885                    size_t plugin_addr_len,
886                    int active,
887                    const struct GNUNET_ATS_Information *atsi,
888                    uint32_t atsi_count,
889                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
890                    struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in)
891
892 {
893   struct GNUNET_ATS_Information *atsp;
894   struct PeerInformationMessage *msg;
895   char *addrp;
896   size_t plugin_name_length;
897   size_t msize;
898   struct GNUNET_SERVER_NotificationContext *nc;
899
900   if (NULL != plugin_name)
901     plugin_name_length = strlen (plugin_name) + 1;
902   else
903     plugin_name_length = 0;
904   msize = sizeof (struct PeerInformationMessage) +
905           atsi_count * sizeof (struct GNUNET_ATS_Information) +
906           plugin_addr_len + plugin_name_length;
907   char buf[msize] GNUNET_ALIGN;
908
909   GNUNET_assert (msize < GNUNET_SERVER_MAX_MESSAGE_SIZE);
910   GNUNET_assert (atsi_count <
911                  GNUNET_SERVER_MAX_MESSAGE_SIZE /
912                  sizeof (struct GNUNET_ATS_Information));
913   msg = (struct PeerInformationMessage *) buf;
914   msg->header.size = htons (msize);
915   msg->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE);
916   msg->ats_count = htonl (atsi_count);
917   msg->id = htonl (ai->id);
918   if (NULL != id)
919     msg->peer = *id;
920   else
921     memset (&msg->peer, '\0', sizeof (struct GNUNET_PeerIdentity));
922   msg->address_length = htons (plugin_addr_len);
923   msg->address_active = ntohl (active);
924   msg->plugin_name_length = htons (plugin_name_length);
925   msg->bandwidth_out = bandwidth_out;
926   msg->bandwidth_in = bandwidth_in;
927   atsp = (struct GNUNET_ATS_Information *) &msg[1];
928   memcpy (atsp, atsi, sizeof (struct GNUNET_ATS_Information) * atsi_count);
929   addrp = (char *) &atsp[atsi_count];
930   if (NULL != plugin_addr)
931     memcpy (addrp, plugin_addr, plugin_addr_len);
932   if (NULL != plugin_name)
933     strcpy (&addrp[plugin_addr_len], plugin_name);
934   nc = *GNUNET_SERVER_client_get_user_context (ai->client,
935                                                struct GNUNET_SERVER_NotificationContext *);
936   if (NULL == nc)
937   {
938     GNUNET_break (0);
939     return;
940   }
941   GNUNET_SERVER_notification_context_unicast (nc,
942                                               ai->client,
943                                               &msg->header,
944                                               GNUNET_NO);
945 }
946
947
948 /**
949  * Iterator for #GAS_addresses_get_peer_info(), called with peer-specific
950  * information to be passed back to the client.
951  *
952  * @param cls closure with our `struct AddressIteration *`
953  * @param id the peer id
954  * @param plugin_name plugin name
955  * @param plugin_addr address
956  * @param plugin_addr_len length of @a plugin_addr
957  * @param active is address actively used
958  * @param atsi ats performance information
959  * @param atsi_count number of ats performance elements in @a atsi
960  * @param bandwidth_out current outbound bandwidth assigned to address
961  * @param bandwidth_in current inbound bandwidth assigned to address
962  */
963 static void
964 req_addr_peerinfo_it (void *cls,
965                       const struct GNUNET_PeerIdentity *id,
966                       const char *plugin_name,
967                       const void *plugin_addr,
968                       size_t plugin_addr_len,
969                       int active,
970                       const struct GNUNET_ATS_Information *atsi,
971                       uint32_t atsi_count,
972                       struct GNUNET_BANDWIDTH_Value32NBO bandwidth_out,
973                       struct GNUNET_BANDWIDTH_Value32NBO bandwidth_in)
974 {
975   struct AddressIteration *ai = cls;
976
977   if ( (NULL == id) &&
978        (NULL == plugin_name) &&
979        (NULL == plugin_addr) )
980   {
981     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982                 "Address iteration done for one peer\n");
983     return;
984   }
985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986               "Callback for %s peer `%s' plugin `%s' BW out %u, BW in %u\n",
987               (active == GNUNET_YES) ? "ACTIVE" : "INACTIVE",
988               GNUNET_i2s (id),
989               plugin_name,
990               (unsigned int) ntohl (bandwidth_out.value__),
991               (unsigned int) ntohl (bandwidth_in.value__));
992   /* Transmit result (either if address is active, or if
993      client wanted all addresses) */
994   if ( (GNUNET_YES != ai->all) &&
995        (GNUNET_YES != active))
996     return;
997   transmit_req_addr (ai,
998                      id,
999                      plugin_name,
1000                      plugin_addr, plugin_addr_len,
1001                      active,
1002                      atsi,
1003                      atsi_count,
1004                      bandwidth_out,
1005                      bandwidth_in);
1006 }
1007
1008
1009 /**
1010  * Handle 'address list request' messages from clients.
1011  *
1012  * @param cls unused, NULL
1013  * @param client client that sent the request
1014  * @param message the request message
1015  */
1016 void
1017 GAS_handle_request_address_list (void *cls,
1018                                  struct GNUNET_SERVER_Client *client,
1019                                  const struct GNUNET_MessageHeader *message)
1020 {
1021   struct AddressIteration ai;
1022   const struct AddressListRequestMessage *alrm;
1023   struct GNUNET_PeerIdentity allzeros;
1024
1025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1026               "Received ADDRESSLIST_REQUEST message\n");
1027   alrm = (const struct AddressListRequestMessage *) message;
1028   ai.all = ntohl (alrm->all);
1029   ai.id = ntohl (alrm->id);
1030   ai.client = client;
1031
1032   memset (&allzeros,
1033           '\0',
1034           sizeof (struct GNUNET_PeerIdentity));
1035   if (0 == memcmp (&alrm->peer,
1036                    &allzeros,
1037                    sizeof (struct GNUNET_PeerIdentity)))
1038   {
1039     /* Return addresses for all peers */
1040     GAS_addresses_get_peer_info (NULL,
1041                                  &req_addr_peerinfo_it,
1042                                  &ai);
1043   }
1044   else
1045   {
1046     /* Return addresses for a specific peer */
1047     GAS_addresses_get_peer_info (&alrm->peer,
1048                                  &req_addr_peerinfo_it,
1049                                  &ai);
1050   }
1051   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052               "Finished handling `%s' message\n",
1053               "ADDRESSLIST_REQUEST");
1054   transmit_req_addr (&ai,
1055                      NULL, NULL, NULL,
1056                      0, GNUNET_NO,
1057                      NULL, 0,
1058                      GNUNET_BANDWIDTH_ZERO,
1059                      GNUNET_BANDWIDTH_ZERO);
1060   GNUNET_SERVER_receive_done (client,
1061                               GNUNET_OK);
1062 }
1063
1064
1065
1066 /* end of gnunet-service-ats_addresses.c */