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