ddb4f41c89631a2a8585217630b3694c51c13080
[oweals/gnunet.git] / src / ats / ats_api_scheduling.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,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  * @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 /**
34  * Message in linked list we should send to the ATS service.  The
35  * actual binary message follows this struct.
36  */
37 struct PendingMessage
38 {
39
40   /**
41    * Kept in a DLL.
42    */
43   struct PendingMessage *next;
44
45   /**
46    * Kept in a DLL.
47    */
48   struct PendingMessage *prev;
49
50   /**
51    * Size of the message.
52    */
53   size_t size;
54
55   /**
56    * Is this the 'ATS_START' message?
57    */
58   int is_init;
59 };
60
61
62 /**
63  * Information we track per session.
64  */
65 struct SessionRecord
66 {
67   /**
68    * Identity of the peer (just needed for error checking).
69    */
70   struct GNUNET_PeerIdentity peer;
71
72   /**
73    * Session handle.
74    */
75   struct Session *session;
76
77   /**
78    * Set to GNUNET_YES if the slot is used.
79    */
80   int slot_used;
81 };
82
83
84 struct ATS_Network
85 {
86   struct ATS_Network * next;
87
88   struct ATS_Network * prev;
89
90   struct sockaddr *network;
91   struct sockaddr *netmask;
92   socklen_t length;
93 };
94
95
96
97 /**
98  * Handle to the ATS subsystem for bandwidth/transport scheduling information.
99  */
100 struct GNUNET_ATS_SchedulingHandle
101 {
102
103   /**
104    * Our configuration.
105    */
106   const struct GNUNET_CONFIGURATION_Handle *cfg;
107
108   /**
109    * Callback to invoke on suggestions.
110    */
111   GNUNET_ATS_AddressSuggestionCallback suggest_cb;
112
113   /**
114    * Closure for 'suggest_cb'.
115    */
116   void *suggest_cb_cls;
117
118   /**
119    * Connection to ATS service.
120    */
121   struct GNUNET_CLIENT_Connection *client;
122
123   /**
124    * Head of list of messages for the ATS service.
125    */
126   struct PendingMessage *pending_head;
127
128   /**
129    * Tail of list of messages for the ATS service
130    */
131   struct PendingMessage *pending_tail;
132
133   /**
134    * Current request for transmission to ATS.
135    */
136   struct GNUNET_CLIENT_TransmitHandle *th;
137
138   /**
139    * Head of network list
140    */
141   struct ATS_Network * net_head;
142
143   /**
144    * Tail of network list
145    */
146   struct ATS_Network * net_tail;
147
148
149   /**
150    * Array of session objects (we need to translate them to numbers and back
151    * for the protocol; the offset in the array is the session number on the
152    * network).  Index 0 is always NULL and reserved to represent the NULL pointer.
153    * Unused entries are also NULL.
154    */
155   struct SessionRecord *session_array;
156
157   /**
158    * Task to trigger reconnect.
159    */
160   GNUNET_SCHEDULER_TaskIdentifier task;
161
162   /**
163    * Task retrieving interfaces from the system
164    */
165
166   GNUNET_SCHEDULER_TaskIdentifier interface_task;
167
168
169   /**
170    * Size of the session array.
171    */
172   unsigned int session_array_size;
173
174   /**
175    * Should we reconnect to ATS due to some serious error?
176    */
177   int reconnect;
178 };
179
180
181 /**
182  * Re-establish the connection to the ATS service.
183  *
184  * @param sh handle to use to re-connect.
185  */
186 static void
187 reconnect (struct GNUNET_ATS_SchedulingHandle *sh);
188
189
190 /**
191  * Re-establish the connection to the ATS service.
192  *
193  * @param cls handle to use to re-connect.
194  * @param tc scheduler context
195  */
196 static void
197 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
198 {
199   struct GNUNET_ATS_SchedulingHandle *sh = cls;
200
201   sh->task = GNUNET_SCHEDULER_NO_TASK;
202   reconnect (sh);
203 }
204
205
206 /**
207  * Disconnect from ATS and then reconnect.
208  *
209  * @param sh our handle
210  */
211 static void
212 force_reconnect (struct GNUNET_ATS_SchedulingHandle *sh)
213 {
214   sh->reconnect = GNUNET_NO;
215   GNUNET_CLIENT_disconnect (sh->client);
216   sh->client = NULL;
217   sh->task =
218       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &reconnect_task,
219                                     sh);
220 }
221
222
223 /**
224  * Transmit messages from the message queue to the service
225  * (if there are any, and if we are not already trying).
226  *
227  * @param sh handle to use
228  */
229 static void
230 do_transmit (struct GNUNET_ATS_SchedulingHandle *sh);
231
232
233 /**
234  * Type of a function to call when we receive a message
235  * from the service.
236  *
237  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
238  * @param msg message received, NULL on timeout or fatal error
239  */
240 static void
241 process_ats_message (void *cls, const struct GNUNET_MessageHeader *msg);
242
243
244 /**
245  * We can now transmit a message to ATS. Do it.
246  *
247  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
248  * @param size number of bytes we can transmit to ATS
249  * @param buf where to copy the messages
250  * @return number of bytes copied into buf
251  */
252 static size_t
253 transmit_message_to_ats (void *cls, size_t size, void *buf)
254 {
255   struct GNUNET_ATS_SchedulingHandle *sh = cls;
256   struct PendingMessage *p;
257   size_t ret;
258   char *cbuf;
259
260   sh->th = NULL;
261   if ((size == 0) || (buf == NULL))
262   {
263     force_reconnect (sh);
264     return 0;
265   }
266   ret = 0;
267   cbuf = buf;
268   while ((NULL != (p = sh->pending_head)) && (p->size <= size))
269   {
270     memcpy (&cbuf[ret], &p[1], p->size);
271     ret += p->size;
272     size -= p->size;
273     GNUNET_CONTAINER_DLL_remove (sh->pending_head, sh->pending_tail, p);
274     if (GNUNET_YES == p->is_init)
275       GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
276                              GNUNET_TIME_UNIT_FOREVER_REL);
277     GNUNET_free (p);
278   }
279   do_transmit (sh);
280   return ret;
281 }
282
283
284 /**
285  * Transmit messages from the message queue to the service
286  * (if there are any, and if we are not already trying).
287  *
288  * @param sh handle to use
289  */
290 static void
291 do_transmit (struct GNUNET_ATS_SchedulingHandle *sh)
292 {
293   struct PendingMessage *p;
294
295   if (NULL != sh->th)
296     return;
297   if (NULL == (p = sh->pending_head))
298     return;
299   if (NULL == sh->client)
300     return;                     /* currently reconnecting */
301   sh->th =
302       GNUNET_CLIENT_notify_transmit_ready (sh->client, p->size,
303                                            GNUNET_TIME_UNIT_FOREVER_REL,
304                                            GNUNET_NO, &transmit_message_to_ats,
305                                            sh);
306 }
307
308
309 /**
310  * Find the session object corresponding to the given session ID.
311  *
312  * @param sh our handle
313  * @param session_id current session ID
314  * @param peer peer the session belongs to
315  * @return the session object (or NULL)
316  */
317 static struct Session *
318 find_session (struct GNUNET_ATS_SchedulingHandle *sh, uint32_t session_id,
319               const struct GNUNET_PeerIdentity *peer)
320 {
321
322   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
323               "Find session %u from peer %s in %p\n",
324               (unsigned int) session_id, GNUNET_i2s (peer), sh);
325
326   if (session_id >= sh->session_array_size)
327   {
328     GNUNET_break (0);
329     return NULL;
330   }
331   if (0 == session_id)
332     return NULL;
333   if (sh->session_array[session_id].session == NULL)
334   {
335     GNUNET_break (0 ==
336                   memcmp (peer, &sh->session_array[session_id].peer,
337                           sizeof (struct GNUNET_PeerIdentity)));
338     return NULL;
339   }
340
341   if (0 !=
342       memcmp (peer, &sh->session_array[session_id].peer,
343               sizeof (struct GNUNET_PeerIdentity)))
344   {
345     GNUNET_break (0);
346     sh->reconnect = GNUNET_YES;
347     return NULL;
348   }
349   return sh->session_array[session_id].session;
350 }
351
352
353 /**
354  * Get the ID for the given session object.  If we do not have an ID for
355  * the given session object, allocate one.
356  *
357  * @param sh our handle
358  * @param session session object
359  * @param peer peer the session belongs to
360  * @return the session id
361  */
362 static uint32_t
363 get_session_id (struct GNUNET_ATS_SchedulingHandle *sh, struct Session *session,
364                 const struct GNUNET_PeerIdentity *peer)
365 {
366   unsigned int i;
367   unsigned int f;
368
369
370   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
371               "Get session ID for session %p from peer %s in %p\n", session,
372               GNUNET_i2s (peer), sh);
373
374   if (NULL == session)
375     return 0;
376   f = 0;
377   for (i = 1; i < sh->session_array_size; i++)
378   {
379     if (session == sh->session_array[i].session)
380     {
381       GNUNET_assert (0 ==
382                      memcmp (peer, &sh->session_array[i].peer,
383                              sizeof (struct GNUNET_PeerIdentity)));
384       return i;
385     }
386     if ((f == 0) && (sh->session_array[i].slot_used == GNUNET_NO))
387       f = i;
388   }
389   if (f == 0)
390   {
391     f = sh->session_array_size;
392     GNUNET_array_grow (sh->session_array, sh->session_array_size,
393                        sh->session_array_size * 2);
394   }
395   GNUNET_assert (f > 0);
396   sh->session_array[f].session = session;
397   sh->session_array[f].peer = *peer;
398   sh->session_array[f].slot_used = GNUNET_YES;
399
400   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
401               "Assigning session ID %u for session %p of peer %s in %p\n", f,
402               session, GNUNET_i2s (peer), sh);
403
404   return f;
405 }
406
407
408 /**
409  * Remove the session of the given session ID from the session
410  * table (it is no longer valid).
411  *
412  * @param sh our handle
413  * @param session_id identifies session that is no longer valid
414  * @param peer peer the session belongs to
415  */
416 static void
417 remove_session (struct GNUNET_ATS_SchedulingHandle *sh, uint32_t session_id,
418                 const struct GNUNET_PeerIdentity *peer)
419 {
420   GNUNET_assert (peer != NULL);
421   GNUNET_assert (sh != NULL);
422
423   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
424               "Release sessionID %u from peer %s in %p\n",
425               (unsigned int) session_id, GNUNET_i2s (peer), sh);
426
427   if (0 == session_id)
428     return;
429   GNUNET_assert (session_id < sh->session_array_size);
430   GNUNET_assert (GNUNET_YES == sh->session_array[session_id].slot_used);
431   GNUNET_assert (0 ==
432                  memcmp (peer, &sh->session_array[session_id].peer,
433                          sizeof (struct GNUNET_PeerIdentity)));
434   sh->session_array[session_id].session = NULL;
435 }
436
437
438 /**
439  * Release the session slot from the session table (ATS service is
440  * also done using it).
441  *
442  * @param sh our handle
443  * @param session_id identifies session that is no longer valid
444  * @param peer peer the session belongs to
445  */
446 static void
447 release_session (struct GNUNET_ATS_SchedulingHandle *sh, uint32_t session_id,
448                  const struct GNUNET_PeerIdentity *peer)
449 {
450
451   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
452               "Release sessionID %u from peer %s in %p\n",
453               (unsigned int) session_id, GNUNET_i2s (peer), sh);
454
455   if (session_id >= sh->session_array_size)
456   {
457     GNUNET_break (0);
458     sh->reconnect = GNUNET_YES;
459     return;
460   }
461
462   /* this slot should have been removed from remove_session before */
463   GNUNET_assert (sh->session_array[session_id].session == NULL);
464
465   if (0 !=
466       memcmp (peer, &sh->session_array[session_id].peer,
467               sizeof (struct GNUNET_PeerIdentity)))
468   {
469     GNUNET_break (0);
470     sh->reconnect = GNUNET_YES;
471     return;
472   }
473   sh->session_array[session_id].slot_used = GNUNET_NO;
474   memset (&sh->session_array[session_id].peer, 0,
475           sizeof (struct GNUNET_PeerIdentity));
476 }
477
478
479 static void
480 process_release_message (struct GNUNET_ATS_SchedulingHandle *sh,
481                          const struct SessionReleaseMessage *srm)
482 {
483   release_session (sh, ntohl (srm->session_id), &srm->peer);
484 }
485
486
487 /**
488  * Type of a function to call when we receive a message
489  * from the service.
490  *
491  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
492  * @param msg message received, NULL on timeout or fatal error
493  */
494 static void
495 process_ats_message (void *cls, const struct GNUNET_MessageHeader *msg)
496 {
497   struct GNUNET_ATS_SchedulingHandle *sh = cls;
498   const struct AddressSuggestionMessage *m;
499   const struct GNUNET_ATS_Information *atsi;
500   const char *plugin_address;
501   const char *plugin_name;
502   uint16_t plugin_address_length;
503   uint16_t plugin_name_length;
504   uint32_t ats_count;
505   struct GNUNET_HELLO_Address address;
506   struct Session *s;
507
508   if (NULL == msg)
509   {
510     force_reconnect (sh);
511     return;
512   }
513   if ((ntohs (msg->type) == GNUNET_MESSAGE_TYPE_ATS_SESSION_RELEASE) &&
514       (ntohs (msg->size) == sizeof (struct SessionReleaseMessage)))
515   {
516     process_release_message (sh, (const struct SessionReleaseMessage *) msg);
517     GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
518                            GNUNET_TIME_UNIT_FOREVER_REL);
519     if (GNUNET_YES == sh->reconnect)
520       force_reconnect (sh);
521     return;
522   }
523   if ((ntohs (msg->type) != GNUNET_MESSAGE_TYPE_ATS_ADDRESS_SUGGESTION) ||
524       (ntohs (msg->size) <= sizeof (struct AddressSuggestionMessage)))
525   {
526     GNUNET_break (0);
527     force_reconnect (sh);
528     return;
529   }
530   m = (const struct AddressSuggestionMessage *) msg;
531   ats_count = ntohl (m->ats_count);
532   plugin_address_length = ntohs (m->address_length);
533   atsi = (const struct GNUNET_ATS_Information *) &m[1];
534   plugin_address = (const char *) &atsi[ats_count];
535   plugin_name = &plugin_address[plugin_address_length];
536   plugin_name_length = ntohs (m->plugin_name_length);
537   if ((plugin_address_length + plugin_name_length +
538        ats_count * sizeof (struct GNUNET_ATS_Information) +
539        sizeof (struct AddressSuggestionMessage) != ntohs (msg->size)) ||
540       (ats_count >
541        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information))
542       || (plugin_name[plugin_name_length - 1] != '\0'))
543   {
544     GNUNET_break (0);
545     force_reconnect (sh);
546     return;
547   }
548   uint32_t session_id = ntohl (m->session_id);
549
550   if (session_id == 0)
551     s = NULL;
552   else
553   {
554     s = find_session (sh, session_id, &m->peer);
555     if (s == NULL)
556     {
557
558       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
559                   "ATS tries to use outdated session `%s'\n",
560                   GNUNET_i2s (&m->peer));
561       GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
562                              GNUNET_TIME_UNIT_FOREVER_REL);
563       return;
564     }
565   }
566   address.peer = m->peer;
567   address.address = plugin_address;
568   address.address_length = plugin_address_length;
569   address.transport_name = plugin_name;
570
571   if ((s == NULL) && (0 == address.address_length))
572   {
573     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
574                 "ATS returned invalid address for peer `%s' transport `%s' address length %i, session_id %i\n",
575                 GNUNET_i2s (&address.peer), address.transport_name,
576                 plugin_address_length, session_id);
577     GNUNET_break_op (0);
578     GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
579                            GNUNET_TIME_UNIT_FOREVER_REL);
580     return;
581   }
582
583   sh->suggest_cb (sh->suggest_cb_cls, &address, s, m->bandwidth_out,
584                   m->bandwidth_in, atsi, ats_count);
585
586   GNUNET_CLIENT_receive (sh->client, &process_ats_message, sh,
587                          GNUNET_TIME_UNIT_FOREVER_REL);
588   if (GNUNET_YES == sh->reconnect)
589     force_reconnect (sh);
590 }
591
592
593 /**
594  * Re-establish the connection to the ATS service.
595  *
596  * @param sh handle to use to re-connect.
597  */
598 static void
599 reconnect (struct GNUNET_ATS_SchedulingHandle *sh)
600 {
601   struct PendingMessage *p;
602   struct ClientStartMessage *init;
603
604   GNUNET_assert (NULL == sh->client);
605   sh->client = GNUNET_CLIENT_connect ("ats", sh->cfg);
606   GNUNET_assert (NULL != sh->client);
607   if ((NULL == (p = sh->pending_head)) || (GNUNET_YES != p->is_init))
608   {
609     p = GNUNET_malloc (sizeof (struct PendingMessage) +
610                        sizeof (struct ClientStartMessage));
611     p->size = sizeof (struct ClientStartMessage);
612     p->is_init = GNUNET_YES;
613     init = (struct ClientStartMessage *) &p[1];
614     init->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_START);
615     init->header.size = htons (sizeof (struct ClientStartMessage));
616     init->start_flag = htonl (START_FLAG_SCHEDULING);
617     GNUNET_CONTAINER_DLL_insert (sh->pending_head, sh->pending_tail, p);
618   }
619   do_transmit (sh);
620 }
621
622 /**
623  * delete the current network list
624  */
625
626 static void
627 delete_networks (struct GNUNET_ATS_SchedulingHandle *sh)
628 {
629   struct ATS_Network * cur = sh->net_head;
630   while (cur != NULL)
631   {
632     GNUNET_CONTAINER_DLL_remove(sh->net_head, sh->net_tail, cur);
633     GNUNET_free (cur);
634     cur = sh->net_head;
635   }
636 }
637
638
639 static int
640 interface_proc (void *cls, const char *name,
641                 int isDefault,
642                 const struct sockaddr *
643                 addr,
644                 const struct sockaddr *
645                 broadcast_addr,
646                 const struct sockaddr *
647                 netmask, socklen_t addrlen)
648 {
649   struct GNUNET_ATS_SchedulingHandle * sh = cls;
650   /* Calculate network */
651   struct ATS_Network *net = NULL;
652
653   /* Skipping IPv4 loopback addresses since we have special check  */
654   if  (addr->sa_family == AF_INET)
655   {
656     struct sockaddr_in * a4 = (struct sockaddr_in *) addr;
657
658     if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000))
659        return GNUNET_OK;
660   }
661   /* Skipping IPv6 loopback addresses since we have special check  */
662   if  (addr->sa_family == AF_INET6)
663   {
664     struct sockaddr_in6 * a6 = (struct sockaddr_in6 *) addr;
665     if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr))
666       return GNUNET_OK;
667   }
668
669   if (addr->sa_family == AF_INET)
670   {
671     struct sockaddr_in *addr4 = (struct sockaddr_in *) addr;
672     struct sockaddr_in *netmask4 = (struct sockaddr_in *) netmask;
673     struct sockaddr_in *tmp = NULL;
674     struct sockaddr_in network4;
675
676     net = GNUNET_malloc(sizeof (struct ATS_Network) + 2 * sizeof (struct sockaddr_in));
677     tmp = (struct sockaddr_in *) &net[1];
678     net->network = (struct sockaddr *) &tmp[0];
679     net->netmask = (struct sockaddr *) &tmp[1];
680     net->length = addrlen;
681
682     memset (&network4, 0, sizeof (network4));
683     network4.sin_family = AF_INET;
684 #if HAVE_SOCKADDR_IN_SIN_LEN
685     network4.sin_len = sizeof (network4);
686 #endif
687     network4.sin_addr.s_addr = (addr4->sin_addr.s_addr & netmask4->sin_addr.s_addr);
688
689     memcpy (net->netmask, netmask4, sizeof (struct sockaddr_in));
690     memcpy (net->network, &network4, sizeof (struct sockaddr_in));
691   }
692
693   if (addr->sa_family == AF_INET6)
694   {
695     struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) addr;
696     struct sockaddr_in6 *netmask6 = (struct sockaddr_in6 *) netmask;
697     struct sockaddr_in6 * tmp = NULL;
698     struct sockaddr_in6 network6;
699
700     net = GNUNET_malloc(sizeof (struct ATS_Network) + 2 * sizeof (struct sockaddr_in6));
701     tmp = (struct sockaddr_in6 *) &net[1];
702     net->network = (struct sockaddr *) &tmp[0];
703     net->netmask = (struct sockaddr *) &tmp[1];
704     net->length = addrlen;
705
706     memset (&network6, 0, sizeof (network6));
707     network6.sin6_family = AF_INET6;
708 #if HAVE_SOCKADDR_IN_SIN_LEN
709     network6.sin6_len = sizeof (network6);
710 #endif
711     int c = 0;
712     uint32_t *addr_elem = (uint32_t *) &addr6->sin6_addr;
713     uint32_t *mask_elem = (uint32_t *) &netmask6->sin6_addr;
714     uint32_t *net_elem = (uint32_t *) &network6.sin6_addr;
715     for (c = 0; c < 4; c++)
716       net_elem[c] = addr_elem[c] & mask_elem[c];
717
718     memcpy (net->netmask, netmask6, sizeof (struct sockaddr_in6));
719     memcpy (net->network, &network6, sizeof (struct sockaddr_in6));
720   }
721
722   /* Store in list */
723   if (net != NULL)
724   {
725 #if VERBOSE_ATS
726     char * netmask = GNUNET_strdup (GNUNET_a2s((struct sockaddr *) net->netmask, addrlen));
727     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Adding network `%s', netmask `%s'\n",
728         GNUNET_a2s((struct sockaddr *) net->network, addrlen),
729         netmask);
730     GNUNET_free (netmask);
731 # endif
732     GNUNET_CONTAINER_DLL_insert(sh->net_head, sh->net_tail, net);
733   }
734   return GNUNET_OK;
735 }
736
737
738
739 /**
740  * Periodically get list of addresses
741  * @param cls closure
742  * @param tc Task context
743  */
744 static void
745 get_addresses (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
746 {
747   struct GNUNET_ATS_SchedulingHandle * sh = cls;
748   sh->interface_task = GNUNET_SCHEDULER_NO_TASK;
749   delete_networks (sh);
750   GNUNET_OS_network_interfaces_list(interface_proc, sh);
751   sh->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVALL,
752                                                      get_addresses,
753                                                      sh);
754 }
755
756 /**
757  * Returns where the address is located: LAN or WAN or ...
758  * @param sh the scheduling handle
759  * @param addr address
760  * @param addrlen address length
761  * @return location as GNUNET_ATS_Information
762  */
763
764 const struct GNUNET_ATS_Information
765 GNUNET_ATS_address_get_type (struct GNUNET_ATS_SchedulingHandle * sh, const struct sockaddr * addr, socklen_t addrlen)
766 {
767   GNUNET_assert (sh != NULL);
768   struct GNUNET_ATS_Information ats;
769   struct ATS_Network * cur = sh->net_head;
770   int type = GNUNET_ATS_NET_UNSPECIFIED;
771
772   if  (addr->sa_family == AF_UNIX)
773   {
774     type = GNUNET_ATS_NET_LOOPBACK;
775   }
776
777   /* IPv4 loopback check */
778   if  (addr->sa_family == AF_INET)
779   {
780     struct sockaddr_in * a4 = (struct sockaddr_in *) addr;
781
782     if ((a4->sin_addr.s_addr & htonl(0xff000000)) == htonl (0x7f000000))
783       type = GNUNET_ATS_NET_LOOPBACK;
784   }
785   /* IPv6 loopback check */
786   if  (addr->sa_family == AF_INET6)
787   {
788     struct sockaddr_in6 * a6 = (struct sockaddr_in6 *) addr;
789     if (IN6_IS_ADDR_LOOPBACK (&a6->sin6_addr))
790       type = GNUNET_ATS_NET_LOOPBACK;
791   }
792
793   /* Check local networks */
794   while ((cur != NULL) && (type == GNUNET_ATS_NET_UNSPECIFIED))
795   {
796     if (addrlen != cur->length)
797     {
798       cur = cur->next;
799       continue;
800     }
801
802     if (addr->sa_family == AF_INET)
803     {
804       struct sockaddr_in * a4 = (struct sockaddr_in *) addr;
805       struct sockaddr_in * net4 = (struct sockaddr_in *) cur->network;
806       struct sockaddr_in * mask4 = (struct sockaddr_in *) cur->netmask;
807
808       if (((a4->sin_addr.s_addr & mask4->sin_addr.s_addr)) == net4->sin_addr.s_addr)
809       {
810         char * net = GNUNET_strdup (GNUNET_a2s ((const struct sockaddr *) net4, addrlen));
811         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, "ats-scheduling-api",
812             "`%s' is in network `%s'\n",
813             GNUNET_a2s ((const struct sockaddr *)a4, addrlen),
814             net);
815         GNUNET_free (net);
816         type = GNUNET_ATS_NET_LAN;
817       }
818     }
819     if (addr->sa_family == AF_INET6)
820     {
821       struct sockaddr_in6 * a6 = (struct sockaddr_in6 *) addr;
822       struct sockaddr_in6 * net6 = (struct sockaddr_in6 *) cur->network;
823       struct sockaddr_in6 * mask6 = (struct sockaddr_in6 *) cur->netmask;
824
825       int res = GNUNET_YES;
826       int c = 0;
827       uint32_t *addr_elem = (uint32_t *) &a6->sin6_addr;
828       uint32_t *mask_elem = (uint32_t *) &mask6->sin6_addr;
829       uint32_t *net_elem = (uint32_t *) &net6->sin6_addr;
830       for (c = 0; c < 4; c++)
831         if ((addr_elem[c] & mask_elem[c]) != net_elem[c])
832           res = GNUNET_NO;
833
834       if (res == GNUNET_YES)
835       {
836         char * net = GNUNET_strdup (GNUNET_a2s ((const struct sockaddr *) net6, addrlen));
837         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' is in network `%s'\n",
838               GNUNET_a2s ((const struct sockaddr *) a6, addrlen),
839               net);
840         GNUNET_free (net);
841         type = GNUNET_ATS_NET_LAN;
842       }
843     }
844     cur = cur->next;
845   }
846
847   /* no local network found for this address, default: WAN */
848   if (type == GNUNET_ATS_NET_UNSPECIFIED)
849     type = GNUNET_ATS_NET_WAN;
850
851 #if VERBOSE
852   const char * range;
853   switch (type) {
854     case GNUNET_ATS_NET_WAN:
855         range = "WAN";
856       break;
857     case GNUNET_ATS_NET_LAN:
858         range = "LAN";
859       break;
860     case GNUNET_ATS_NET_LOOPBACK:
861         range = "LOOPBACK";
862       break;
863     default:
864
865       break;
866   }
867 #endif
868
869   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
870   ats.value = htonl (type);
871   return (const struct GNUNET_ATS_Information) ats;
872 }
873
874 /**
875  * Initialize the ATS subsystem.
876  *
877  * @param cfg configuration to use
878  * @param suggest_cb notification to call whenever the suggestation changed
879  * @param suggest_cb_cls closure for 'suggest_cb'
880  * @return ats context
881  */
882 struct GNUNET_ATS_SchedulingHandle *
883 GNUNET_ATS_scheduling_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
884                             GNUNET_ATS_AddressSuggestionCallback suggest_cb,
885                             void *suggest_cb_cls)
886 {
887   struct GNUNET_ATS_SchedulingHandle *sh;
888
889   sh = GNUNET_malloc (sizeof (struct GNUNET_ATS_SchedulingHandle));
890   sh->cfg = cfg;
891   sh->suggest_cb = suggest_cb;
892   sh->suggest_cb_cls = suggest_cb_cls;
893   GNUNET_array_grow (sh->session_array, sh->session_array_size, 4);
894   GNUNET_OS_network_interfaces_list(interface_proc, sh);
895   sh->interface_task = GNUNET_SCHEDULER_add_delayed (INTERFACE_PROCESSING_INTERVALL,
896       get_addresses,
897       sh);
898   reconnect (sh);
899   return sh;
900 }
901
902
903 /**
904  * Client is done with ATS scheduling, release resources.
905  *
906  * @param sh handle to release
907  */
908 void
909 GNUNET_ATS_scheduling_done (struct GNUNET_ATS_SchedulingHandle *sh)
910 {
911   struct PendingMessage *p;
912
913   while (NULL != (p = sh->pending_head))
914   {
915     GNUNET_CONTAINER_DLL_remove (sh->pending_head, sh->pending_tail, p);
916     GNUNET_free (p);
917   }
918   if (NULL != sh->client)
919   {
920     GNUNET_CLIENT_disconnect (sh->client);
921     sh->client = NULL;
922   }
923   if (GNUNET_SCHEDULER_NO_TASK != sh->task)
924   {
925     GNUNET_SCHEDULER_cancel (sh->task);
926     sh->task = GNUNET_SCHEDULER_NO_TASK;
927   }
928
929   delete_networks (sh);
930   if (sh->interface_task != GNUNET_SCHEDULER_NO_TASK)
931   {
932     GNUNET_SCHEDULER_cancel(sh->interface_task);
933     sh->interface_task = GNUNET_SCHEDULER_NO_TASK;
934   }
935   GNUNET_array_grow (sh->session_array, sh->session_array_size, 0);
936   GNUNET_free (sh);
937   sh = NULL;
938 }
939
940
941 /**
942  * We would like to establish a new connection with a peer.  ATS
943  * should suggest a good address to begin with.
944  *
945  * @param sh handle
946  * @param peer identity of the peer we need an address for
947  */
948 void
949 GNUNET_ATS_suggest_address (struct GNUNET_ATS_SchedulingHandle *sh,
950                             const struct GNUNET_PeerIdentity *peer)
951 {
952   struct PendingMessage *p;
953   struct RequestAddressMessage *m;
954
955   p = GNUNET_malloc (sizeof (struct PendingMessage) +
956                      sizeof (struct RequestAddressMessage));
957   p->size = sizeof (struct RequestAddressMessage);
958   p->is_init = GNUNET_NO;
959   m = (struct RequestAddressMessage *) &p[1];
960   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS);
961   m->header.size = htons (sizeof (struct RequestAddressMessage));
962   m->reserved = htonl (0);
963   m->peer = *peer;
964   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
965   do_transmit (sh);
966 }
967
968
969 /**
970  * We would like to stop receiving address updates for this peer
971  *
972  * @param sh handle
973  * @param peer identity of the peer
974  */
975 void
976 GNUNET_ATS_suggest_address_cancel (struct GNUNET_ATS_SchedulingHandle *sh,
977                                    const struct GNUNET_PeerIdentity *peer)
978 {
979   struct PendingMessage *p;
980   struct RequestAddressMessage *m;
981
982   p = GNUNET_malloc (sizeof (struct PendingMessage) +
983                      sizeof (struct RequestAddressMessage));
984   p->size = sizeof (struct RequestAddressMessage);
985   p->is_init = GNUNET_NO;
986   m = (struct RequestAddressMessage *) &p[1];
987   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_REQUEST_ADDRESS_CANCEL);
988   m->header.size = htons (sizeof (struct RequestAddressMessage));
989   m->reserved = htonl (0);
990   m->peer = *peer;
991   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
992   do_transmit (sh);
993 }
994
995 /**
996  * We have updated performance statistics for a given address.  Note
997  * that this function can be called for addresses that are currently
998  * in use as well as addresses that are valid but not actively in use.
999  * Furthermore, the peer may not even be connected to us right now (in
1000  * which case the call may be ignored or the information may be stored
1001  * for later use).  Update bandwidth assignments.
1002  *
1003  * @param sh handle
1004  * @param address the address
1005  * @param session session handle (if available)
1006  * @param ats performance data for the address
1007  * @param ats_count number of performance records in 'ats'
1008  */
1009 void
1010 GNUNET_ATS_address_update (struct GNUNET_ATS_SchedulingHandle *sh,
1011                            const struct GNUNET_HELLO_Address *address,
1012                            struct Session *session,
1013                            const struct GNUNET_ATS_Information *ats,
1014                            uint32_t ats_count)
1015 {
1016   struct PendingMessage *p;
1017   struct AddressUpdateMessage *m;
1018   struct GNUNET_ATS_Information *am;
1019   char *pm;
1020   size_t namelen;
1021   size_t msize;
1022
1023   if (address == NULL)
1024   {
1025     GNUNET_break (0);
1026     return;
1027   }
1028   if ((address == NULL) && (session == NULL))
1029   {
1030     GNUNET_break (0);
1031     return;
1032   }
1033
1034   namelen =
1035       (address->transport_name ==
1036        NULL) ? 0 : strlen (address->transport_name) + 1;
1037   msize =
1038       sizeof (struct AddressUpdateMessage) + address->address_length +
1039       ats_count * sizeof (struct GNUNET_ATS_Information) + namelen;
1040   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1041       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1042       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1043       (ats_count >=
1044        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information)))
1045   {
1046     GNUNET_break (0);
1047     return;
1048   }
1049
1050   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1051   p->size = msize;
1052   p->is_init = GNUNET_NO;
1053   m = (struct AddressUpdateMessage *) &p[1];
1054   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_UPDATE);
1055   m->header.size = htons (msize);
1056   m->ats_count = htonl (ats_count);
1057   m->peer = address->peer;
1058   m->address_length = htons (address->address_length);
1059   m->plugin_name_length = htons (namelen);
1060   m->session_id = htonl (get_session_id (sh, session, &address->peer));
1061   am = (struct GNUNET_ATS_Information *) &m[1];
1062   memcpy (am, ats, ats_count * sizeof (struct GNUNET_ATS_Information));
1063   pm = (char *) &am[ats_count];
1064   memcpy (pm, address->address, address->address_length);
1065   memcpy (&pm[address->address_length], address->transport_name, namelen);
1066   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1067   do_transmit (sh);
1068 }
1069
1070
1071 /**
1072  * An address is now in use or not used any more.
1073  *
1074  * @param sh handle
1075  * @param address the address
1076  * @param session session handle
1077  * @param in_use GNUNET_YES if this address is now used, GNUNET_NO
1078  * if address is not used any more
1079  */
1080 void
1081 GNUNET_ATS_address_in_use (struct GNUNET_ATS_SchedulingHandle *sh,
1082                            const struct GNUNET_HELLO_Address *address,
1083                            struct Session *session, int in_use)
1084 {
1085   struct PendingMessage *p;
1086   struct AddressUseMessage *m;
1087   char *pm;
1088   size_t namelen;
1089   size_t msize;
1090
1091   GNUNET_assert (NULL != address);
1092   namelen =
1093       (address->transport_name ==
1094        NULL) ? 0 : strlen (address->transport_name) + 1;
1095   msize = sizeof (struct AddressUseMessage) + address->address_length + namelen;
1096   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1097       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1098       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1099   {
1100     GNUNET_break (0);
1101     return;
1102   }
1103
1104   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1105   p->size = msize;
1106   p->is_init = GNUNET_NO;
1107   m = (struct AddressUseMessage *) &p[1];
1108   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_IN_USE);
1109   m->header.size = htons (msize);
1110   m->peer = address->peer;
1111   m->in_use = htons (in_use);
1112   m->address_length = htons (address->address_length);
1113   m->plugin_name_length = htons (namelen);
1114   m->session_id = htonl (get_session_id (sh, session, &address->peer));
1115   pm = (char *) &m[1];
1116   memcpy (pm, address->address, address->address_length);
1117   memcpy (&pm[address->address_length], address->transport_name, namelen);
1118   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1119
1120   do_transmit (sh);
1121 }
1122
1123 /**
1124  * A session got destroyed, stop including it as a valid address.
1125  *
1126  * @param sh handle
1127  * @param address the address
1128  * @param session session handle that is no longer valid
1129  */
1130 void
1131 GNUNET_ATS_address_destroyed (struct GNUNET_ATS_SchedulingHandle *sh,
1132                               const struct GNUNET_HELLO_Address *address,
1133                               struct Session *session)
1134 {
1135   struct PendingMessage *p;
1136   struct AddressDestroyedMessage *m;
1137   char *pm;
1138   size_t namelen;
1139   size_t msize;
1140   uint32_t session_id;
1141
1142   GNUNET_assert (address->transport_name != NULL);
1143   namelen = strlen (address->transport_name) + 1;
1144   GNUNET_assert (namelen > 1);
1145   msize =
1146       sizeof (struct AddressDestroyedMessage) + address->address_length +
1147       namelen;
1148   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1149       (address->address_length >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1150       (namelen >= GNUNET_SERVER_MAX_MESSAGE_SIZE))
1151   {
1152     GNUNET_break (0);
1153     return;
1154   }
1155
1156   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1157   p->size = msize;
1158   p->is_init = GNUNET_NO;
1159   m = (struct AddressDestroyedMessage *) &p[1];
1160   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESS_DESTROYED);
1161   m->header.size = htons (msize);
1162   m->reserved = htonl (0);
1163   m->peer = address->peer;
1164   m->address_length = htons (address->address_length);
1165   m->plugin_name_length = htons (namelen);
1166   session_id = get_session_id (sh, session, &address->peer);
1167   m->session_id = htonl (session_id);
1168   pm = (char *) &m[1];
1169   memcpy (pm, address->address, address->address_length);
1170   memcpy (&pm[address->address_length], address->transport_name, namelen);
1171   GNUNET_CONTAINER_DLL_insert_tail (sh->pending_head, sh->pending_tail, p);
1172   do_transmit (sh);
1173   remove_session (sh, session_id, &address->peer);
1174 }
1175
1176 /* end of ats_api_scheduling.c */