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