ec0b52fe1c772d6cb78fda02fb9c8d697fa274e0
[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 phm performance monitor handle to use
788  */
789 void
790 GNUNET_ATS_performance_monitor_stop (struct GNUNET_ATS_PerformanceMonitorHandle * phm)
791 {
792         struct MonitorMessage *m;
793         struct PendingMessage *p;
794
795         GNUNET_assert (NULL != phm);
796
797   p = GNUNET_malloc (sizeof (struct PendingMessage) +
798                      sizeof (struct MonitorMessage));
799   p->size = sizeof (struct MonitorMessage);
800   m = (struct MonitorMessage *) &p[1];
801   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_MONITOR);
802   m->header.size = htons (sizeof (struct MonitorMessage));
803   m->id = htonl (phm->id);
804   m->op = htonl (GNUNET_NO);
805   GNUNET_CONTAINER_DLL_insert_tail (phm->ph->pending_head, phm->ph->pending_tail, p);
806   do_transmit (phm->ph);
807
808         GNUNET_CONTAINER_DLL_remove (phm->ph->monitor_head, phm->ph->monitor_tail, phm);
809         GNUNET_free (phm);
810 }
811
812 /**
813  * Client is done using the ATS performance subsystem, release resources.
814  *
815  * @param ph handle
816  */
817 void
818 GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph)
819 {
820   struct PendingMessage *p;
821   struct GNUNET_ATS_ReservationContext *rc;
822   struct GNUNET_ATS_AddressListHandle *alh;
823   struct GNUNET_ATS_PerformanceMonitorHandle *phm;
824
825   while (NULL != (p = ph->pending_head))
826   {
827     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
828     GNUNET_free (p);
829   }
830   while (NULL != (alh = ph->addresslist_head))
831   {
832     GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, ph->addresslist_tail,
833                                  alh);
834     GNUNET_free (alh);
835   }
836   while (NULL != (rc = ph->reservation_head))
837   {
838     GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail,
839                                  rc);
840     GNUNET_break (NULL == rc->rcb);
841     GNUNET_free (rc);
842   }
843   while (NULL != (phm = ph->monitor_head))
844   {
845     GNUNET_CONTAINER_DLL_remove (ph->monitor_head, ph->monitor_tail, phm);
846     GNUNET_free (phm);
847   }
848   if (GNUNET_SCHEDULER_NO_TASK != ph->task)
849   {
850     GNUNET_SCHEDULER_cancel (ph->task);
851     ph->task = GNUNET_SCHEDULER_NO_TASK;
852   }
853   if (NULL != ph->client)
854   {
855     GNUNET_CLIENT_disconnect (ph->client);
856     ph->client = NULL;
857   }
858   GNUNET_free (ph);
859 }
860
861
862 /**
863  * Reserve inbound bandwidth from the given peer.  ATS will look at
864  * the current amount of traffic we receive from the peer and ensure
865  * that the peer could add 'amount' of data to its stream.
866  *
867  * @param ph performance handle
868  * @param peer identifies the peer
869  * @param amount reserve N bytes for receiving, negative
870  *                amounts can be used to undo a (recent) reservation;
871  * @param rcb function to call with the resulting reservation information
872  * @param rcb_cls closure for info
873  * @return NULL on error
874  * @deprecated will be replaced soon
875  */
876 struct GNUNET_ATS_ReservationContext *
877 GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph,
878                               const struct GNUNET_PeerIdentity *peer,
879                               int32_t amount,
880                               GNUNET_ATS_ReservationCallback rcb, void *rcb_cls)
881 {
882   struct GNUNET_ATS_ReservationContext *rc;
883   struct PendingMessage *p;
884   struct ReservationRequestMessage *m;
885
886   rc = GNUNET_malloc (sizeof (struct GNUNET_ATS_ReservationContext));
887   rc->size = amount;
888   rc->peer = *peer;
889   rc->rcb = rcb;
890   rc->rcb_cls = rcb_cls;
891   if ((rcb != NULL) && (amount > 0))
892     rc->undo = GNUNET_YES;
893   GNUNET_CONTAINER_DLL_insert_tail (ph->reservation_head, ph->reservation_tail,
894                                     rc);
895
896   p = GNUNET_malloc (sizeof (struct PendingMessage) +
897                      sizeof (struct ReservationRequestMessage));
898   p->size = sizeof (struct ReservationRequestMessage);
899   p->is_init = GNUNET_NO;
900   m = (struct ReservationRequestMessage *) &p[1];
901   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST);
902   m->header.size = htons (sizeof (struct ReservationRequestMessage));
903   m->amount = htonl (amount);
904   m->peer = *peer;
905   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
906   do_transmit (ph);
907   return rc;
908 }
909
910
911 /**
912  * Cancel request for reserving bandwidth.
913  *
914  * @param rc context returned by the original GNUNET_ATS_reserve_bandwidth call
915  */
916 void
917 GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc)
918 {
919   rc->rcb = NULL;
920 }
921
922 /**
923  * Get information about addresses known to the ATS subsystem.
924  *
925  * @param handle the performance handle to use
926  * @param peer peer idm can be NULL for all peers
927  * @param all GNUNET_YES to get information about all addresses or GNUNET_NO to
928  *        get only address currently used
929  * @param infocb callback to call with the addresses,
930  *        will callback with address == NULL when done
931  * @param infocb_cls closure for infocb
932  * @return ats performance context
933  */
934 struct GNUNET_ATS_AddressListHandle*
935 GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *handle,
936                                        const struct GNUNET_PeerIdentity *peer,
937                                        int all,
938                                        GNUNET_ATS_AddressInformationCallback infocb,
939                                        void *infocb_cls)
940 {
941   struct GNUNET_ATS_AddressListHandle *alh;
942   struct PendingMessage *p;
943   struct AddressListRequestMessage *m;
944
945   GNUNET_assert (NULL != handle);
946   if (NULL == infocb)
947     return NULL;
948
949   alh = GNUNET_malloc (sizeof (struct GNUNET_ATS_AddressListHandle));
950   alh->id = handle->id;
951   handle->id ++;
952   alh->cb = infocb;
953   alh->cb_cls = infocb_cls;
954   alh->ph = handle;
955   alh->all_addresses = all;
956   if (NULL == peer)
957     alh->all_peers = GNUNET_YES;
958   else
959   {
960       alh->all_peers = GNUNET_NO;
961       alh->peer = (*peer);
962   }
963
964   GNUNET_CONTAINER_DLL_insert (handle->addresslist_head, handle->addresslist_tail, alh);
965
966   p = GNUNET_malloc (sizeof (struct PendingMessage) +
967                      sizeof (struct AddressListRequestMessage));
968   p->size = sizeof (struct AddressListRequestMessage);
969   m = (struct AddressListRequestMessage *) &p[1];
970   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST);
971   m->header.size = htons (sizeof (struct AddressListRequestMessage));
972   m->all = htonl (all);
973   m->id = htonl (alh->id);
974   if (NULL != peer)
975     m->peer = *peer;
976   else
977   {
978       memset (&m->peer, '\0', sizeof (struct GNUNET_PeerIdentity));
979   }
980   GNUNET_CONTAINER_DLL_insert_tail (handle->pending_head, handle->pending_tail, p);
981
982   do_transmit (handle);
983
984   return alh;
985 }
986
987
988 /**
989  * Cancel a pending address listing operation
990  *
991  * @param handle the GNUNET_ATS_AddressListHandle handle to cancel
992  */
993 void
994 GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandle *handle)
995 {
996   GNUNET_assert (NULL != handle);
997
998   GNUNET_CONTAINER_DLL_remove (handle->ph->addresslist_head, handle->ph->addresslist_tail, handle);
999   GNUNET_free (handle);
1000 }
1001
1002
1003 /**
1004  * Convert a GNUNET_ATS_PreferenceType to a string
1005  *
1006  * @param type the preference type
1007  * @return a string or NULL if invalid
1008  */
1009 const char *
1010 GNUNET_ATS_print_preference_type (uint32_t type)
1011 {
1012   char *prefs[GNUNET_ATS_PreferenceCount] = GNUNET_ATS_PreferenceTypeString;
1013   if (type < GNUNET_ATS_PreferenceCount)
1014     return prefs[type];
1015   return NULL;
1016 }
1017
1018
1019 /**
1020  * Change preferences for the given peer. Preference changes are forgotten if peers
1021  * disconnect.
1022  *
1023  * @param ph performance handle
1024  * @param peer identifies the peer
1025  * @param ... 0-terminated specification of the desired changes
1026  */
1027 void
1028 GNUNET_ATS_change_preference (struct GNUNET_ATS_PerformanceHandle *ph,
1029                               const struct GNUNET_PeerIdentity *peer, ...)
1030 {
1031   struct PendingMessage *p;
1032   struct ChangePreferenceMessage *m;
1033   size_t msize;
1034   uint32_t count;
1035   struct PreferenceInformation *pi;
1036   va_list ap;
1037   enum GNUNET_ATS_PreferenceKind kind;
1038
1039   count = 0;
1040   va_start (ap, peer);
1041   while (GNUNET_ATS_PREFERENCE_END !=
1042          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1043   {
1044     switch (kind)
1045     {
1046     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1047       count++;
1048       (void) va_arg (ap, double);
1049
1050       break;
1051     case GNUNET_ATS_PREFERENCE_LATENCY:
1052       count++;
1053       (void) va_arg (ap, double);
1054
1055       break;
1056     default:
1057       GNUNET_assert (0);
1058     }
1059   }
1060   va_end (ap);
1061   msize =
1062       count * sizeof (struct PreferenceInformation) +
1063       sizeof (struct ChangePreferenceMessage);
1064   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1065   p->size = msize;
1066   p->is_init = GNUNET_NO;
1067   m = (struct ChangePreferenceMessage *) &p[1];
1068   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE);
1069   m->header.size = htons (msize);
1070   m->num_preferences = htonl (count);
1071   m->peer = *peer;
1072   pi = (struct PreferenceInformation *) &m[1];
1073   count = 0;
1074   va_start (ap, peer);
1075   while (GNUNET_ATS_PREFERENCE_END !=
1076          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1077   {
1078     pi[count].preference_kind = htonl (kind);
1079     switch (kind)
1080     {
1081     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1082       pi[count].preference_value = (float) va_arg (ap, double);
1083
1084       count++;
1085       break;
1086     case GNUNET_ATS_PREFERENCE_LATENCY:
1087       pi[count].preference_value = (float) va_arg (ap, double);
1088
1089       count++;
1090       break;
1091     default:
1092       GNUNET_assert (0);
1093     }
1094   }
1095   va_end (ap);
1096   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
1097   do_transmit (ph);
1098 }
1099
1100 /* end of ats_api_performance.c */