038a349aaa4122f168c9f97975ab0fce27ec2624
[oweals/gnunet.git] / src / ats / ats_api_performance.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_performance.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 /**
32  * Message in linked list we should send to the ATS service.  The
33  * actual binary message follows this struct.
34  */
35 struct PendingMessage
36 {
37
38   /**
39    * Kept in a DLL.
40    */
41   struct PendingMessage *next;
42
43   /**
44    * Kept in a DLL.
45    */
46   struct PendingMessage *prev;
47
48   /**
49    * Size of the message.
50    */
51   size_t size;
52
53   /**
54    * Is this the 'ATS_START' message?
55    */
56   int is_init;
57 };
58
59
60 /**
61  * Linked list of pending reservations.
62  */
63 struct GNUNET_ATS_ReservationContext
64 {
65
66   /**
67    * Kept in a DLL.
68    */
69   struct GNUNET_ATS_ReservationContext *next;
70
71   /**
72    * Kept in a DLL.
73    */
74   struct GNUNET_ATS_ReservationContext *prev;
75
76   /**
77    * Target peer.
78    */
79   struct GNUNET_PeerIdentity peer;
80
81   /**
82    * Desired reservation
83    */
84   int32_t size;
85
86   /**
87    * Function to call on result.
88    */
89   GNUNET_ATS_ReservationCallback rcb;
90
91   /**
92    * Closure for 'rcb'
93    */
94   void *rcb_cls;
95
96   /**
97    * Do we need to undo this reservation if it succeeded?  Set to
98    * GNUNET_YES if a reservation is cancelled.  (at that point, 'info'
99    * is also set to NULL; however, info will ALSO be NULL for the
100    * reservation context that is created to undo the original request,
101    * so 'info' being NULL cannot be used to check if undo is
102    * required).
103    */
104   int undo;
105 };
106
107
108 /**
109  * Linked list of pending reservations.
110  */
111 struct GNUNET_ATS_AddressListHandle
112 {
113
114   /**
115    * Kept in a DLL.
116    */
117   struct GNUNET_ATS_AddressListHandle *next;
118
119   /**
120    * Kept in a DLL.
121    */
122   struct GNUNET_ATS_AddressListHandle *prev;
123
124   /**
125    * Performance handle
126    */
127   struct GNUNET_ATS_PerformanceHandle *ph;
128
129   /**
130    * Callback
131    */
132   GNUNET_ATS_AddressInformationCallback cb;
133
134   /**
135    * Callback closure
136    */
137   void *cb_cls;
138
139   /**
140    * Target peer.
141    */
142   struct GNUNET_PeerIdentity peer;
143
144   /**
145    * Return all or specific peer only
146    */
147   int all_peers;
148
149   /**
150    * Return all or used address only
151    */
152   int all_addresses;
153
154   /**
155    * Request multiplexing
156    */
157   uint32_t id;
158 };
159
160
161
162 struct GNUNET_ATS_PerformanceMonitorHandle
163 {
164         struct GNUNET_ATS_PerformanceMonitorHandle *next;
165         struct GNUNET_ATS_PerformanceMonitorHandle *prev;
166
167         struct GNUNET_ATS_PerformanceHandle * ph;
168
169         GNUNET_ATS_PerformanceMonitorCb moncb;
170         void *moncb_cls;
171
172         uint32_t id;
173 };
174
175
176 /**
177  * ATS Handle to obtain and/or modify performance information.
178  */
179 struct GNUNET_ATS_PerformanceHandle
180 {
181
182   /**
183    * Our configuration.
184    */
185   const struct GNUNET_CONFIGURATION_Handle *cfg;
186
187   /**
188    * Callback to invoke on performance changes.
189    */
190   GNUNET_ATS_AddressInformationCallback infocb;
191
192   /**
193    * Closure for 'infocb'.
194    */
195   void *infocb_cls;
196
197   /**
198    * Connection to ATS service.
199    */
200   struct GNUNET_CLIENT_Connection *client;
201
202   /**
203    * Head of list of messages for the ATS service.
204    */
205   struct PendingMessage *pending_head;
206
207   /**
208    * Tail of list of messages for the ATS service
209    */
210   struct PendingMessage *pending_tail;
211
212   /**
213    * Head of linked list of pending reservation requests.
214    */
215   struct GNUNET_ATS_ReservationContext *reservation_head;
216
217   /**
218    * Tail of linked list of pending reservation requests.
219    */
220   struct GNUNET_ATS_ReservationContext *reservation_tail;
221
222   /**
223    * Head of linked list of pending address list requests.
224    */
225   struct GNUNET_ATS_AddressListHandle *addresslist_head;
226
227   /**
228    * Tail of linked list of pending address list requests.
229    */
230   struct GNUNET_ATS_AddressListHandle *addresslist_tail;
231
232   /**
233    * Head of linked list of pending performance monitors.
234    */
235   struct GNUNET_ATS_PerformanceMonitorHandle *monitor_head;
236
237   /**
238    * Tail of linked list of pending performance monitors.
239    */
240   struct GNUNET_ATS_PerformanceMonitorHandle *monitor_tail;
241
242   /**
243    * Current request for transmission to ATS.
244    */
245   struct GNUNET_CLIENT_TransmitHandle *th;
246
247   /**
248    * Task to trigger reconnect.
249    */
250   GNUNET_SCHEDULER_TaskIdentifier task;
251
252   /**
253    * Monitor request multiplexing
254    */
255   uint32_t monitor_id;
256
257   /**
258    * Request multiplexing
259    */
260   uint32_t id;
261 };
262
263
264 /**
265  * Re-establish the connection to the ATS service.
266  *
267  * @param ph handle to use to re-connect.
268  */
269 static void
270 reconnect (struct GNUNET_ATS_PerformanceHandle *ph);
271
272
273 /**
274  * Re-establish the connection to the ATS service.
275  *
276  * @param cls handle to use to re-connect.
277  * @param tc scheduler context
278  */
279 static void
280 reconnect_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
281 {
282   struct GNUNET_ATS_PerformanceHandle *ph = cls;
283
284   ph->task = GNUNET_SCHEDULER_NO_TASK;
285   reconnect (ph);
286 }
287
288
289 /**
290  * Transmit messages from the message queue to the service
291  * (if there are any, and if we are not already trying).
292  *
293  * @param ph handle to use
294  */
295 static void
296 do_transmit (struct GNUNET_ATS_PerformanceHandle *ph);
297
298
299 /**
300  * We can now transmit a message to ATS. Do it.
301  *
302  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
303  * @param size number of bytes we can transmit to ATS
304  * @param buf where to copy the messages
305  * @return number of bytes copied into buf
306  */
307 static size_t
308 transmit_message_to_ats (void *cls, size_t size, void *buf)
309 {
310   struct GNUNET_ATS_PerformanceHandle *ph = cls;
311   struct PendingMessage *p;
312   size_t ret;
313   char *cbuf;
314
315   ph->th = NULL;
316   ret = 0;
317   cbuf = buf;
318   while ((NULL != (p = ph->pending_head)) && (p->size <= size))
319   {
320     memcpy (&cbuf[ret], &p[1], p->size);
321     ret += p->size;
322     size -= p->size;
323     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
324     GNUNET_free (p);
325   }
326   do_transmit (ph);
327   return ret;
328 }
329
330
331 /**
332  * Transmit messages from the message queue to the service
333  * (if there are any, and if we are not already trying).
334  *
335  * @param ph handle to use
336  */
337 static void
338 do_transmit (struct GNUNET_ATS_PerformanceHandle *ph)
339 {
340   struct PendingMessage *p;
341
342   if (NULL != ph->th)
343     return;
344   if (NULL == (p = ph->pending_head))
345     return;
346   if (NULL == ph->client)
347     return;                     /* currently reconnecting */
348   ph->th =
349       GNUNET_CLIENT_notify_transmit_ready (ph->client, p->size,
350                                            GNUNET_TIME_UNIT_FOREVER_REL,
351                                            GNUNET_YES, &transmit_message_to_ats,
352                                            ph);
353 }
354
355
356 /**
357  * We received a peer information message.  Validate and process it.
358  *
359  * @param ph our context with the callback
360  * @param msg the message
361  * @return GNUNET_OK if the message was well-formed
362  */
363 static int
364 process_pi_message (struct GNUNET_ATS_PerformanceHandle *ph,
365                     const struct GNUNET_MessageHeader *msg)
366 {
367   const struct PeerInformationMessage *pi;
368   const struct GNUNET_ATS_Information *atsi;
369   const char *plugin_address;
370   const char *plugin_name;
371   struct GNUNET_HELLO_Address address;
372   uint16_t plugin_address_length;
373   uint16_t plugin_name_length;
374   uint32_t ats_count;
375
376   if (ntohs (msg->size) < sizeof (struct PeerInformationMessage))
377   {
378     GNUNET_break (0);
379     return GNUNET_SYSERR;
380   }
381
382   pi = (const struct PeerInformationMessage *) msg;
383   ats_count = ntohl (pi->ats_count);
384   plugin_address_length = ntohs (pi->address_length);
385   plugin_name_length = ntohs (pi->plugin_name_length);
386   atsi = (const struct GNUNET_ATS_Information *) &pi[1];
387   plugin_address = (const char *) &atsi[ats_count];
388   plugin_name = &plugin_address[plugin_address_length];
389   if ((plugin_address_length + plugin_name_length +
390        ats_count * sizeof (struct GNUNET_ATS_Information) +
391        sizeof (struct PeerInformationMessage) != ntohs (msg->size)) ||
392       (ats_count >
393        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information))
394       || (plugin_name[plugin_name_length - 1] != '\0'))
395   {
396     GNUNET_break (0);
397     return GNUNET_SYSERR;
398   }
399   if (ph->infocb == NULL)
400   {
401     return GNUNET_OK;
402   }
403
404   address.peer = pi->peer;
405   address.address = plugin_address;
406   address.address_length = plugin_address_length;
407   address.transport_name = plugin_name;
408   ph->infocb (ph->infocb_cls, &address, pi->bandwidth_out, pi->bandwidth_in,
409               atsi, ats_count);
410   return GNUNET_OK;
411 }
412
413
414 /**
415  * We received a reservation result message.  Validate and process it.
416  *
417  * @param ph our context with the callback
418  * @param msg the message
419  * @return GNUNET_OK if the message was well-formed
420  */
421 static int
422 process_rr_message (struct GNUNET_ATS_PerformanceHandle *ph,
423                     const struct GNUNET_MessageHeader *msg)
424 {
425   const struct ReservationResultMessage *rr;
426   struct GNUNET_ATS_ReservationContext *rc;
427   int32_t amount;
428
429   if (ntohs (msg->size) < sizeof (struct ReservationResultMessage))
430   {
431     GNUNET_break (0);
432     return GNUNET_SYSERR;
433   }
434   rr = (const struct ReservationResultMessage *) msg;
435   amount = ntohl (rr->amount);
436   rc = ph->reservation_head;
437   if (0 != memcmp (&rr->peer, &rc->peer, sizeof (struct GNUNET_PeerIdentity)))
438   {
439     GNUNET_break (0);
440     return GNUNET_SYSERR;
441   }
442   GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail, rc);
443   if ((amount == 0) || (rc->rcb != NULL))
444   {
445     /* tell client if not cancelled */
446     if (rc->rcb != NULL)
447       rc->rcb (rc->rcb_cls, &rr->peer, amount,
448                GNUNET_TIME_relative_ntoh (rr->res_delay));
449     GNUNET_free (rc);
450     return GNUNET_OK;
451   }
452   /* amount non-zero, but client cancelled, consider undo! */
453   if (GNUNET_YES != rc->undo)
454   {
455     GNUNET_free (rc);
456     return GNUNET_OK;           /* do not try to undo failed undos or negative amounts */
457   }
458   GNUNET_free (rc);
459   (void) GNUNET_ATS_reserve_bandwidth (ph, &rr->peer, -amount, NULL, NULL);
460   return GNUNET_OK;
461 }
462
463
464 /**
465  * We received a reservation result message.  Validate and process it.
466  *
467  * @param ph our context with the callback
468  * @param msg the message
469  * @return GNUNET_OK if the message was well-formed
470  */
471 static int
472 process_ar_message (struct GNUNET_ATS_PerformanceHandle *ph,
473                     const struct GNUNET_MessageHeader *msg)
474 {
475   const struct PeerInformationMessage *pi;
476   struct GNUNET_ATS_AddressListHandle *alh;
477   struct GNUNET_ATS_AddressListHandle *next;
478   const struct GNUNET_ATS_Information *atsi;
479   const char *plugin_address;
480   const char *plugin_name;
481   struct GNUNET_HELLO_Address address;
482   struct GNUNET_PeerIdentity allzeros;
483   struct GNUNET_BANDWIDTH_Value32NBO bandwidth_zero;
484   uint16_t plugin_address_length;
485   uint16_t plugin_name_length;
486   uint32_t ats_count;
487   uint32_t active;
488   uint32_t id;
489
490   if (ntohs (msg->size) < sizeof (struct PeerInformationMessage))
491   {
492     GNUNET_break (0);
493     return GNUNET_SYSERR;
494   }
495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
496       _("Received %s message\n"), "ATS_ADDRESSLIST_RESPONSE");
497
498   pi = (const struct PeerInformationMessage *) msg;
499   id = ntohl (pi->id);
500   ats_count = ntohl (pi->ats_count);
501   active = ntohl (pi->address_active);
502   plugin_address_length = ntohs (pi->address_length);
503   plugin_name_length = ntohs (pi->plugin_name_length);
504   atsi = (const struct GNUNET_ATS_Information *) &pi[1];
505   plugin_address = (const char *) &atsi[ats_count];
506   plugin_name = &plugin_address[plugin_address_length];
507   if ((plugin_address_length + plugin_name_length +
508        ats_count * sizeof (struct GNUNET_ATS_Information) +
509        sizeof (struct PeerInformationMessage) != ntohs (msg->size)) ||
510       (ats_count >
511        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_ATS_Information))
512       || (plugin_name[plugin_name_length - 1] != '\0'))
513   {
514     GNUNET_break (0);
515     return GNUNET_SYSERR;
516   }
517
518   next = ph->addresslist_head;
519   while (NULL != (alh = next))
520   {
521       next = alh->next;
522       if (alh->id == id)
523         break;
524   }
525   if (NULL == alh)
526   {
527       /* was canceled */
528       return GNUNET_SYSERR;
529   }
530
531   memset (&allzeros, '\0', sizeof (allzeros));
532   if ((0 == memcmp (&allzeros, &pi->peer, sizeof (allzeros))) &&
533       (0 == plugin_name_length) &&
534       (0 == plugin_address_length) &&
535       (0 == ats_count))
536   {
537       /* Done */
538       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
539           _("Received last message for %s \n"), "ATS_ADDRESSLIST_RESPONSE");
540       bandwidth_zero.value__ = htonl (0);
541       if (NULL != alh->cb)
542         alh->cb (ph->infocb_cls,
543               NULL,
544               bandwidth_zero, bandwidth_zero,
545               NULL, 0);
546       GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, ph->addresslist_tail, alh);
547       GNUNET_free (alh);
548       return GNUNET_OK;
549   }
550
551   address.peer = pi->peer;
552   address.address = plugin_address;
553   address.address_length = plugin_address_length;
554   address.transport_name = plugin_name;
555
556   if ((GNUNET_YES == alh->all_addresses) || (GNUNET_YES == active))
557   {
558     if (NULL != alh->cb)
559       alh->cb (ph->infocb_cls,
560             &address,
561             pi->bandwidth_out, pi->bandwidth_in,
562             atsi, ats_count);
563   }
564   return GNUNET_OK;
565 }
566
567 /**
568  * We received a monitor response message.  Validate and process it.
569  *
570  * @param ph our context with the callback
571  * @param msg the message
572  * @return GNUNET_OK if the message was well-formed
573  */
574 static int
575 process_mr_message (struct GNUNET_ATS_PerformanceHandle *ph,
576                     const struct GNUNET_MessageHeader *msg)
577 {
578         struct MonitorResponseMessage *mrm = (struct MonitorResponseMessage *) msg;
579         struct GNUNET_ATS_PerformanceMonitorHandle *cur;
580         struct GNUNET_ATS_Information *ats;
581         size_t msg_size;
582         uint32_t ats_count;
583         uint32_t id;
584
585   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
586       _("Received %s message\n"), "ATS_MONITOR_RESPONSE");
587
588         msg_size = ntohs (msg->size);
589         if (msg_size < sizeof (struct MonitorResponseMessage))
590         {
591                 GNUNET_break (0);
592                 return GNUNET_SYSERR;
593         }
594
595         ats_count = ntohl (mrm->ats_count);
596         if (msg_size != (sizeof (struct MonitorResponseMessage) +
597                         ats_count * sizeof (struct GNUNET_ATS_Information)))
598                 {
599                         GNUNET_break (0);
600                         return GNUNET_SYSERR;
601                 }
602
603         id = ntohl (mrm->id);
604         /* Do work here */
605         for (cur = ph->monitor_head; NULL != cur; cur = cur->next)
606         {
607                         if (id == cur->id)
608                                 break;
609         }
610   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
611       _("Received %s message for id %u\n"), "ATS_MONITOR_RESPONSE", id);
612         if (NULL == cur)
613         {
614                 GNUNET_break (0);
615                 return GNUNET_SYSERR;
616         }
617
618         ats = (struct GNUNET_ATS_Information *) &mrm[1];
619         cur->moncb (cur->moncb_cls, &mrm->peer, ats, ats_count);
620
621         return GNUNET_OK;
622 }
623
624
625 /**
626  * Type of a function to call when we receive a message
627  * from the service.
628  *
629  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
630  * @param msg message received, NULL on timeout or fatal error
631  */
632 static void
633 process_ats_message (void *cls, const struct GNUNET_MessageHeader *msg)
634 {
635   struct GNUNET_ATS_PerformanceHandle *ph = cls;
636
637   if (NULL == msg)
638     goto reconnect;
639   switch (ntohs (msg->type))
640   {
641   case GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION:
642     if (GNUNET_OK != process_pi_message (ph, msg))
643       goto reconnect;
644     break;
645   case GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT:
646     if (GNUNET_OK != process_rr_message (ph, msg))
647       goto reconnect;
648     break;
649   case GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE:
650     if (GNUNET_OK != process_ar_message (ph, msg))
651       goto reconnect;
652     break;
653   case GNUNET_MESSAGE_TYPE_ATS_MONITOR_RESPONSE:
654     if (GNUNET_OK != process_mr_message (ph, msg))
655       goto reconnect;
656     break;
657   default:
658     GNUNET_break (0);
659     goto reconnect;
660   }
661   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
662                          GNUNET_TIME_UNIT_FOREVER_REL);
663   return;
664 reconnect:
665   if (NULL != ph->th)
666   {
667     GNUNET_CLIENT_notify_transmit_ready_cancel (ph->th);
668     ph->th = NULL;
669   }
670   GNUNET_CLIENT_disconnect (ph->client);
671   ph->client = NULL;
672   ph->task =
673       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &reconnect_task,
674                                     ph);
675 }
676
677
678 /**
679  * Re-establish the connection to the ATS service.
680  *
681  * @param ph handle to use to re-connect.
682  */
683 static void
684 reconnect (struct GNUNET_ATS_PerformanceHandle *ph)
685 {
686   struct PendingMessage *p;
687   struct ClientStartMessage *init;
688
689   GNUNET_assert (NULL == ph->client);
690   ph->client = GNUNET_CLIENT_connect ("ats", ph->cfg);
691   GNUNET_assert (NULL != ph->client);
692   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
693                          GNUNET_TIME_UNIT_FOREVER_REL);
694   if ((NULL == (p = ph->pending_head)) || (GNUNET_YES != p->is_init))
695   {
696     p = GNUNET_malloc (sizeof (struct PendingMessage) +
697                        sizeof (struct ClientStartMessage));
698     p->size = sizeof (struct ClientStartMessage);
699     p->is_init = GNUNET_YES;
700     init = (struct ClientStartMessage *) &p[1];
701     init->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_START);
702     init->header.size = htons (sizeof (struct ClientStartMessage));
703     init->start_flag =
704         htonl ((ph->infocb ==
705                 NULL) ? START_FLAG_PERFORMANCE_NO_PIC :
706                START_FLAG_PERFORMANCE_WITH_PIC);
707     GNUNET_CONTAINER_DLL_insert (ph->pending_head, ph->pending_tail, p);
708   }
709   do_transmit (ph);
710 }
711
712
713
714 /**
715  * Get handle to access performance API of the ATS subsystem.
716  *
717  * @param cfg configuration to use
718  * @param infocb function to call on allocation changes, can be NULL
719  * @param infocb_cls closure for infocb
720  * @return ats performance context
721  */
722 struct GNUNET_ATS_PerformanceHandle *
723 GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
724                              GNUNET_ATS_AddressInformationCallback infocb,
725                              void *infocb_cls)
726 {
727   struct GNUNET_ATS_PerformanceHandle *ph;
728
729   ph = GNUNET_malloc (sizeof (struct GNUNET_ATS_PerformanceHandle));
730   ph->cfg = cfg;
731   ph->infocb = infocb;
732   ph->infocb_cls = infocb_cls;
733   ph->id  = 0;
734   reconnect (ph);
735   return ph;
736 }
737
738
739 /**
740  * Start monitoring performance information
741  *
742  * @param ph performance handle to use
743  * @param monitor_cb function to call on performance changes
744  * @param monitor_cb_cls closure for infocb
745  * @return a performance monitor handle
746  */
747 struct GNUNET_ATS_PerformanceMonitorHandle *
748 GNUNET_ATS_performance_monitor_start (struct GNUNET_ATS_PerformanceHandle * ph,
749                                                                                                                                                         GNUNET_ATS_PerformanceMonitorCb monitor_cb,
750                                                                                                                                                         void * monitor_cb_cls)
751 {
752         struct MonitorMessage *m;
753         struct PendingMessage *p;
754         GNUNET_assert (NULL != ph);
755
756         if (NULL == monitor_cb)
757                 return NULL;
758
759         struct GNUNET_ATS_PerformanceMonitorHandle *phm =
760                         GNUNET_malloc (sizeof (struct GNUNET_ATS_PerformanceMonitorHandle));
761
762         ph->monitor_id ++;
763         phm->id = ph->monitor_id;
764         phm->ph = ph;
765         phm->moncb = monitor_cb;
766         phm->moncb_cls = monitor_cb_cls;
767         GNUNET_CONTAINER_DLL_insert (ph->monitor_head, ph->monitor_tail, phm);
768
769   p = GNUNET_malloc (sizeof (struct PendingMessage) +
770                      sizeof (struct MonitorMessage));
771   p->size = sizeof (struct MonitorMessage);
772   m = (struct MonitorMessage *) &p[1];
773   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_MONITOR);
774   m->header.size = htons (sizeof (struct MonitorMessage));
775   m->id = htonl (phm->id);
776   m->op = htonl (GNUNET_YES);
777   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
778   do_transmit (ph);
779
780         return phm;
781 }
782
783
784 /**
785  * Stop monitoring performance information
786  *
787  * @param ph performance handle to use
788  * @param monitor_cb function to call on performance changes
789  * @param monitor_cb_cls closure for infocb
790  * @return a performance monitor handle
791  */
792 void
793 GNUNET_ATS_performance_monitor_stop (struct GNUNET_ATS_PerformanceMonitorHandle * phm)
794 {
795         struct MonitorMessage *m;
796         struct PendingMessage *p;
797
798         GNUNET_assert (NULL != phm);
799
800   p = GNUNET_malloc (sizeof (struct PendingMessage) +
801                      sizeof (struct MonitorMessage));
802   p->size = sizeof (struct MonitorMessage);
803   m = (struct MonitorMessage *) &p[1];
804   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_MONITOR);
805   m->header.size = htons (sizeof (struct MonitorMessage));
806   m->id = htonl (phm->id);
807   m->op = htonl (GNUNET_NO);
808   GNUNET_CONTAINER_DLL_insert_tail (phm->ph->pending_head, phm->ph->pending_tail, p);
809   do_transmit (phm->ph);
810
811         GNUNET_CONTAINER_DLL_remove (phm->ph->monitor_head, phm->ph->monitor_tail, phm);
812         GNUNET_free (phm);
813 }
814
815 /**
816  * Client is done using the ATS performance subsystem, release resources.
817  *
818  * @param ph handle
819  */
820 void
821 GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph)
822 {
823   struct PendingMessage *p;
824   struct GNUNET_ATS_ReservationContext *rc;
825   struct GNUNET_ATS_AddressListHandle *alh;
826   struct GNUNET_ATS_PerformanceMonitorHandle *phm;
827
828   while (NULL != (p = ph->pending_head))
829   {
830     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
831     GNUNET_free (p);
832   }
833   while (NULL != (alh = ph->addresslist_head))
834   {
835     GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, ph->addresslist_tail,
836                                  alh);
837     GNUNET_free (alh);
838   }
839   while (NULL != (rc = ph->reservation_head))
840   {
841     GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail,
842                                  rc);
843     GNUNET_break (NULL == rc->rcb);
844     GNUNET_free (rc);
845   }
846   while (NULL != (phm = ph->monitor_head))
847   {
848     GNUNET_CONTAINER_DLL_remove (ph->monitor_head, ph->monitor_tail, phm);
849     GNUNET_free (phm);
850   }
851   if (GNUNET_SCHEDULER_NO_TASK != ph->task)
852   {
853     GNUNET_SCHEDULER_cancel (ph->task);
854     ph->task = GNUNET_SCHEDULER_NO_TASK;
855   }
856   if (NULL != ph->client)
857   {
858     GNUNET_CLIENT_disconnect (ph->client);
859     ph->client = NULL;
860   }
861   GNUNET_free (ph);
862 }
863
864
865 /**
866  * Reserve inbound bandwidth from the given peer.  ATS will look at
867  * the current amount of traffic we receive from the peer and ensure
868  * that the peer could add 'amount' of data to its stream.
869  *
870  * @param ph performance handle
871  * @param peer identifies the peer
872  * @param amount reserve N bytes for receiving, negative
873  *                amounts can be used to undo a (recent) reservation;
874  * @param rcb function to call with the resulting reservation information
875  * @param rcb_cls closure for info
876  * @return NULL on error
877  * @deprecated will be replaced soon
878  */
879 struct GNUNET_ATS_ReservationContext *
880 GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph,
881                               const struct GNUNET_PeerIdentity *peer,
882                               int32_t amount,
883                               GNUNET_ATS_ReservationCallback rcb, void *rcb_cls)
884 {
885   struct GNUNET_ATS_ReservationContext *rc;
886   struct PendingMessage *p;
887   struct ReservationRequestMessage *m;
888
889   rc = GNUNET_malloc (sizeof (struct GNUNET_ATS_ReservationContext));
890   rc->size = amount;
891   rc->peer = *peer;
892   rc->rcb = rcb;
893   rc->rcb_cls = rcb_cls;
894   if ((rcb != NULL) && (amount > 0))
895     rc->undo = GNUNET_YES;
896   GNUNET_CONTAINER_DLL_insert_tail (ph->reservation_head, ph->reservation_tail,
897                                     rc);
898
899   p = GNUNET_malloc (sizeof (struct PendingMessage) +
900                      sizeof (struct ReservationRequestMessage));
901   p->size = sizeof (struct ReservationRequestMessage);
902   p->is_init = GNUNET_NO;
903   m = (struct ReservationRequestMessage *) &p[1];
904   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST);
905   m->header.size = htons (sizeof (struct ReservationRequestMessage));
906   m->amount = htonl (amount);
907   m->peer = *peer;
908   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
909   do_transmit (ph);
910   return rc;
911 }
912
913
914 /**
915  * Cancel request for reserving bandwidth.
916  *
917  * @param rc context returned by the original GNUNET_ATS_reserve_bandwidth call
918  */
919 void
920 GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc)
921 {
922   rc->rcb = NULL;
923 }
924
925 /**
926  * Get information about addresses known to the ATS subsystem.
927  *
928  * @param handle the performance handle to use
929  * @param peer peer idm can be NULL for all peers
930  * @param all GNUNET_YES to get information about all addresses or GNUNET_NO to
931  *        get only address currently used
932  * @param infocb callback to call with the addresses,
933  *        will callback with address == NULL when done
934  * @param infocb_cls closure for infocb
935  * @return ats performance context
936  */
937 struct GNUNET_ATS_AddressListHandle*
938 GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *handle,
939                                        const struct GNUNET_PeerIdentity *peer,
940                                        int all,
941                                        GNUNET_ATS_AddressInformationCallback infocb,
942                                        void *infocb_cls)
943 {
944   struct GNUNET_ATS_AddressListHandle *alh;
945   struct PendingMessage *p;
946   struct AddressListRequestMessage *m;
947
948   GNUNET_assert (NULL != handle);
949   if (NULL == infocb)
950     return NULL;
951
952   alh = GNUNET_malloc (sizeof (struct GNUNET_ATS_AddressListHandle));
953   alh->id = handle->id;
954   handle->id ++;
955   alh->cb = infocb;
956   alh->cb_cls = infocb_cls;
957   alh->ph = handle;
958   alh->all_addresses = all;
959   if (NULL == peer)
960     alh->all_peers = GNUNET_YES;
961   else
962   {
963       alh->all_peers = GNUNET_NO;
964       alh->peer = (*peer);
965   }
966
967   GNUNET_CONTAINER_DLL_insert (handle->addresslist_head, handle->addresslist_tail, alh);
968
969   p = GNUNET_malloc (sizeof (struct PendingMessage) +
970                      sizeof (struct AddressListRequestMessage));
971   p->size = sizeof (struct AddressListRequestMessage);
972   m = (struct AddressListRequestMessage *) &p[1];
973   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST);
974   m->header.size = htons (sizeof (struct AddressListRequestMessage));
975   m->all = htonl (all);
976   m->id = htonl (alh->id);
977   if (NULL != peer)
978     m->peer = *peer;
979   else
980   {
981       memset (&m->peer, '\0', sizeof (struct GNUNET_PeerIdentity));
982   }
983   GNUNET_CONTAINER_DLL_insert_tail (handle->pending_head, handle->pending_tail, p);
984
985   do_transmit (handle);
986
987   return alh;
988 }
989
990
991 /**
992  * Cancel a pending address listing operation
993  *
994  * @param handle the GNUNET_ATS_AddressListHandle handle to cancel
995  */
996 void
997 GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandle *handle)
998 {
999   GNUNET_assert (NULL != handle);
1000
1001   GNUNET_CONTAINER_DLL_remove (handle->ph->addresslist_head, handle->ph->addresslist_tail, handle);
1002   GNUNET_free (handle);
1003 }
1004
1005
1006 /**
1007  * Convert a GNUNET_ATS_PreferenceType to a string
1008  *
1009  * @param type the preference type
1010  * @return a string or NULL if invalid
1011  */
1012 const char *
1013 GNUNET_ATS_print_preference_type (uint32_t type)
1014 {
1015   char *prefs[GNUNET_ATS_PreferenceCount] = GNUNET_ATS_PreferenceTypeString;
1016   if (type < GNUNET_ATS_PreferenceCount)
1017     return prefs[type];
1018   return NULL;
1019 }
1020
1021
1022 /**
1023  * Change preferences for the given peer. Preference changes are forgotten if peers
1024  * disconnect.
1025  *
1026  * @param ph performance handle
1027  * @param peer identifies the peer
1028  * @param ... 0-terminated specification of the desired changes
1029  */
1030 void
1031 GNUNET_ATS_change_preference (struct GNUNET_ATS_PerformanceHandle *ph,
1032                               const struct GNUNET_PeerIdentity *peer, ...)
1033 {
1034   struct PendingMessage *p;
1035   struct ChangePreferenceMessage *m;
1036   size_t msize;
1037   uint32_t count;
1038   struct PreferenceInformation *pi;
1039   va_list ap;
1040   enum GNUNET_ATS_PreferenceKind kind;
1041
1042   count = 0;
1043   va_start (ap, peer);
1044   while (GNUNET_ATS_PREFERENCE_END !=
1045          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1046   {
1047     switch (kind)
1048     {
1049     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1050       count++;
1051       (void) va_arg (ap, double);
1052
1053       break;
1054     case GNUNET_ATS_PREFERENCE_LATENCY:
1055       count++;
1056       (void) va_arg (ap, double);
1057
1058       break;
1059     default:
1060       GNUNET_assert (0);
1061     }
1062   }
1063   va_end (ap);
1064   msize =
1065       count * sizeof (struct PreferenceInformation) +
1066       sizeof (struct ChangePreferenceMessage);
1067   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1068   p->size = msize;
1069   p->is_init = GNUNET_NO;
1070   m = (struct ChangePreferenceMessage *) &p[1];
1071   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE);
1072   m->header.size = htons (msize);
1073   m->num_preferences = htonl (count);
1074   m->peer = *peer;
1075   pi = (struct PreferenceInformation *) &m[1];
1076   count = 0;
1077   va_start (ap, peer);
1078   while (GNUNET_ATS_PREFERENCE_END !=
1079          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1080   {
1081     pi[count].preference_kind = htonl (kind);
1082     switch (kind)
1083     {
1084     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1085       pi[count].preference_value = (float) va_arg (ap, double);
1086
1087       count++;
1088       break;
1089     case GNUNET_ATS_PREFERENCE_LATENCY:
1090       pi[count].preference_value = (float) va_arg (ap, double);
1091
1092       count++;
1093       break;
1094     default:
1095       GNUNET_assert (0);
1096     }
1097   }
1098   va_end (ap);
1099   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
1100   do_transmit (ph);
1101 }
1102
1103 /* end of ats_api_performance.c */