496a18b12b13049f5d73040ee220972bfeb960c7
[oweals/gnunet.git] / src / ats / ats_api_scheduling.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-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  * @file ats/ats_api_scheduling.c
22  * @brief automatic transport selection and outbound bandwidth determination
23  * @author Christian Grothoff
24  * @author Matthias Wachs
25  */
26 #include "platform.h"
27 #include "gnunet_ats_service.h"
28 #include "ats.h"
29
30
31 #define INTERFACE_PROCESSING_INTERVALL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
32
33 #define NOT_FOUND 0
34
35 /**
36  * Message in linked list we should send to the ATS service.  The
37  * actual binary message follows this struct.
38  */
39 struct PendingMessage
40 {
41
42   /**
43    * Kept in a DLL.
44    */
45   struct PendingMessage *next;
46
47   /**
48    * Kept in a DLL.
49    */
50   struct PendingMessage *prev;
51
52   /**
53    * Size of the message.
54    */
55   size_t size;
56
57   /**
58    * Is this the 'ATS_START' message?
59    */
60   int is_init;
61 };
62
63
64 /**
65  * Information we track per session.
66  */
67 struct SessionRecord
68 {
69   /**
70    * Identity of the peer (just needed for error checking).
71    */
72   struct GNUNET_PeerIdentity peer;
73
74   /**
75    * Session handle.
76    */
77   struct Session *session;
78
79   /**
80    * Set to #GNUNET_YES if the slot is used.
81    */
82   int slot_used;
83 };
84
85
86 struct ATS_Network
87 {
88   struct ATS_Network * next;
89
90   struct ATS_Network * prev;
91
92   struct sockaddr *network;
93
94   struct sockaddr *netmask;
95
96   socklen_t length;
97 };
98
99
100 /**
101  * Handle for address suggestions
102  */
103 struct GNUNET_ATS_SuggestHandle
104 {
105   struct GNUNET_ATS_SuggestHandle *prev;
106
107   struct GNUNET_ATS_SuggestHandle *next;
108
109   struct GNUNET_PeerIdentity id;
110 };
111
112
113 /**
114  * Handle to the ATS subsystem for bandwidth/transport scheduling information.
115  */
116 struct GNUNET_ATS_SchedulingHandle
117 {
118
119   /**
120    * Our configuration.
121    */
122   const struct GNUNET_CONFIGURATION_Handle *cfg;
123
124   /**
125    * Callback to invoke on suggestions.
126    */
127   GNUNET_ATS_AddressSuggestionCallback suggest_cb;
128
129   /**
130    * Closure for @e suggest_cb.
131    */
132   void *suggest_cb_cls;
133
134   /**
135    * DLL for suggestions head
136    */
137   struct GNUNET_ATS_SuggestHandle *sug_head;
138
139   /**
140    * DLL for suggestions tail
141    */
142   struct GNUNET_ATS_SuggestHandle *sug_tail;
143
144   /**
145    * Connection to ATS service.
146    */
147   struct GNUNET_CLIENT_Connection *client;
148
149   /**
150    * Head of list of messages for the ATS service.
151    */
152   struct PendingMessage *pending_head;
153
154   /**
155    * Tail of list of messages for the ATS service
156    */
157   struct PendingMessage *pending_tail;
158
159   /**
160    * Current request for transmission to ATS.
161    */
162   struct GNUNET_CLIENT_TransmitHandle *th;
163
164   /**
165    * Head of network list
166    */
167   struct ATS_Network *net_head;
168
169   /**
170    * Tail of network list
171    */
172   struct ATS_Network *net_tail;
173
174   /**
175    * Array of session objects (we need to translate them to numbers and back
176    * for the protocol; the offset in the array is the session number on the
177    * network).  Index 0 is always NULL and reserved to represent the NULL pointer.
178    * Unused entries are also NULL.
179    */
180   struct SessionRecord *session_array;
181
182   /**
183    * Task to trigger reconnect.
184    */
185   struct GNUNET_SCHEDULER_Task *task;
186
187   /**
188    * Task retrieving interfaces from the system
189    */
190   struct GNUNET_SCHEDULER_Task *interface_task;
191
192   /**
193    * Size of the @e session_array.
194    */
195   unsigned int session_array_size;
196
197   /**
198    * Should we reconnect to ATS due to some serious error?
199    */
200   int reconnect;
201 };
202
203
204 /**
205  * Re-establish the connection to the ATS service.
206  *
207  * @param sh handle to use to re-connect.
208  */
209 static void
210 reconnect (struct GNUNET_ATS_SchedulingHandle *sh);
211
212
213 /**
214  * Re-establish the connection to the ATS service.
215  *
216  * @param cls handle to use to re-connect.
217  * @param tc scheduler context
218  */
219 static void
220 reconnect_task (void *cls,
221                 const struct GNUNET_SCHEDULER_TaskContext *tc)
222 {
223   struct GNUNET_ATS_SchedulingHandle *sh = cls;
224
225   sh->task = NULL;
226   reconnect (sh);
227 }
228
229
230 /**
231  * Disconnect from ATS and then reconnect.
232  *
233  * @param sh our handle
234  */
235 static void
236 force_reconnect (struct GNUNET_ATS_SchedulingHandle *sh)
237 {
238   sh->reconnect = GNUNET_NO;
239   GNUNET_CLIENT_disconnect (sh->client);
240   sh->client = NULL;
241   sh->task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
242                                            &reconnect_task,
243                                            sh);
244 }
245
246
247 /**
248  * Transmit messages from the message queue to the service
249  * (if there are any, and if we are not already trying).
250  *
251  * @param sh handle to use
252  */
253 static void
254 do_transmit (struct GNUNET_ATS_SchedulingHandle *sh);
255
256
257 /**
258  * Type of a function to call when we receive a message
259  * from the service.
260  *
261  * @param cls the `struct GNUNET_ATS_SchedulingHandle`
262  * @param msg message received, NULL on timeout or fatal error
263  */
264 static void
265 process_ats_message (void *cls,
266                      const struct GNUNET_MessageHeader *msg);
267
268
269 /**
270  * We can now transmit a message to ATS. Do it.
271  *
272  * @param cls the `struct GNUNET_ATS_SchedulingHandle`
273  * @param size number of bytes we can transmit to ATS
274  * @param buf where to copy the messages
275  * @return number of bytes copied into @a buf
276  */
277 static size_t
278 transmit_message_to_ats (void *cls,
279                          size_t size,
280                          void *buf)
281 {
282   struct GNUNET_ATS_SchedulingHandle *sh = cls;
283   struct PendingMessage *p;
284   size_t ret;
285   char *cbuf;
286
287   sh->th = NULL;
288   if ((0 == size) || (NULL == buf))
289   {
290     force_reconnect (sh);
291     return 0;
292   }
293   ret = 0;
294   cbuf = buf;
295   while ((NULL != (p = sh->pending_head)) && (p->size <= size))
296   {
297     memcpy (&cbuf[ret],
298             &p[1],
299             p->size);
300     ret += p->size;
301     size -= p->size;
302     GNUNET_CONTAINER_DLL_remove (sh->pending_head,
303                                  sh->pending_tail,
304                                  p);
305     GNUNET_free (p);
306   }
307   do_transmit (sh);
308   return ret;
309 }
310
311
312 /**
313  * Transmit messages from the message queue to the service
314  * (if there are any, and if we are not already trying).
315  *
316  * @param sh handle to use
317  */
318 static void
319 do_transmit (struct GNUNET_ATS_SchedulingHandle *sh)
320 {
321   struct PendingMessage *p;
322
323   if (NULL != sh->th)
324     return;
325   if (NULL == (p = sh->pending_head))
326     return;
327   if (NULL == sh->client)
328     return;                     /* currently reconnecting */
329   sh->th =
330       GNUNET_CLIENT_notify_transmit_ready (sh->client, p->size,
331                                            GNUNET_TIME_UNIT_FOREVER_REL,
332                                            GNUNET_NO, &transmit_message_to_ats,
333                                            sh);
334 }
335
336
337 /**
338  * Find the session object corresponding to the given session ID.
339  *
340  * @param sh our handle
341  * @param session_id current session ID
342  * @param peer peer the session belongs to
343  * @return the session object (or NULL)
344  */
345 static struct Session *
346 find_session (struct GNUNET_ATS_SchedulingHandle *sh,
347               uint32_t session_id,
348               const struct GNUNET_PeerIdentity *peer)
349 {
350   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
351               "Find session %u from peer %s in %p\n",
352               (unsigned int) session_id, GNUNET_i2s (peer), sh);
353
354   if (session_id >= sh->session_array_size)
355   {
356     GNUNET_break (0);
357     return NULL;
358   }
359   if (0 == session_id)
360     return NULL;
361   if (sh->session_array[session_id].session == NULL)
362   {
363     GNUNET_break (0 ==
364                   memcmp (peer, &sh->session_array[session_id].peer,
365                           sizeof (struct GNUNET_PeerIdentity)));
366     return NULL;
367   }
368
369   if (0 !=
370       memcmp (peer, &sh->session_array[session_id].peer,
371               sizeof (struct GNUNET_PeerIdentity)))
372   {
373     GNUNET_break (0);
374     sh->reconnect = GNUNET_YES;
375     return NULL;
376   }
377   /* This check exploits the fact that first field of a session object
378    * is peer identity.
379    */
380   if (0 !=
381       memcmp (peer, sh->session_array[session_id].session,
382               sizeof (struct GNUNET_PeerIdentity)))
383   {
384     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
385               "Session %p belongs to peer `%s'\n",
386               sh->session_array[session_id].session, GNUNET_i2s_full ((struct GNUNET_PeerIdentity *) &sh->session_array[session_id].peer));
387 /*
388     GNUNET_break (0);
389     sh->reconnect = GNUNET_YES;
390     return NULL;
391 */
392   }
393   return sh->session_array[session_id].session;
394 }
395
396
397 /**
398  * Get an available session ID for the given session object.
399  *
400  * @param sh our handle
401  * @param session session object
402  * @param peer peer the session belongs to
403  * @return the session id
404  */
405 static uint32_t
406 find_empty_session_slot (struct GNUNET_ATS_SchedulingHandle *sh,
407                          struct Session *session,
408                          const struct GNUNET_PeerIdentity *peer)
409 {
410   unsigned int i;
411   unsigned int f;
412
413   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
414                    "ats-scheduling-api",
415                    "Get session ID for session %p from peer %s in %p\n",
416                    session,
417                    GNUNET_i2s (peer),
418                    sh);
419   if (NULL == session)
420     return NOT_FOUND;
421   f = 0;
422   for (i = 1; i < sh->session_array_size; i++)
423   {
424     if ((f == 0) && (sh->session_array[i].slot_used == GNUNET_NO))
425       f = i;
426   }
427   if (f == 0)
428   {
429     f = sh->session_array_size;
430     GNUNET_array_grow (sh->session_array, sh->session_array_size,
431                        sh->session_array_size * 2);
432   }
433   GNUNET_assert (f > 0);
434   sh->session_array[f].session = session;
435   sh->session_array[f].peer = *peer;
436   sh->session_array[f].slot_used = GNUNET_YES;
437
438   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
439               "Assigning session ID %u for session %p of peer %s in %p\n", f,
440               session, GNUNET_i2s (peer), sh);
441
442   return f;
443 }
444
445
446 /**
447  * Get the ID for the given session object.
448  *
449  * @param sh our handle
450  * @param session session object
451  * @param peer peer the session belongs to
452  * @return the session id or NOT_FOUND for error
453  */
454 static uint32_t
455 find_session_id (struct GNUNET_ATS_SchedulingHandle *sh,
456                  struct Session *session,
457                  const struct GNUNET_PeerIdentity *peer)
458 {
459   unsigned int i;
460   char * p2;
461
462   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
463               "Get session ID for session %p from peer %s in %p\n", session,
464               GNUNET_i2s (peer), sh);
465
466   if (NULL == session)
467     return NOT_FOUND;
468   for (i = 1; i < sh->session_array_size; i++)
469   {
470     if (session == sh->session_array[i].session)
471     {
472       if (0 != memcmp (peer, &sh->session_array[i].peer,
473                        sizeof (struct GNUNET_PeerIdentity)))
474       {
475         p2 = strdup (GNUNET_i2s (&sh->session_array[i].peer));
476         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, "ats-scheduling-api",
477                     "Session %p did not match: old session was for peer `%s' new session is for `%s'\n",
478                     session, GNUNET_i2s (peer), p2);
479         GNUNET_free (p2);
480         return NOT_FOUND;
481       }
482       return i;
483     }
484   }
485   return NOT_FOUND;
486 }
487
488
489 /**
490  * Remove the session of the given session ID from the session
491  * table (it is no longer valid).
492  *
493  * @param sh our handle
494  * @param session_id identifies session that is no longer valid
495  * @param peer peer the session belongs to
496  */
497 static void
498 remove_session (struct GNUNET_ATS_SchedulingHandle *sh,
499                 uint32_t session_id,
500                 const struct GNUNET_PeerIdentity *peer)
501 {
502   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
503                    "ats-scheduling-api",
504                    "Release sessionID %u from peer %s in %p\n",
505                    (unsigned int) session_id,
506                    GNUNET_i2s (peer),
507                    sh);
508
509   if (0 == session_id)
510     return;
511
512   GNUNET_assert (session_id < sh->session_array_size);
513   GNUNET_assert (GNUNET_YES == sh->session_array[session_id].slot_used);
514   GNUNET_assert (0 == memcmp (peer,
515                               &sh->session_array[session_id].peer,
516                               sizeof (struct GNUNET_PeerIdentity)));
517   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
518               "Session %p for peer `%s' removed from slot %u \n",
519               sh->session_array[session_id].session,
520               GNUNET_i2s (peer),
521               session_id);
522   sh->session_array[session_id].session = NULL;
523 }
524
525
526 /**
527  * Release the session slot from the session table (ATS service is
528  * also done using it).
529  *
530  * @param sh our handle
531  * @param session_id identifies session that is no longer valid
532  * @param peer peer the session belongs to
533  */
534 static void
535 release_session (struct GNUNET_ATS_SchedulingHandle *sh,
536                  uint32_t session_id,
537                  const struct GNUNET_PeerIdentity *peer)
538 {
539
540   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
541               "Release sessionID %u from peer %s in %p\n",
542               (unsigned int) session_id, GNUNET_i2s (peer), sh);
543
544   if (session_id >= sh->session_array_size)
545   {
546     GNUNET_break (0);
547     sh->reconnect = GNUNET_YES;
548     return;
549   }
550
551   /* this slot should have been removed from remove_session before */
552   GNUNET_assert (sh->session_array[session_id].session == NULL);
553
554   if (0 !=
555       memcmp (peer, &sh->session_array[session_id].peer,
556               sizeof (struct GNUNET_PeerIdentity)))
557   {
558     GNUNET_break (0);
559     sh->reconnect = GNUNET_YES;
560     return;
561   }
562   sh->session_array[session_id].slot_used = GNUNET_NO;
563   memset (&sh->session_array[session_id].peer, 0,
564           sizeof (struct GNUNET_PeerIdentity));
565 }
566
567
568 static void
569 process_release_message (struct GNUNET_ATS_SchedulingHandle *sh,
570                          const struct SessionReleaseMessage *srm)
571 {
572   release_session (sh, ntohl (srm->session_id), &srm->peer);
573 }
574
575
576 /**
577  * Type of a function to call when we receive a message
578  * from the service.
579  *
580  * @param cls the `struct GNUNET_ATS_SchedulingHandle`
581  * @param msg message received, NULL on timeout or fatal error
582  */
583 static void
584 process_ats_message (void *cls,
585                      const struct GNUNET_MessageHeader *msg)
586 {
587   struct GNUNET_ATS_SchedulingHandle *sh = cls;
588   const struct AddressSuggestionMessage *m;
589   const struct GNUNET_ATS_Information *atsi;
590   const char *plugin_address;
591   const char *plugin_name;
592   uint16_t plugin_address_length;
593   uint16_t plugin_name_length;
594   uint32_t ats_count;
595   struct GNUNET_HELLO_Address address;
596   struct Session *s;
597
598   if (NULL == msg)
599   {
600     force_reconnect (sh);
601     return;
602   }
603   if ((ntohs (msg->type) == GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE) &&
604       (ntohs (msg->size) == sizeof (struct SessionReleaseMessage)))
605   {
606     process_release_message (sh, (const struct SessionReleaseMessage *) msg);
607     GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
608                            GNUNET_TIME_UNIT_FOREVER_REL);
609     if (GNUNET_YES == sh->reconnect)
610       force_reconnect (sh);
611     return;
612   }
613   if ((ntohs (msg->type) != GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION) ||
614       (ntohs (msg->size) <= sizeof (struct AddressSuggestionMessage)))
615   {
616     GNUNET_break (0);
617     force_reconnect (sh);
618     return;
619   }
620   m = (const struct AddressSuggestionMessage *) msg;
621   ats_count = ntohl (m->ats_count);
622   plugin_address_length = ntohs (m->address_length);
623   atsi = (const struct GNUNET_ATS_Information *) &m[1];
624   plugin_address = (const char *) &atsi[ats_count];
625   plugin_name = &plugin_address[plugin_address_length];
626   plugin_name_length = ntohs (m->plugin_name_length);
627   if ((plugin_address_length + plugin_name_length +
628        ats_count * sizeof (struct GNUNET_ATS_Information) +
629        sizeof (struct AddressSuggestionMessage) != ntohs (msg->size)) ||
630       (ats_count >
631        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information))
632       || (plugin_name[plugin_name_length - 1] != '\0'))
633   {
634     GNUNET_break (0);
635     force_reconnect (sh);
636     return;
637   }
638   uint32_t session_id = ntohl (m->session_id);
639
640   if (session_id == 0)
641     s = NULL;
642   else
643   {
644     s = find_session (sh, session_id, &m->peer);
645     if (s == NULL)
646     {
647
648       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
649                   "ATS tries to use outdated session `%s'\n",
650                   GNUNET_i2s (&m->peer));
651       GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
652                              GNUNET_TIME_UNIT_FOREVER_REL);
653       return;
654     }
655   }
656
657   if (NULL == sh->suggest_cb)
658         return;
659
660   address.peer = m->peer;
661   address.address = plugin_address;
662   address.address_length = plugin_address_length;
663   address.transport_name = plugin_name;
664   address.local_info = ntohl(m->address_local_info);
665
666   if ((s == NULL) && (0 == address.address_length))
667   {
668     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
669                 "ATS returned invalid address for peer `%s' transport `%s' address length %i, session_id %i\n",
670                 GNUNET_i2s (&address.peer), address.transport_name,
671                 plugin_address_length, session_id);
672     GNUNET_break_op (0);
673     GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
674                            GNUNET_TIME_UNIT_FOREVER_REL);
675     return;
676   }
677
678   sh->suggest_cb (sh->suggest_cb_cls,
679                   (const struct GNUNET_PeerIdentity *) &m->peer,
680                   &address, s, m->bandwidth_out,
681                   m->bandwidth_in, atsi, ats_count);
682
683   GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
684                          GNUNET_TIME_UNIT_FOREVER_REL);
685   if (GNUNET_YES == sh->reconnect)
686     force_reconnect (sh);
687 }
688
689
690 /**
691  * Re-establish the connection to the ATS service.
692  *
693  * @param sh handle to use to re-connect.
694  */
695 static void
696 reconnect (struct GNUNET_ATS_SchedulingHandle *sh)
697 {
698   struct PendingMessage *p;
699   struct ClientStartMessage *init;
700
701   GNUNET_assert (NULL == sh->client);
702   sh->client = GNUNET_CLIENT_connect ("ats", sh->cfg);
703   GNUNET_assert (NULL != sh->client);
704   GNUNET_CLIENT_receive (sh->client,
705                          &process_ats_message, sh,
706                          GNUNET_TIME_UNIT_FOREVER_REL);
707   if ( (NULL == (p = sh->pending_head)) ||
708        (GNUNET_YES != p->is_init) )
709   {
710     p = GNUNET_malloc (sizeof (struct PendingMessage) +
711                        sizeof (struct ClientStartMessage));
712     p->size = sizeof (struct ClientStartMessage);
713     p->is_init = GNUNET_YES;
714     init = (struct ClientStartMessage *) &p[1];
715     init->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_START);
716     init->header.size = htons (sizeof (struct ClientStartMessage));
717     init->start_flag = htonl (START_FLAG_SCHEDULING);
718     GNUNET_CONTAINER_DLL_insert (sh->pending_head,
719                                  sh->pending_tail,
720                                  p);
721   }
722   do_transmit (sh);
723 }
724
725
726 /**
727  * Delete the current network list.
728  *
729  * @param sh scheduling handle to clean up
730  */
731 static void
732 delete_networks (struct GNUNET_ATS_SchedulingHandle *sh)
733 {
734   struct ATS_Network *cur;
735
736   while (NULL != (cur = sh->net_head))
737   {
738     GNUNET_CONTAINER_DLL_remove (sh->net_head,
739                                  sh->net_tail,
740                                  cur);
741     GNUNET_free (cur);
742   }
743 }
744
745
746 static int
747 interface_proc (void *cls,
748                 const char *name,
749                 int isDefault,
750                 const struct sockaddr *addr,
751                 const struct sockaddr *broadcast_addr,
752                 const struct sockaddr *netmask,
753                 socklen_t addrlen)
754 {
755   struct GNUNET_ATS_SchedulingHandle *sh = cls;
756   /* Calculate network */
757   struct ATS_Network *net = NULL;
758
759   /* Skipping IPv4 loopback addresses since we have special check  */
760   if  (addr->sa_family == AF_INET)
761   {
762     struct sockaddr_in * a4 = (struct sockaddr_in *) addr;
763
764     if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000))
765        return GNUNET_OK;
766   }
767   /* Skipping IPv6 loopback addresses since we have special check  */
768   if  (addr->sa_family == AF_INET6)
769   {
770     struct sockaddr_in6 * a6 = (struct sockaddr_in6 *) addr;
771     if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr))
772       return GNUNET_OK;
773   }
774
775   if (addr->sa_family == AF_INET)
776   {
777     struct sockaddr_in *addr4 = (struct sockaddr_in *) addr;
778     struct sockaddr_in *netmask4 = (struct sockaddr_in *) netmask;
779     struct sockaddr_in *tmp = NULL;
780     struct sockaddr_in network4;
781
782     net = GNUNET_malloc(sizeof (struct ATS_Network) + 2 * sizeof (struct sockaddr_in));
783     tmp = (struct sockaddr_in *) &net[1];
784     net->network = (struct sockaddr *) &tmp[0];
785     net->netmask = (struct sockaddr *) &tmp[1];
786     net->length = addrlen;
787
788     memset (&network4, 0, sizeof (network4));
789     network4.sin_family = AF_INET;
790 #if HAVE_SOCKADDR_IN_SIN_LEN
791     network4.sin_len = sizeof (network4);
792 #endif
793     network4.sin_addr.s_addr = (addr4->sin_addr.s_addr & netmask4->sin_addr.s_addr);
794
795     memcpy (net->netmask, netmask4, sizeof (struct sockaddr_in));
796     memcpy (net->network, &network4, sizeof (struct sockaddr_in));
797   }
798
799   if (addr->sa_family == AF_INET6)
800   {
801     struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr;
802     struct sockaddr_in6 *netmask6 = (struct sockaddr_in6 *) netmask;
803     struct sockaddr_in6 * tmp = NULL;
804     struct sockaddr_in6 network6;
805
806     net = GNUNET_malloc(sizeof (struct ATS_Network) + 2 * sizeof (struct sockaddr_in6));
807     tmp = (struct sockaddr_in6 *) &net[1];
808     net->network = (struct sockaddr *) &tmp[0];
809     net->netmask = (struct sockaddr *) &tmp[1];
810     net->length = addrlen;
811
812     memset (&network6, 0, sizeof (network6));
813     network6.sin6_family = AF_INET6;
814 #if HAVE_SOCKADDR_IN_SIN_LEN
815     network6.sin6_len = sizeof (network6);
816 #endif
817     int c = 0;
818     uint32_t *addr_elem = (uint32_t *) &addr6->sin6_addr;
819     uint32_t *mask_elem = (uint32_t *) &netmask6->sin6_addr;
820     uint32_t *net_elem = (uint32_t *) &network6.sin6_addr;
821     for (c = 0; c < 4; c++)
822       net_elem[c] = addr_elem[c] & mask_elem[c];
823
824     memcpy (net->netmask, netmask6, sizeof (struct sockaddr_in6));
825     memcpy (net->network, &network6, sizeof (struct sockaddr_in6));
826   }
827
828   /* Store in list */
829   if (net != NULL)
830   {
831 #if VERBOSE_ATS
832     char * netmask = GNUNET_strdup (GNUNET_a2s((struct sockaddr *) net->netmask, addrlen));
833     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding network `%s', netmask `%s'\n",
834         GNUNET_a2s((struct sockaddr *) net->network, addrlen),
835         netmask);
836     GNUNET_free (netmask);
837 # endif
838     GNUNET_CONTAINER_DLL_insert(sh->net_head, sh->net_tail, net);
839   }
840   return GNUNET_OK;
841 }
842
843
844 /**
845  * Periodically get list of network addresses from our interfaces.
846  *
847  * @param cls closure
848  * @param tc Task context
849  */
850 static void
851 get_addresses (void *cls,
852                const struct GNUNET_SCHEDULER_TaskContext *tc)
853 {
854   struct GNUNET_ATS_SchedulingHandle *sh = cls;
855
856   sh->interface_task = NULL;
857   delete_networks (sh);
858   GNUNET_OS_network_interfaces_list (&interface_proc,
859                                      sh);
860   sh->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVALL,
861                                                      &get_addresses,
862                                                      sh);
863 }
864
865
866 /**
867  * Convert a `enum GNUNET_ATS_Network_Type` to a string
868  *
869  * @param net the network type
870  * @return a string or NULL if invalid
871  */
872 const char *
873 GNUNET_ATS_print_network_type (enum GNUNET_ATS_Network_Type net)
874 {
875   switch (net)
876     {
877     case GNUNET_ATS_NET_UNSPECIFIED:
878       return "UNSPECIFIED";
879     case GNUNET_ATS_NET_LOOPBACK:
880       return "LOOPBACK";
881     case GNUNET_ATS_NET_LAN:
882       return "LAN";
883     case GNUNET_ATS_NET_WAN:
884       return "WAN";
885     case GNUNET_ATS_NET_WLAN:
886       return "WLAN";
887     case GNUNET_ATS_NET_BT:
888       return "BLUETOOTH";
889     default:
890       return NULL;
891     }
892 }
893
894
895 /**
896  * Convert a ATS property to a string
897  *
898  * @param type the property type
899  * @return a string or NULL if invalid
900  */
901 const char *
902 GNUNET_ATS_print_property_type (enum GNUNET_ATS_Property type)
903 {
904   switch (type)
905   {
906   case GNUNET_ATS_ARRAY_TERMINATOR:
907     return "TERMINATOR";
908   case GNUNET_ATS_UTILIZATION_OUT:
909     return "UTILIZATION_UP";
910   case GNUNET_ATS_UTILIZATION_IN:
911     return "UTILIZATION_DOWN";
912   case GNUNET_ATS_UTILIZATION_PAYLOAD_OUT:
913     return "UTILIZATION_PAYLOAD_UP";
914   case GNUNET_ATS_UTILIZATION_PAYLOAD_IN:
915     return "UTILIZATION_PAYLOAD_DOWN";
916   case GNUNET_ATS_NETWORK_TYPE:
917     return "NETWORK_TYPE";
918   case GNUNET_ATS_QUALITY_NET_DELAY:
919     return "DELAY";
920   case GNUNET_ATS_QUALITY_NET_DISTANCE:
921     return "DISTANCE";
922   case GNUNET_ATS_COST_WAN:
923     return "COST_WAN";
924   case GNUNET_ATS_COST_LAN:
925     return "COST_LAN";
926   case GNUNET_ATS_COST_WLAN:
927     return "COST_WLAN";
928   default:
929     return NULL;
930   }
931 }
932
933
934 /**
935  * Returns where the address is located: LAN or WAN or ...
936  *
937  * @param sh the scheduling handle
938  * @param addr address
939  * @param addrlen address length
940  * @return type of the network the address belongs to
941  */
942 enum GNUNET_ATS_Network_Type
943 GNUNET_ATS_address_get_type (struct GNUNET_ATS_SchedulingHandle *sh,
944                              const struct sockaddr *addr,
945                              socklen_t addrlen)
946 {
947   struct ATS_Network *cur = sh->net_head;
948   enum GNUNET_ATS_NetworkType type = GNUNET_ATS_NET_UNSPECIFIED;
949
950   switch (addr->sa_family)
951     {
952     case AF_UNIX:
953       type = GNUNET_ATS_NET_LOOPBACK;
954       break;
955     case AF_INET:
956       {
957         const struct sockaddr_in *a4 = (const struct sockaddr_in *) addr;
958
959         if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000))
960           type = GNUNET_ATS_NET_LOOPBACK;
961         break;
962       }
963     case AF_INET6:
964       {
965         const struct sockaddr_in6 *a6 = (const struct sockaddr_in6 *) addr;
966
967         if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr))
968           type = GNUNET_ATS_NET_LOOPBACK;
969         break;
970       }
971     default:
972       GNUNET_break (0);
973       break;
974    }
975
976   /* Check local networks */
977   while ((cur != NULL) && (type == GNUNET_ATS_NET_UNSPECIFIED))
978   {
979     if (addrlen != cur->length)
980     {
981       cur = cur->next;
982       continue;
983     }
984     if (addr->sa_family == AF_INET)
985     {
986       struct sockaddr_in * a4 = (struct sockaddr_in *) addr;
987       struct sockaddr_in * net4 = (struct sockaddr_in *) cur->network;
988       struct sockaddr_in * mask4 = (struct sockaddr_in *) cur->netmask;
989
990       if (((a4->sin_addr.s_addr & mask4->sin_addr.s_addr)) == net4->sin_addr.s_addr)
991         type = GNUNET_ATS_NET_LAN;
992     }
993     if (addr->sa_family == AF_INET6)
994     {
995       struct sockaddr_in6 * a6 = (struct sockaddr_in6 *) addr;
996       struct sockaddr_in6 * net6 = (struct sockaddr_in6 *) cur->network;
997       struct sockaddr_in6 * mask6 = (struct sockaddr_in6 *) cur->netmask;
998
999       int res = GNUNET_YES;
1000       int c = 0;
1001       uint32_t *addr_elem = (uint32_t *) &a6->sin6_addr;
1002       uint32_t *mask_elem = (uint32_t *) &mask6->sin6_addr;
1003       uint32_t *net_elem = (uint32_t *) &net6->sin6_addr;
1004       for (c = 0; c < 4; c++)
1005         if ((addr_elem[c] & mask_elem[c]) != net_elem[c])
1006           res = GNUNET_NO;
1007
1008       if (res == GNUNET_YES)
1009         type = GNUNET_ATS_NET_LAN;
1010     }
1011     cur = cur->next;
1012   }
1013
1014   /* no local network found for this address, default: WAN */
1015   if (type == GNUNET_ATS_NET_UNSPECIFIED)
1016     type = GNUNET_ATS_NET_WAN;
1017   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG,
1018                    "ats-scheduling-api",
1019                    "`%s' is in network `%s'\n",
1020                    GNUNET_a2s (addr,
1021                                addrlen),
1022                    GNUNET_ATS_print_network_type (type));
1023   return type;
1024 }
1025
1026
1027 /**
1028  * Initialize the ATS subsystem.
1029  *
1030  * @param cfg configuration to use
1031  * @param suggest_cb notification to call whenever the suggestation changed
1032  * @param suggest_cb_cls closure for @a suggest_cb
1033  * @return ats context
1034  */
1035 struct GNUNET_ATS_SchedulingHandle *
1036 GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1037                             GNUNET_ATS_AddressSuggestionCallback suggest_cb,
1038                             void *suggest_cb_cls)
1039 {
1040   struct GNUNET_ATS_SchedulingHandle *sh;
1041
1042   sh = GNUNET_new (struct GNUNET_ATS_SchedulingHandle);
1043   sh->cfg = cfg;
1044   sh->suggest_cb = suggest_cb;
1045   sh->suggest_cb_cls = suggest_cb_cls;
1046   GNUNET_array_grow (sh->session_array,
1047                      sh->session_array_size,
1048                      4);
1049   GNUNET_OS_network_interfaces_list (&interface_proc,
1050                                      sh);
1051   sh->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVALL,
1052                                                      &get_addresses,
1053                                                      sh);
1054   reconnect (sh);
1055   return sh;
1056 }
1057
1058
1059 /**
1060  * Client is done with ATS scheduling, release resources.
1061  *
1062  * @param sh handle to release
1063  */
1064 void
1065 GNUNET_ATS_scheduling_done (struct GNUNET_ATS_SchedulingHandle *sh)
1066 {
1067   struct PendingMessage *p;
1068   struct GNUNET_ATS_SuggestHandle *cur;
1069
1070   while (NULL != (p = sh->pending_head))
1071   {
1072     GNUNET_CONTAINER_DLL_remove (sh->pending_head,
1073                                  sh->pending_tail,
1074                                  p);
1075     GNUNET_free (p);
1076   }
1077   if (NULL != sh->client)
1078   {
1079     GNUNET_CLIENT_disconnect (sh->client);
1080     sh->client = NULL;
1081   }
1082   if (NULL != sh->task)
1083   {
1084     GNUNET_SCHEDULER_cancel (sh->task);
1085     sh->task = NULL;
1086   }
1087   while (NULL != (cur = sh->sug_head))
1088   {
1089     GNUNET_CONTAINER_DLL_remove (sh->sug_head,
1090                                  sh->sug_tail,
1091                                  cur);
1092     GNUNET_free (cur);
1093   }
1094   delete_networks (sh);
1095   if (NULL != sh->interface_task)
1096   {
1097     GNUNET_SCHEDULER_cancel (sh->interface_task);
1098     sh->interface_task = NULL;
1099   }
1100   GNUNET_array_grow (sh->session_array,
1101                      sh->session_array_size,
1102                      0);
1103   GNUNET_free (sh);
1104 }
1105
1106
1107 /**
1108  * We would like to reset the address suggestion block time for this
1109  * peer
1110  *
1111  * @param sh handle
1112  * @param peer identity of the peer we want to reset
1113  */
1114 void
1115 GNUNET_ATS_reset_backoff (struct GNUNET_ATS_SchedulingHandle *sh,
1116                           const struct GNUNET_PeerIdentity *peer)
1117 {
1118   struct PendingMessage *p;
1119   struct ResetBackoffMessage *m;
1120
1121   p = GNUNET_malloc (sizeof (struct PendingMessage) +
1122                      sizeof (struct ResetBackoffMessage));
1123   p->size = sizeof (struct ResetBackoffMessage);
1124   p->is_init = GNUNET_NO;
1125   m = (struct ResetBackoffMessage *) &p[1];
1126   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_RESET_BACKOFF);
1127   m->header.size = htons (sizeof (struct ResetBackoffMessage));
1128   m->reserved = htonl (0);
1129   m->peer = *peer;
1130   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head,
1131                                     sh->pending_tail,
1132                                     p);
1133   do_transmit (sh);
1134 }
1135
1136
1137 /**
1138  * We would like to receive address suggestions for a peer. ATS will
1139  * respond with a call to the continuation immediately containing an address or
1140  * no address if none is available. ATS can suggest more addresses until we call
1141  * #GNUNET_ATS_suggest_address_cancel().
1142  *
1143  * @param sh handle
1144  * @param peer identity of the peer we need an address for
1145  * @return suggest handle
1146  */
1147 struct GNUNET_ATS_SuggestHandle *
1148 GNUNET_ATS_suggest_address (struct GNUNET_ATS_SchedulingHandle *sh,
1149                             const struct GNUNET_PeerIdentity *peer)
1150 {
1151   struct PendingMessage *p;
1152   struct RequestAddressMessage *m;
1153   struct GNUNET_ATS_SuggestHandle *s;
1154
1155   // FIXME: ATS needs to remember this in case of
1156   // a disconnect!
1157   p = GNUNET_malloc (sizeof (struct PendingMessage) +
1158                      sizeof (struct RequestAddressMessage));
1159   p->size = sizeof (struct RequestAddressMessage);
1160   m = (struct RequestAddressMessage *) &p[1];
1161   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS);
1162   m->header.size = htons (sizeof (struct RequestAddressMessage));
1163   m->reserved = htonl (0);
1164   m->peer = *peer;
1165   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head,
1166                                     sh->pending_tail,
1167                                     p);
1168   do_transmit (sh);
1169   s = GNUNET_new (struct GNUNET_ATS_SuggestHandle);
1170   s->id = *peer;
1171   GNUNET_CONTAINER_DLL_insert_tail (sh->sug_head,
1172                                     sh->sug_tail,
1173                                     s);
1174   return s;
1175 }
1176
1177
1178 /**
1179  * We would like to stop receiving address updates for this peer
1180  *
1181  * @param sh handle
1182  * @param peer identity of the peer
1183  */
1184 void
1185 GNUNET_ATS_suggest_address_cancel (struct GNUNET_ATS_SchedulingHandle *sh,
1186                                    const struct GNUNET_PeerIdentity *peer)
1187 {
1188   struct PendingMessage *p;
1189   struct RequestAddressMessage *m;
1190   struct GNUNET_ATS_SuggestHandle *s;
1191
1192   for (s = sh->sug_head; NULL != s; s = s->next)
1193     if (0 == memcmp (peer, &s->id, sizeof (s->id)))
1194       break;
1195   if (NULL == s)
1196   {
1197     GNUNET_break (0);
1198     return;
1199   }
1200   GNUNET_CONTAINER_DLL_remove (sh->sug_head,
1201                                sh->sug_tail,
1202                                s);
1203   GNUNET_free (s);
1204
1205   p = GNUNET_malloc (sizeof (struct PendingMessage) +
1206                      sizeof (struct RequestAddressMessage));
1207   p->size = sizeof (struct RequestAddressMessage);
1208   p->is_init = GNUNET_NO;
1209   m = (struct RequestAddressMessage *) &p[1];
1210   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL);
1211   m->header.size = htons (sizeof (struct RequestAddressMessage));
1212   m->reserved = htonl (0);
1213   m->peer = *peer;
1214   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head,
1215                                     sh->pending_tail,
1216                                     p);
1217   do_transmit (sh);
1218 }
1219
1220
1221 /**
1222  * Test if a address and a session is known to ATS
1223  *
1224  * @param sh the scheduling handle
1225  * @param address the address
1226  * @param session the session
1227  * @return #GNUNET_YES or #GNUNET_NO
1228  */
1229 int
1230 GNUNET_ATS_session_known (struct GNUNET_ATS_SchedulingHandle *sh,
1231                           const struct GNUNET_HELLO_Address *address,
1232                           struct Session *session)
1233 {
1234   if (NULL == session)
1235     return GNUNET_NO;
1236   if (NOT_FOUND != find_session_id (sh,
1237                                     session,
1238                                     &address->peer))
1239     return GNUNET_YES;  /* Exists */
1240   return GNUNET_NO;
1241 }
1242
1243
1244 /**
1245  * We have a new address ATS should know. Addresses have to be added with this
1246  * function before they can be: updated, set in use and destroyed
1247  *
1248  * @param sh handle
1249  * @param address the address
1250  * @param session session handle, can be NULL
1251  * @param ats performance data for the address
1252  * @param ats_count number of performance records in @a ats
1253  * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1254  */
1255 int
1256 GNUNET_ATS_address_add (struct GNUNET_ATS_SchedulingHandle *sh,
1257                         const struct GNUNET_HELLO_Address *address,
1258                         struct Session *session,
1259                         const struct GNUNET_ATS_Information *ats,
1260                         uint32_t ats_count)
1261 {
1262
1263   struct PendingMessage *p;
1264   struct AddressUpdateMessage *m;
1265   struct GNUNET_ATS_Information *am;
1266   char *pm;
1267   size_t namelen;
1268   size_t msize;
1269   uint32_t s = 0;
1270
1271   if (NULL == address)
1272   {
1273     GNUNET_break (0);
1274     return GNUNET_SYSERR;
1275   }
1276
1277   namelen = (NULL == address->transport_name)
1278     ? 0
1279     : strlen (address->transport_name) + 1;
1280
1281   msize = sizeof (struct AddressUpdateMessage) + address->address_length +
1282     ats_count * sizeof (struct GNUNET_ATS_Information) + namelen;
1283   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1284       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1285       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1286       (ats_count >=
1287        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information)))
1288   {
1289     GNUNET_break (0);
1290     return GNUNET_SYSERR;
1291   }
1292
1293   if (NULL != session)
1294   {
1295     if (NOT_FOUND != (s = find_session_id (sh, session, &address->peer)))
1296     {
1297       /* Already existing, nothing todo */
1298       return GNUNET_SYSERR;
1299     }
1300     s = find_empty_session_slot (sh,
1301                                  session,
1302                                  &address->peer);
1303     GNUNET_break (NOT_FOUND != s);
1304   }
1305
1306   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1307   p->size = msize;
1308   p->is_init = GNUNET_NO;
1309   m = (struct AddressUpdateMessage *) &p[1];
1310   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_ADD);
1311   m->header.size = htons (msize);
1312   m->ats_count = htonl (ats_count);
1313   m->peer = address->peer;
1314   m->address_length = htons (address->address_length);
1315   m->address_local_info = htonl ((uint32_t) address->local_info);
1316   m->plugin_name_length = htons (namelen);
1317   m->session_id = htonl (s);
1318
1319   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1320               "Adding address for peer `%s', plugin `%s', session %p id %u\n",
1321               GNUNET_i2s (&address->peer),
1322               address->transport_name,
1323               session,
1324               s);
1325
1326   am = (struct GNUNET_ATS_Information *) &m[1];
1327   memcpy (am, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
1328   pm = (char *) &am[ats_count];
1329   memcpy (pm, address->address, address->address_length);
1330   if (NULL != address->transport_name)
1331     memcpy (&pm[address->address_length],
1332             address->transport_name,
1333             namelen);
1334   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head,
1335                                     sh->pending_tail,
1336                                     p);
1337   do_transmit (sh);
1338   return GNUNET_OK;
1339 }
1340
1341
1342 /**
1343  * We have updated performance statistics for a given address.  Note
1344  * that this function can be called for addresses that are currently
1345  * in use as well as addresses that are valid but not actively in use.
1346  * Furthermore, the peer may not even be connected to us right now (in
1347  * which case the call may be ignored or the information may be stored
1348  * for later use).  Update bandwidth assignments.
1349  *
1350  * @param sh handle
1351  * @param address the address
1352  * @param session session handle, can be NULL
1353  * @param ats performance data for the address
1354  * @param ats_count number of performance records in @a ats
1355  * @return #GNUNET_YES on success, #GNUNET_NO if address or session are unknown,
1356  * #GNUNET_SYSERR on hard failure
1357  */
1358 int
1359 GNUNET_ATS_address_update (struct GNUNET_ATS_SchedulingHandle *sh,
1360                            const struct GNUNET_HELLO_Address *address,
1361                            struct Session *session,
1362                            const struct GNUNET_ATS_Information *ats,
1363                            uint32_t ats_count)
1364 {
1365   struct PendingMessage *p;
1366   struct AddressUpdateMessage *m;
1367   struct GNUNET_ATS_Information *am;
1368   char *pm;
1369   size_t namelen;
1370   size_t msize;
1371   uint32_t s = 0;
1372
1373   if (NULL == address)
1374   {
1375     GNUNET_break (0);
1376     return GNUNET_SYSERR;
1377   }
1378   if (NULL == sh)
1379   {
1380     GNUNET_break (0);
1381     return GNUNET_SYSERR;
1382   }
1383
1384   namelen = (address->transport_name ==
1385        NULL) ? 0 : strlen (address->transport_name) + 1;
1386   msize =
1387       sizeof (struct AddressUpdateMessage) + address->address_length +
1388       ats_count * sizeof (struct GNUNET_ATS_Information) + namelen;
1389   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1390       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1391       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1392       (ats_count >=
1393        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information)))
1394   {
1395     GNUNET_break (0);
1396     return GNUNET_SYSERR;
1397   }
1398
1399   if (NULL != session)
1400   {
1401     s = find_session_id (sh, session, &address->peer);
1402     if (NOT_FOUND == s)
1403       return GNUNET_NO;
1404   }
1405
1406   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1407   p->size = msize;
1408   p->is_init = GNUNET_NO;
1409   m = (struct AddressUpdateMessage *) &p[1];
1410   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE);
1411   m->header.size = htons (msize);
1412   m->ats_count = htonl (ats_count);
1413   m->peer = address->peer;
1414   m->address_length = htons (address->address_length);
1415   m->address_local_info = htonl ((uint32_t) address->local_info);
1416   m->plugin_name_length = htons (namelen);
1417
1418   m->session_id = htonl (s);
1419
1420   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1421               "Updating address for peer `%s', plugin `%s', session %p id %u\n",
1422               GNUNET_i2s (&address->peer),
1423               address->transport_name,
1424               session,
1425               s);
1426
1427   am = (struct GNUNET_ATS_Information *) &m[1];
1428   memcpy (am,
1429           ats,
1430           ats_count * sizeof (struct GNUNET_ATS_Information));
1431   pm = (char *) &am[ats_count];
1432   memcpy (pm, address->address, address->address_length);
1433   memcpy (&pm[address->address_length], address->transport_name, namelen);
1434   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1435   do_transmit (sh);
1436   return GNUNET_YES;
1437 }
1438
1439
1440 /**
1441  * An address is now in use or not used any more.
1442  *
1443  * @param sh handle
1444  * @param address the address
1445  * @param session session handle, can be NULL
1446  * @param in_use #GNUNET_YES if this address is now used, #GNUNET_NO
1447  * if address is not used any more
1448  */
1449 void
1450 GNUNET_ATS_address_in_use (struct GNUNET_ATS_SchedulingHandle *sh,
1451                            const struct GNUNET_HELLO_Address *address,
1452                            struct Session *session,
1453                            int in_use)
1454 {
1455   struct PendingMessage *p;
1456   struct AddressUseMessage *m;
1457   char *pm;
1458   size_t namelen;
1459   size_t msize;
1460   uint32_t s = 0;
1461
1462   GNUNET_assert (NULL != address);
1463   namelen =
1464       (address->transport_name ==
1465        NULL) ? 0 : strlen (address->transport_name) + 1;
1466   msize = sizeof (struct AddressUseMessage) + address->address_length + namelen;
1467   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1468       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1469       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1470   {
1471     GNUNET_break (0);
1472     return;
1473   }
1474
1475   if (session != NULL)
1476   {
1477     s = find_session_id (sh, session, &address->peer);
1478     if ((s == NOT_FOUND) && (GNUNET_NO == in_use))
1479     {
1480       /* trying to set unknown address to NO */
1481       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1482                   "Trying to set unknown address to unused for peer `%s', plugin `%s', session %p\n",
1483                   GNUNET_i2s (&address->peer), address->transport_name, session);
1484       GNUNET_break (0);
1485       return;
1486     }
1487     if ((s == NOT_FOUND) && (GNUNET_YES == in_use))
1488     {
1489       /* trying to set new address to YES */
1490       s = find_empty_session_slot (sh, session, &address->peer);
1491       GNUNET_assert (NOT_FOUND != s);
1492     }
1493   }
1494
1495   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1496   p->size = msize;
1497   p->is_init = GNUNET_NO;
1498   m = (struct AddressUseMessage *) &p[1];
1499   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_IN_USE);
1500   m->header.size = htons (msize);
1501   m->peer = address->peer;
1502   m->in_use = htons (in_use);
1503   m->address_length = htons (address->address_length);
1504   m->address_local_info = htonl ((uint32_t) address->local_info);
1505   m->plugin_name_length = htons (namelen);
1506
1507   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1508               "Setting address used to %s for peer `%s', plugin `%s', session %p\n",
1509               (GNUNET_YES == in_use) ? "YES" : "NO",
1510               GNUNET_i2s (&address->peer), address->transport_name, session);
1511
1512   m->session_id = htonl (s);
1513   pm = (char *) &m[1];
1514   memcpy (pm, address->address, address->address_length);
1515   memcpy (&pm[address->address_length], address->transport_name, namelen);
1516   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1517   do_transmit (sh);
1518 }
1519
1520
1521 /**
1522  * An address got destroyed, stop including it as a valid address.
1523  *
1524  * If a session is given, only the session will be removed, if no session is
1525  * given the full address will be deleted.
1526  *
1527  * @param sh handle
1528  * @param address the address
1529  * @param session session handle that is no longer valid, can be NULL
1530  */
1531 void
1532 GNUNET_ATS_address_destroyed (struct GNUNET_ATS_SchedulingHandle *sh,
1533                               const struct GNUNET_HELLO_Address *address,
1534                               struct Session *session)
1535 {
1536   struct PendingMessage *p;
1537   struct AddressDestroyedMessage *m;
1538   char *pm;
1539   size_t namelen;
1540   size_t msize;
1541   uint32_t s;
1542
1543   if (NULL == address)
1544   {
1545     GNUNET_break (0);
1546     return;
1547   }
1548
1549   GNUNET_assert (address->transport_name != NULL);
1550   namelen = strlen (address->transport_name) + 1;
1551   GNUNET_assert (namelen > 1);
1552   msize =
1553       sizeof (struct AddressDestroyedMessage) + address->address_length +
1554       namelen;
1555   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1556       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1557       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1558   {
1559     GNUNET_break (0);
1560     return;
1561   }
1562
1563   s = find_session_id (sh, session, &address->peer);
1564   if ((NULL != session) && (NOT_FOUND == s))
1565   {
1566     /* trying to delete unknown address */
1567     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568                 "Trying to delete unknown address for peer `%s', plugin `%s', session %p\n",
1569                 GNUNET_i2s (&address->peer), address->transport_name, session);
1570     return;
1571   }
1572
1573   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1574   p->size = msize;
1575   p->is_init = GNUNET_NO;
1576   m = (struct AddressDestroyedMessage *) &p[1];
1577   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED);
1578   m->header.size = htons (msize);
1579   m->reserved = htonl (0);
1580   m->peer = address->peer;
1581   m->address_length = htons (address->address_length);
1582   m->address_local_info = htonl ((uint32_t) address->local_info);
1583   m->plugin_name_length = htons (namelen);
1584
1585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1586               "Deleting address for peer `%s', plugin `%s', session %p\n",
1587               GNUNET_i2s (&address->peer), address->transport_name, session);
1588
1589   m->session_id = htonl (s);
1590   pm = (char *) &m[1];
1591   memcpy (pm, address->address, address->address_length);
1592   memcpy (&pm[address->address_length], address->transport_name, namelen);
1593   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1594   do_transmit (sh);
1595   remove_session (sh, s, &address->peer);
1596 }
1597
1598 /* end of ats_api_scheduling.c */