changes
[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         msg_size = ntohs (msg->size);
586         if (msg_size < sizeof (struct MonitorResponseMessage))
587                 return GNUNET_SYSERR;
588
589         ats_count = ntohl (mrm->ats_count);
590         if (msg_size != (sizeof (struct MonitorResponseMessage) +
591                         ats_count * sizeof (struct GNUNET_ATS_Information)))
592                 return GNUNET_SYSERR;
593
594         id = ntohl (mrm->id);
595         /* Do work here */
596         for (cur = ph->monitor_head; NULL != cur; cur = cur->next)
597         {
598                         if (id == cur->id)
599                                 break;
600         }
601
602         if (NULL == cur)
603                 return GNUNET_SYSERR;
604
605         ats = (struct GNUNET_ATS_Information *) &mrm[1];
606         cur->moncb (cur->moncb_cls, &mrm->peer, ats, ats_count);
607
608         return GNUNET_OK;
609 }
610
611
612 /**
613  * Type of a function to call when we receive a message
614  * from the service.
615  *
616  * @param cls the 'struct GNUNET_ATS_SchedulingHandle'
617  * @param msg message received, NULL on timeout or fatal error
618  */
619 static void
620 process_ats_message (void *cls, const struct GNUNET_MessageHeader *msg)
621 {
622   struct GNUNET_ATS_PerformanceHandle *ph = cls;
623
624   if (NULL == msg)
625     goto reconnect;
626   switch (ntohs (msg->type))
627   {
628   case GNUNET_MESSAGE_TYPE_ATS_PEER_INFORMATION:
629     if (GNUNET_OK != process_pi_message (ph, msg))
630       goto reconnect;
631     break;
632   case GNUNET_MESSAGE_TYPE_ATS_RESERVATION_RESULT:
633     if (GNUNET_OK != process_rr_message (ph, msg))
634       goto reconnect;
635     break;
636   case GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_RESPONSE:
637     if (GNUNET_OK != process_ar_message (ph, msg))
638       goto reconnect;
639     break;
640   case GNUNET_MESSAGE_TYPE_ATS_MONITOR_RESPONSE:
641     if (GNUNET_OK != process_mr_message (ph, msg))
642       goto reconnect;
643     break;
644   default:
645     GNUNET_break (0);
646     goto reconnect;
647   }
648   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
649                          GNUNET_TIME_UNIT_FOREVER_REL);
650   return;
651 reconnect:
652   if (NULL != ph->th)
653   {
654     GNUNET_CLIENT_notify_transmit_ready_cancel (ph->th);
655     ph->th = NULL;
656   }
657   GNUNET_CLIENT_disconnect (ph->client);
658   ph->client = NULL;
659   ph->task =
660       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, &reconnect_task,
661                                     ph);
662 }
663
664
665 /**
666  * Re-establish the connection to the ATS service.
667  *
668  * @param ph handle to use to re-connect.
669  */
670 static void
671 reconnect (struct GNUNET_ATS_PerformanceHandle *ph)
672 {
673   struct PendingMessage *p;
674   struct ClientStartMessage *init;
675
676   GNUNET_assert (NULL == ph->client);
677   ph->client = GNUNET_CLIENT_connect ("ats", ph->cfg);
678   GNUNET_assert (NULL != ph->client);
679   GNUNET_CLIENT_receive (ph->client, &process_ats_message, ph,
680                          GNUNET_TIME_UNIT_FOREVER_REL);
681   if ((NULL == (p = ph->pending_head)) || (GNUNET_YES != p->is_init))
682   {
683     p = GNUNET_malloc (sizeof (struct PendingMessage) +
684                        sizeof (struct ClientStartMessage));
685     p->size = sizeof (struct ClientStartMessage);
686     p->is_init = GNUNET_YES;
687     init = (struct ClientStartMessage *) &p[1];
688     init->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_START);
689     init->header.size = htons (sizeof (struct ClientStartMessage));
690     init->start_flag =
691         htonl ((ph->infocb ==
692                 NULL) ? START_FLAG_PERFORMANCE_NO_PIC :
693                START_FLAG_PERFORMANCE_WITH_PIC);
694     GNUNET_CONTAINER_DLL_insert (ph->pending_head, ph->pending_tail, p);
695   }
696   do_transmit (ph);
697 }
698
699
700
701 /**
702  * Get handle to access performance API of the ATS subsystem.
703  *
704  * @param cfg configuration to use
705  * @param infocb function to call on allocation changes, can be NULL
706  * @param infocb_cls closure for infocb
707  * @return ats performance context
708  */
709 struct GNUNET_ATS_PerformanceHandle *
710 GNUNET_ATS_performance_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
711                              GNUNET_ATS_AddressInformationCallback infocb,
712                              void *infocb_cls)
713 {
714   struct GNUNET_ATS_PerformanceHandle *ph;
715
716   ph = GNUNET_malloc (sizeof (struct GNUNET_ATS_PerformanceHandle));
717   ph->cfg = cfg;
718   ph->infocb = infocb;
719   ph->infocb_cls = infocb_cls;
720   ph->id  = 0;
721   reconnect (ph);
722   return ph;
723 }
724
725
726 /**
727  * Start monitoring performance information
728  *
729  * @param ph performance handle to use
730  * @param monitor_cb function to call on performance changes
731  * @param monitor_cb_cls closure for infocb
732  * @return a performance monitor handle
733  */
734 struct GNUNET_ATS_PerformanceMonitorHandle *
735 GNUNET_ATS_performance_monitor_start (struct GNUNET_ATS_PerformanceHandle * ph,
736                                                                                                                                                         GNUNET_ATS_PerformanceMonitorCb monitor_cb,
737                                                                                                                                                         void * monitor_cb_cls)
738 {
739         struct MonitorMessage *m;
740         struct PendingMessage *p;
741         GNUNET_assert (NULL != ph);
742
743         struct GNUNET_ATS_PerformanceMonitorHandle *phm =
744                         GNUNET_malloc (sizeof (struct GNUNET_ATS_PerformanceMonitorHandle));
745
746         ph->monitor_id ++;
747         phm->id = ph->monitor_id;
748         phm->ph = ph;
749         phm->moncb = monitor_cb;
750         phm->moncb_cls = monitor_cb_cls;
751         GNUNET_CONTAINER_DLL_insert (ph->monitor_head, ph->monitor_tail, phm);
752
753   p = GNUNET_malloc (sizeof (struct PendingMessage) +
754                      sizeof (struct MonitorMessage));
755   p->size = sizeof (struct MonitorMessage);
756   m = (struct MonitorMessage *) &p[1];
757   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_MONITOR);
758   m->header.size = htons (sizeof (struct MonitorMessage));
759   m->id = htonl (phm->id);
760   m->op = htonl (GNUNET_YES);
761   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
762   do_transmit (ph);
763
764         return phm;
765 }
766
767
768 /**
769  * Stop monitoring performance information
770  *
771  * @param ph performance handle to use
772  * @param monitor_cb function to call on performance changes
773  * @param monitor_cb_cls closure for infocb
774  * @return a performance monitor handle
775  */
776 void
777 GNUNET_ATS_performance_monitor_stop (struct GNUNET_ATS_PerformanceMonitorHandle * phm)
778 {
779         struct MonitorMessage *m;
780         struct PendingMessage *p;
781
782         GNUNET_assert (NULL != phm);
783
784   p = GNUNET_malloc (sizeof (struct PendingMessage) +
785                      sizeof (struct MonitorMessage));
786   p->size = sizeof (struct MonitorMessage);
787   m = (struct MonitorMessage *) &p[1];
788   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_MONITOR);
789   m->header.size = htons (sizeof (struct MonitorMessage));
790   m->id = htonl (phm->id);
791   m->op = htonl (GNUNET_NO);
792   GNUNET_CONTAINER_DLL_insert_tail (phm->ph->pending_head, phm->ph->pending_tail, p);
793   do_transmit (phm->ph);
794
795         GNUNET_CONTAINER_DLL_remove (phm->ph->monitor_head, phm->ph->monitor_tail, phm);
796         GNUNET_free (phm);
797 }
798
799 /**
800  * Client is done using the ATS performance subsystem, release resources.
801  *
802  * @param ph handle
803  */
804 void
805 GNUNET_ATS_performance_done (struct GNUNET_ATS_PerformanceHandle *ph)
806 {
807   struct PendingMessage *p;
808   struct GNUNET_ATS_ReservationContext *rc;
809   struct GNUNET_ATS_AddressListHandle *alh;
810   struct GNUNET_ATS_PerformanceMonitorHandle *phm;
811
812   while (NULL != (p = ph->pending_head))
813   {
814     GNUNET_CONTAINER_DLL_remove (ph->pending_head, ph->pending_tail, p);
815     GNUNET_free (p);
816   }
817   while (NULL != (alh = ph->addresslist_head))
818   {
819     GNUNET_CONTAINER_DLL_remove (ph->addresslist_head, ph->addresslist_tail,
820                                  alh);
821     GNUNET_free (alh);
822   }
823   while (NULL != (rc = ph->reservation_head))
824   {
825     GNUNET_CONTAINER_DLL_remove (ph->reservation_head, ph->reservation_tail,
826                                  rc);
827     GNUNET_break (NULL == rc->rcb);
828     GNUNET_free (rc);
829   }
830   while (NULL != (phm = ph->monitor_head))
831   {
832     GNUNET_CONTAINER_DLL_remove (ph->monitor_head, ph->monitor_tail, phm);
833     GNUNET_free (phm);
834   }
835   if (GNUNET_SCHEDULER_NO_TASK != ph->task)
836   {
837     GNUNET_SCHEDULER_cancel (ph->task);
838     ph->task = GNUNET_SCHEDULER_NO_TASK;
839   }
840   if (NULL != ph->client)
841   {
842     GNUNET_CLIENT_disconnect (ph->client);
843     ph->client = NULL;
844   }
845   GNUNET_free (ph);
846 }
847
848
849 /**
850  * Reserve inbound bandwidth from the given peer.  ATS will look at
851  * the current amount of traffic we receive from the peer and ensure
852  * that the peer could add 'amount' of data to its stream.
853  *
854  * @param ph performance handle
855  * @param peer identifies the peer
856  * @param amount reserve N bytes for receiving, negative
857  *                amounts can be used to undo a (recent) reservation;
858  * @param rcb function to call with the resulting reservation information
859  * @param rcb_cls closure for info
860  * @return NULL on error
861  * @deprecated will be replaced soon
862  */
863 struct GNUNET_ATS_ReservationContext *
864 GNUNET_ATS_reserve_bandwidth (struct GNUNET_ATS_PerformanceHandle *ph,
865                               const struct GNUNET_PeerIdentity *peer,
866                               int32_t amount,
867                               GNUNET_ATS_ReservationCallback rcb, void *rcb_cls)
868 {
869   struct GNUNET_ATS_ReservationContext *rc;
870   struct PendingMessage *p;
871   struct ReservationRequestMessage *m;
872
873   rc = GNUNET_malloc (sizeof (struct GNUNET_ATS_ReservationContext));
874   rc->size = amount;
875   rc->peer = *peer;
876   rc->rcb = rcb;
877   rc->rcb_cls = rcb_cls;
878   if ((rcb != NULL) && (amount > 0))
879     rc->undo = GNUNET_YES;
880   GNUNET_CONTAINER_DLL_insert_tail (ph->reservation_head, ph->reservation_tail,
881                                     rc);
882
883   p = GNUNET_malloc (sizeof (struct PendingMessage) +
884                      sizeof (struct ReservationRequestMessage));
885   p->size = sizeof (struct ReservationRequestMessage);
886   p->is_init = GNUNET_NO;
887   m = (struct ReservationRequestMessage *) &p[1];
888   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_RESERVATION_REQUEST);
889   m->header.size = htons (sizeof (struct ReservationRequestMessage));
890   m->amount = htonl (amount);
891   m->peer = *peer;
892   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
893   do_transmit (ph);
894   return rc;
895 }
896
897
898 /**
899  * Cancel request for reserving bandwidth.
900  *
901  * @param rc context returned by the original GNUNET_ATS_reserve_bandwidth call
902  */
903 void
904 GNUNET_ATS_reserve_bandwidth_cancel (struct GNUNET_ATS_ReservationContext *rc)
905 {
906   rc->rcb = NULL;
907 }
908
909 /**
910  * Get information about addresses known to the ATS subsystem.
911  *
912  * @param handle the performance handle to use
913  * @param peer peer idm can be NULL for all peers
914  * @param all GNUNET_YES to get information about all addresses or GNUNET_NO to
915  *        get only address currently used
916  * @param infocb callback to call with the addresses,
917  *        will callback with address == NULL when done
918  * @param infocb_cls closure for infocb
919  * @return ats performance context
920  */
921 struct GNUNET_ATS_AddressListHandle*
922 GNUNET_ATS_performance_list_addresses (struct GNUNET_ATS_PerformanceHandle *handle,
923                                        const struct GNUNET_PeerIdentity *peer,
924                                        int all,
925                                        GNUNET_ATS_AddressInformationCallback infocb,
926                                        void *infocb_cls)
927 {
928   struct GNUNET_ATS_AddressListHandle *alh;
929   struct PendingMessage *p;
930   struct AddressListRequestMessage *m;
931
932   GNUNET_assert (NULL != handle);
933   if (NULL == infocb)
934     return NULL;
935
936   alh = GNUNET_malloc (sizeof (struct GNUNET_ATS_AddressListHandle));
937   alh->id = handle->id;
938   handle->id ++;
939   alh->cb = infocb;
940   alh->cb_cls = infocb_cls;
941   alh->ph = handle;
942   alh->all_addresses = all;
943   if (NULL == peer)
944     alh->all_peers = GNUNET_YES;
945   else
946   {
947       alh->all_peers = GNUNET_NO;
948       alh->peer = (*peer);
949   }
950
951   GNUNET_CONTAINER_DLL_insert (handle->addresslist_head, handle->addresslist_tail, alh);
952
953   p = GNUNET_malloc (sizeof (struct PendingMessage) +
954                      sizeof (struct AddressListRequestMessage));
955   p->size = sizeof (struct AddressListRequestMessage);
956   m = (struct AddressListRequestMessage *) &p[1];
957   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_ADDRESSLIST_REQUEST);
958   m->header.size = htons (sizeof (struct AddressListRequestMessage));
959   m->all = htonl (all);
960   m->id = htonl (alh->id);
961   if (NULL != peer)
962     m->peer = *peer;
963   else
964   {
965       memset (&m->peer, '\0', sizeof (struct GNUNET_PeerIdentity));
966   }
967   GNUNET_CONTAINER_DLL_insert_tail (handle->pending_head, handle->pending_tail, p);
968
969   do_transmit (handle);
970
971   return alh;
972 }
973
974
975 /**
976  * Cancel a pending address listing operation
977  *
978  * @param handle the GNUNET_ATS_AddressListHandle handle to cancel
979  */
980 void
981 GNUNET_ATS_performance_list_addresses_cancel (struct GNUNET_ATS_AddressListHandle *handle)
982 {
983   GNUNET_assert (NULL != handle);
984
985   GNUNET_CONTAINER_DLL_remove (handle->ph->addresslist_head, handle->ph->addresslist_tail, handle);
986   GNUNET_free (handle);
987 }
988
989
990 /**
991  * Convert a GNUNET_ATS_PreferenceType to a string
992  *
993  * @param type the preference type
994  * @return a string or NULL if invalid
995  */
996 const char *
997 GNUNET_ATS_print_preference_type (uint32_t type)
998 {
999   char *prefs[GNUNET_ATS_PreferenceCount] = GNUNET_ATS_PreferenceTypeString;
1000   if (type < GNUNET_ATS_PreferenceCount)
1001     return prefs[type];
1002   return NULL;
1003 }
1004
1005
1006 /**
1007  * Change preferences for the given peer. Preference changes are forgotten if peers
1008  * disconnect.
1009  *
1010  * @param ph performance handle
1011  * @param peer identifies the peer
1012  * @param ... 0-terminated specification of the desired changes
1013  */
1014 void
1015 GNUNET_ATS_change_preference (struct GNUNET_ATS_PerformanceHandle *ph,
1016                               const struct GNUNET_PeerIdentity *peer, ...)
1017 {
1018   struct PendingMessage *p;
1019   struct ChangePreferenceMessage *m;
1020   size_t msize;
1021   uint32_t count;
1022   struct PreferenceInformation *pi;
1023   va_list ap;
1024   enum GNUNET_ATS_PreferenceKind kind;
1025
1026   count = 0;
1027   va_start (ap, peer);
1028   while (GNUNET_ATS_PREFERENCE_END !=
1029          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1030   {
1031     switch (kind)
1032     {
1033     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1034       count++;
1035       (void) va_arg (ap, double);
1036
1037       break;
1038     case GNUNET_ATS_PREFERENCE_LATENCY:
1039       count++;
1040       (void) va_arg (ap, double);
1041
1042       break;
1043     default:
1044       GNUNET_assert (0);
1045     }
1046   }
1047   va_end (ap);
1048   msize =
1049       count * sizeof (struct PreferenceInformation) +
1050       sizeof (struct ChangePreferenceMessage);
1051   p = GNUNET_malloc (sizeof (struct PendingMessage) + msize);
1052   p->size = msize;
1053   p->is_init = GNUNET_NO;
1054   m = (struct ChangePreferenceMessage *) &p[1];
1055   m->header.type = htons (GNUNET_MESSAGE_TYPE_ATS_PREFERENCE_CHANGE);
1056   m->header.size = htons (msize);
1057   m->num_preferences = htonl (count);
1058   m->peer = *peer;
1059   pi = (struct PreferenceInformation *) &m[1];
1060   count = 0;
1061   va_start (ap, peer);
1062   while (GNUNET_ATS_PREFERENCE_END !=
1063          (kind = va_arg (ap, enum GNUNET_ATS_PreferenceKind)))
1064   {
1065     pi[count].preference_kind = htonl (kind);
1066     switch (kind)
1067     {
1068     case GNUNET_ATS_PREFERENCE_BANDWIDTH:
1069       pi[count].preference_value = (float) va_arg (ap, double);
1070
1071       count++;
1072       break;
1073     case GNUNET_ATS_PREFERENCE_LATENCY:
1074       pi[count].preference_value = (float) va_arg (ap, double);
1075
1076       count++;
1077       break;
1078     default:
1079       GNUNET_assert (0);
1080     }
1081   }
1082   va_end (ap);
1083   GNUNET_CONTAINER_DLL_insert_tail (ph->pending_head, ph->pending_tail, p);
1084   do_transmit (ph);
1085 }
1086
1087 /* end of ats_api_performance.c */