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